Upload folder using huggingface_hub
Browse files- mmdet_code/mmdetection/mmdet/models/dense_heads/dala_heads.py +96 -26
- mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__init__.py +7 -2
- mmdet_code/mmdetection/mmdet/models/task_modules/assigners/dala_assigner.py +141 -3
- mmdet_code/mmdetection/projects/EfficientDet/README.md +26 -0
- mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.py +9 -0
- mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.py +8 -0
- mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.py +9 -0
- mmdet_code/train_all_levir_baseline.py +17 -1
mmdet_code/mmdetection/mmdet/models/dense_heads/dala_heads.py
CHANGED
|
@@ -8,7 +8,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
|
|
@@ -32,6 +32,41 @@ class DalaAnchorTargetMixin:
|
|
| 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,
|
|
@@ -39,23 +74,63 @@ class DalaAnchorTargetMixin:
|
|
| 39 |
img_meta: dict,
|
| 40 |
gt_instances_ignore: Optional[InstanceData] = None,
|
| 41 |
unmap_outputs: bool = True) -> tuple:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 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)
|
|
@@ -63,15 +138,10 @@ class DalaAnchorTargetMixin:
|
|
| 63 |
label_weights[pos_inds] = pos_weights
|
| 64 |
bbox_weights[pos_inds] = pos_weights[:, None]
|
| 65 |
negative_weight = pos_weights.mean()
|
| 66 |
-
|
| 67 |
-
|
| 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)
|
|
@@ -80,8 +150,8 @@ class DalaAnchorTargetMixin:
|
|
| 80 |
bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
|
| 81 |
bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
|
| 86 |
|
| 87 |
@MODELS.register_module()
|
|
|
|
| 8 |
from torch import Tensor
|
| 9 |
|
| 10 |
from mmdet.registry import MODELS
|
| 11 |
+
from mmdet.structures.bbox import BaseBoxes, get_box_tensor
|
| 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
|
|
|
|
| 32 |
self.use_dwl = use_dwl
|
| 33 |
super().__init__(**kwargs)
|
| 34 |
|
| 35 |
+
def get_targets(self,
|
| 36 |
+
anchor_list: List[List[Tensor]],
|
| 37 |
+
valid_flag_list: List[List[Tensor]],
|
| 38 |
+
batch_gt_instances: InstanceList,
|
| 39 |
+
batch_img_metas: List[dict],
|
| 40 |
+
batch_gt_instances_ignore: OptInstanceList = None,
|
| 41 |
+
unmap_outputs: bool = True,
|
| 42 |
+
return_sampling_results: bool = False) -> tuple:
|
| 43 |
+
"""Preserve FPN boundaries while the base head flattens anchors."""
|
| 44 |
+
if not anchor_list:
|
| 45 |
+
return super().get_targets(
|
| 46 |
+
anchor_list,
|
| 47 |
+
valid_flag_list,
|
| 48 |
+
batch_gt_instances,
|
| 49 |
+
batch_img_metas,
|
| 50 |
+
batch_gt_instances_ignore,
|
| 51 |
+
unmap_outputs,
|
| 52 |
+
return_sampling_results)
|
| 53 |
+
if hasattr(self, '_dala_num_level_anchors'):
|
| 54 |
+
raise RuntimeError('DALA target generation is not re-entrant')
|
| 55 |
+
self._dala_num_level_anchors = [
|
| 56 |
+
anchors.size(0) for anchors in anchor_list[0]
|
| 57 |
+
]
|
| 58 |
+
try:
|
| 59 |
+
return super().get_targets(
|
| 60 |
+
anchor_list,
|
| 61 |
+
valid_flag_list,
|
| 62 |
+
batch_gt_instances,
|
| 63 |
+
batch_img_metas,
|
| 64 |
+
batch_gt_instances_ignore,
|
| 65 |
+
unmap_outputs,
|
| 66 |
+
return_sampling_results)
|
| 67 |
+
finally:
|
| 68 |
+
del self._dala_num_level_anchors
|
| 69 |
+
|
| 70 |
def _get_targets_single(self,
|
| 71 |
flat_anchors: Union[Tensor, BaseBoxes],
|
| 72 |
valid_flags: Tensor,
|
|
|
|
| 74 |
img_meta: dict,
|
| 75 |
gt_instances_ignore: Optional[InstanceData] = None,
|
| 76 |
unmap_outputs: bool = True) -> tuple:
|
| 77 |
+
inside_flags = anchor_inside_flags(
|
| 78 |
+
flat_anchors, valid_flags, img_meta['img_shape'][:2],
|
| 79 |
+
self.train_cfg['allowed_border'])
|
| 80 |
+
if not inside_flags.any():
|
| 81 |
+
raise ValueError(
|
| 82 |
+
'There is no valid anchor inside the image boundary. Please '
|
| 83 |
+
'check the image size and anchor sizes, or set '
|
| 84 |
+
'``allowed_border`` to -1 to skip the condition.')
|
| 85 |
+
|
| 86 |
+
anchors = flat_anchors[inside_flags]
|
| 87 |
+
pred_instances = InstanceData(priors=anchors)
|
| 88 |
+
num_level_anchors = getattr(self, '_dala_num_level_anchors', None)
|
| 89 |
+
if num_level_anchors is not None:
|
| 90 |
+
if sum(num_level_anchors) != flat_anchors.size(0):
|
| 91 |
+
raise ValueError('num_level_anchors does not match flat priors')
|
| 92 |
+
full_level_ids = torch.cat([
|
| 93 |
+
valid_flags.new_full((count, ), level, dtype=torch.long)
|
| 94 |
+
for level, count in enumerate(num_level_anchors)
|
| 95 |
+
])
|
| 96 |
+
pred_instances.level_ids = full_level_ids[inside_flags]
|
| 97 |
+
|
| 98 |
+
assign_result = self.assigner.assign(pred_instances, gt_instances,
|
| 99 |
+
gt_instances_ignore)
|
| 100 |
+
sampling_result = self.sampler.sample(assign_result, pred_instances,
|
| 101 |
+
gt_instances)
|
| 102 |
+
|
| 103 |
+
num_valid_anchors = anchors.shape[0]
|
| 104 |
+
target_dim = gt_instances.bboxes.size(-1) if self.reg_decoded_bbox \
|
| 105 |
+
else self.bbox_coder.encode_size
|
| 106 |
+
bbox_targets = anchors.new_zeros(num_valid_anchors, target_dim)
|
| 107 |
+
bbox_weights = anchors.new_zeros(num_valid_anchors, target_dim)
|
| 108 |
+
labels = anchors.new_full(
|
| 109 |
+
(num_valid_anchors, ), self.num_classes, dtype=torch.long)
|
| 110 |
+
label_weights = anchors.new_zeros(
|
| 111 |
+
num_valid_anchors, dtype=torch.float)
|
| 112 |
+
|
| 113 |
+
pos_inds = sampling_result.pos_inds
|
| 114 |
+
neg_inds = sampling_result.neg_inds
|
| 115 |
if len(pos_inds) > 0:
|
| 116 |
+
if not self.reg_decoded_bbox:
|
| 117 |
+
pos_bbox_targets = self.bbox_coder.encode(
|
| 118 |
+
sampling_result.pos_priors,
|
| 119 |
+
sampling_result.pos_gt_bboxes)
|
| 120 |
+
else:
|
| 121 |
+
pos_bbox_targets = get_box_tensor(
|
| 122 |
+
sampling_result.pos_gt_bboxes)
|
| 123 |
+
bbox_targets[pos_inds, :] = pos_bbox_targets
|
| 124 |
+
bbox_weights[pos_inds, :] = 1.0
|
| 125 |
+
labels[pos_inds] = sampling_result.pos_gt_labels
|
| 126 |
+
if self.train_cfg['pos_weight'] <= 0:
|
| 127 |
+
label_weights[pos_inds] = 1.0
|
| 128 |
+
else:
|
| 129 |
+
label_weights[pos_inds] = self.train_cfg['pos_weight']
|
| 130 |
+
if len(neg_inds) > 0:
|
| 131 |
+
label_weights[neg_inds] = 1.0
|
| 132 |
+
|
| 133 |
+
if self.use_dwl and len(pos_inds) > 0:
|
| 134 |
gt_bboxes = gt_instances.bboxes.tensor if isinstance(
|
| 135 |
gt_instances.bboxes, BaseBoxes) else gt_instances.bboxes
|
| 136 |
gt_weights = _dwl_gt_weights(gt_bboxes)
|
|
|
|
| 138 |
label_weights[pos_inds] = pos_weights
|
| 139 |
bbox_weights[pos_inds] = pos_weights[:, None]
|
| 140 |
negative_weight = pos_weights.mean()
|
| 141 |
+
if len(neg_inds) > 0:
|
| 142 |
+
label_weights[neg_inds] = negative_weight
|
|
|
|
|
|
|
| 143 |
|
| 144 |
if unmap_outputs:
|
|
|
|
|
|
|
|
|
|
| 145 |
num_total_anchors = flat_anchors.size(0)
|
| 146 |
labels = unmap(
|
| 147 |
labels, num_total_anchors, inside_flags, fill=self.num_classes)
|
|
|
|
| 150 |
bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
|
| 151 |
bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)
|
| 152 |
|
| 153 |
+
return (labels, label_weights, bbox_targets, bbox_weights, pos_inds,
|
| 154 |
+
neg_inds, sampling_result)
|
| 155 |
|
| 156 |
|
| 157 |
@MODELS.register_module()
|
mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__init__.py
CHANGED
|
@@ -5,7 +5,10 @@ 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
|
|
@@ -31,5 +34,7 @@ __all__ = [
|
|
| 31 |
'ClassificationCost', 'CrossEntropyLossCost', 'DiceCost', 'FocalLossCost',
|
| 32 |
'IoUCost', 'BboxOverlaps2D', 'DynamicSoftLabelAssigner',
|
| 33 |
'MultiInstanceAssigner', 'BboxOverlaps2D_GLIP', 'DalaAssigner',
|
| 34 |
-
'DalaPositiveQuota', 'bbox_similarity_distance'
|
|
|
|
|
|
|
| 35 |
]
|
|
|
|
| 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 |
+
geometry_balanced_similarity,
|
| 10 |
+
level_aware_similarity,
|
| 11 |
+
normalized_wasserstein_similarity)
|
| 12 |
from .dynamic_soft_label_assigner import DynamicSoftLabelAssigner
|
| 13 |
from .grid_assigner import GridAssigner
|
| 14 |
from .hungarian_assigner import HungarianAssigner
|
|
|
|
| 34 |
'ClassificationCost', 'CrossEntropyLossCost', 'DiceCost', 'FocalLossCost',
|
| 35 |
'IoUCost', 'BboxOverlaps2D', 'DynamicSoftLabelAssigner',
|
| 36 |
'MultiInstanceAssigner', 'BboxOverlaps2D_GLIP', 'DalaAssigner',
|
| 37 |
+
'DalaPositiveQuota', 'bbox_similarity_distance',
|
| 38 |
+
'geometry_balanced_similarity', 'level_aware_similarity',
|
| 39 |
+
'normalized_wasserstein_similarity'
|
| 40 |
]
|
mmdet_code/mmdetection/mmdet/models/task_modules/assigners/dala_assigner.py
CHANGED
|
@@ -54,6 +54,106 @@ def bbox_similarity_distance(priors: Tensor,
|
|
| 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 |
|
|
@@ -109,12 +209,44 @@ class DalaAssigner(nn.Module, BaseAssigner):
|
|
| 109 |
|
| 110 |
def __init__(self,
|
| 111 |
ignore_iof_thr: float = -1,
|
| 112 |
-
sync_stats: bool = True
|
|
|
|
|
|
|
|
|
|
| 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,
|
|
@@ -124,6 +256,7 @@ class DalaAssigner(nn.Module, BaseAssigner):
|
|
| 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 |
|
|
@@ -154,7 +287,8 @@ class DalaAssigner(nn.Module, BaseAssigner):
|
|
| 154 |
& (centers[:, None, 1] < gt_bboxes[None, :, 3]))
|
| 155 |
inside[ignore_mask] = False
|
| 156 |
|
| 157 |
-
similarities =
|
|
|
|
| 158 |
quotas = self.quota_tracker(inside.sum(dim=0).to(similarities))
|
| 159 |
|
| 160 |
selected_scores = similarities.new_full(similarities.shape, -torch.inf)
|
|
@@ -185,4 +319,8 @@ class DalaAssigner(nn.Module, BaseAssigner):
|
|
| 185 |
num_gts, assigned_gt_inds, max_overlaps, labels=assigned_labels)
|
| 186 |
|
| 187 |
|
| 188 |
-
__all__ = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
return torch.exp(-(location + shape)).clamp_min(eps)
|
| 55 |
|
| 56 |
|
| 57 |
+
def normalized_wasserstein_similarity(priors: Tensor,
|
| 58 |
+
gt_bboxes: Tensor,
|
| 59 |
+
normalizer: float = 32.0,
|
| 60 |
+
eps: float = 1e-7) -> Tensor:
|
| 61 |
+
"""Calculate normalized Wasserstein similarity for S1.
|
| 62 |
+
|
| 63 |
+
Bounding boxes are represented as diagonal Gaussians. The positive
|
| 64 |
+
normalizer only controls score scale; it does not change pairwise ranking.
|
| 65 |
+
"""
|
| 66 |
+
if normalizer <= 0:
|
| 67 |
+
raise ValueError('normalizer must be positive')
|
| 68 |
+
priors = get_box_tensor(priors)[..., :4]
|
| 69 |
+
gt_bboxes = get_box_tensor(gt_bboxes)[..., :4]
|
| 70 |
+
if priors.numel() == 0 or gt_bboxes.numel() == 0:
|
| 71 |
+
return priors.new_zeros((priors.shape[0], gt_bboxes.shape[0]))
|
| 72 |
+
|
| 73 |
+
prior_wh = (priors[:, 2:] - priors[:, :2]).clamp_min(eps)
|
| 74 |
+
gt_wh = (gt_bboxes[:, 2:] - gt_bboxes[:, :2]).clamp_min(eps)
|
| 75 |
+
prior_ctr = (priors[:, :2] + priors[:, 2:]) * 0.5
|
| 76 |
+
gt_ctr = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
|
| 77 |
+
|
| 78 |
+
center_sq = (prior_ctr[:, None, :] -
|
| 79 |
+
gt_ctr[None, :, :]).square().sum(dim=-1)
|
| 80 |
+
shape_sq = ((prior_wh[:, None, :] - gt_wh[None, :, :]) *
|
| 81 |
+
0.5).square().sum(dim=-1)
|
| 82 |
+
distance = (center_sq + shape_sq).clamp_min(0).sqrt()
|
| 83 |
+
return torch.exp(-distance / normalizer).clamp_min(eps)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def geometry_balanced_similarity(priors: Tensor,
|
| 87 |
+
gt_bboxes: Tensor,
|
| 88 |
+
eps: float = 1e-7) -> Tensor:
|
| 89 |
+
"""Calculate S2 Geometry-Balanced SimD.
|
| 90 |
+
|
| 91 |
+
S2 replaces SimD's arithmetic-sum location denominator with twice the
|
| 92 |
+
geometric mean. It is identical to S0 for equal-sized boxes, but prevents
|
| 93 |
+
a much larger anchor from artificially suppressing centre error.
|
| 94 |
+
"""
|
| 95 |
+
priors = get_box_tensor(priors)[..., :4]
|
| 96 |
+
gt_bboxes = get_box_tensor(gt_bboxes)[..., :4]
|
| 97 |
+
if priors.numel() == 0 or gt_bboxes.numel() == 0:
|
| 98 |
+
return priors.new_zeros((priors.shape[0], gt_bboxes.shape[0]))
|
| 99 |
+
|
| 100 |
+
prior_wh = (priors[:, 2:] - priors[:, :2]).clamp_min(eps)
|
| 101 |
+
gt_wh = (gt_bboxes[:, 2:] - gt_bboxes[:, :2]).clamp_min(eps)
|
| 102 |
+
prior_ctr = (priors[:, :2] + priors[:, 2:]) * 0.5
|
| 103 |
+
gt_ctr = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
|
| 104 |
+
|
| 105 |
+
wh_sum = (prior_wh[:, None, :] + gt_wh[None, :, :]).clamp_min(eps)
|
| 106 |
+
location_denom = (2 * torch.sqrt(prior_wh[:, None, :] *
|
| 107 |
+
gt_wh[None, :, :])).clamp_min(eps)
|
| 108 |
+
location = ((prior_ctr[:, None, :] - gt_ctr[None, :, :]) /
|
| 109 |
+
location_denom).square().sum(dim=-1).sqrt()
|
| 110 |
+
shape = ((prior_wh[:, None, :] - gt_wh[None, :, :]) /
|
| 111 |
+
wh_sum).square().sum(dim=-1).sqrt()
|
| 112 |
+
return torch.exp(-(location + shape)).clamp_min(eps)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def level_aware_similarity(priors: Tensor,
|
| 116 |
+
gt_bboxes: Tensor,
|
| 117 |
+
level_ids: Tensor,
|
| 118 |
+
level_lambda: float = 1.0,
|
| 119 |
+
eps: float = 1e-7) -> Tensor:
|
| 120 |
+
"""Calculate S3 SimD multiplied by an FPN-level scale penalty.
|
| 121 |
+
|
| 122 |
+
The canonical scale of a level is the geometric mean square-root area of
|
| 123 |
+
its anchors. This is equivalent to deriving ``kappa * stride`` from the
|
| 124 |
+
configured anchor generator without hard-coding detector-specific scales.
|
| 125 |
+
"""
|
| 126 |
+
if level_lambda < 0:
|
| 127 |
+
raise ValueError('level_lambda must be non-negative')
|
| 128 |
+
priors = get_box_tensor(priors)[..., :4]
|
| 129 |
+
gt_bboxes = get_box_tensor(gt_bboxes)[..., :4]
|
| 130 |
+
if priors.shape[0] != level_ids.numel():
|
| 131 |
+
raise ValueError('level_ids must contain one entry per prior')
|
| 132 |
+
base = bbox_similarity_distance(priors, gt_bboxes, eps=eps)
|
| 133 |
+
if priors.numel() == 0 or gt_bboxes.numel() == 0 or level_lambda == 0:
|
| 134 |
+
return base
|
| 135 |
+
|
| 136 |
+
level_ids = level_ids.to(device=priors.device, dtype=torch.long)
|
| 137 |
+
if (level_ids < 0).any():
|
| 138 |
+
raise ValueError('level_ids must be non-negative')
|
| 139 |
+
prior_wh = (priors[:, 2:] - priors[:, :2]).clamp_min(eps)
|
| 140 |
+
prior_scale = torch.sqrt(prior_wh.prod(dim=-1).clamp_min(eps))
|
| 141 |
+
canonical_by_level = prior_scale.new_zeros(
|
| 142 |
+
int(level_ids.max().item()) + 1)
|
| 143 |
+
for level in level_ids.unique(sorted=True).tolist():
|
| 144 |
+
scales = prior_scale[level_ids == level]
|
| 145 |
+
canonical_by_level[level] = torch.exp(torch.log(scales).mean())
|
| 146 |
+
|
| 147 |
+
gt_wh = (gt_bboxes[:, 2:] - gt_bboxes[:, :2]).clamp_min(eps)
|
| 148 |
+
gt_scale = torch.sqrt(gt_wh.prod(dim=-1).clamp_min(eps))
|
| 149 |
+
prior_level_scale = canonical_by_level[level_ids]
|
| 150 |
+
octave_mismatch = torch.abs(
|
| 151 |
+
torch.log2(gt_scale[None, :] /
|
| 152 |
+
prior_level_scale[:, None].clamp_min(eps)))
|
| 153 |
+
penalty = torch.exp(-level_lambda * octave_mismatch)
|
| 154 |
+
return (base * penalty).clamp_min(eps)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
class DalaPositiveQuota(nn.Module):
|
| 158 |
"""Track the running anchor density used by ratio-based assignment.
|
| 159 |
|
|
|
|
| 209 |
|
| 210 |
def __init__(self,
|
| 211 |
ignore_iof_thr: float = -1,
|
| 212 |
+
sync_stats: bool = True,
|
| 213 |
+
similarity_mode: str = 's0',
|
| 214 |
+
nwd_normalizer: float = 32.0,
|
| 215 |
+
level_lambda: float = 1.0) -> None:
|
| 216 |
nn.Module.__init__(self)
|
| 217 |
+
if similarity_mode not in {'s0', 's1', 's2', 's3'}:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
'similarity_mode must be one of s0, s1, s2, or s3')
|
| 220 |
+
if nwd_normalizer <= 0:
|
| 221 |
+
raise ValueError('nwd_normalizer must be positive')
|
| 222 |
+
if level_lambda < 0:
|
| 223 |
+
raise ValueError('level_lambda must be non-negative')
|
| 224 |
self.ignore_iof_thr = ignore_iof_thr
|
| 225 |
+
self.similarity_mode = similarity_mode
|
| 226 |
+
self.nwd_normalizer = nwd_normalizer
|
| 227 |
+
self.level_lambda = level_lambda
|
| 228 |
self.quota_tracker = DalaPositiveQuota(sync_stats=sync_stats)
|
| 229 |
self.ignore_calculator = BboxOverlaps2D()
|
| 230 |
|
| 231 |
+
def _calculate_similarity(self, priors: Tensor, gt_bboxes: Tensor,
|
| 232 |
+
level_ids: Optional[Tensor]) -> Tensor:
|
| 233 |
+
"""Dispatch the configured S0--S3 similarity."""
|
| 234 |
+
if self.similarity_mode == 's0':
|
| 235 |
+
return bbox_similarity_distance(priors, gt_bboxes)
|
| 236 |
+
if self.similarity_mode == 's1':
|
| 237 |
+
return normalized_wasserstein_similarity(
|
| 238 |
+
priors, gt_bboxes, normalizer=self.nwd_normalizer)
|
| 239 |
+
if self.similarity_mode == 's2':
|
| 240 |
+
return geometry_balanced_similarity(priors, gt_bboxes)
|
| 241 |
+
if level_ids is None:
|
| 242 |
+
raise ValueError(
|
| 243 |
+
'S3 requires per-prior level_ids from a DALA anchor head')
|
| 244 |
+
return level_aware_similarity(
|
| 245 |
+
priors,
|
| 246 |
+
gt_bboxes,
|
| 247 |
+
level_ids,
|
| 248 |
+
level_lambda=self.level_lambda)
|
| 249 |
+
|
| 250 |
@torch.no_grad()
|
| 251 |
def assign(self,
|
| 252 |
pred_instances: InstanceData,
|
|
|
|
| 256 |
priors = get_box_tensor(pred_instances.priors)[..., :4]
|
| 257 |
gt_bboxes = get_box_tensor(gt_instances.bboxes)[..., :4]
|
| 258 |
gt_labels = getattr(gt_instances, 'labels', None)
|
| 259 |
+
level_ids = getattr(pred_instances, 'level_ids', None)
|
| 260 |
num_priors = priors.shape[0]
|
| 261 |
num_gts = gt_bboxes.shape[0]
|
| 262 |
|
|
|
|
| 287 |
& (centers[:, None, 1] < gt_bboxes[None, :, 3]))
|
| 288 |
inside[ignore_mask] = False
|
| 289 |
|
| 290 |
+
similarities = self._calculate_similarity(priors, gt_bboxes,
|
| 291 |
+
level_ids)
|
| 292 |
quotas = self.quota_tracker(inside.sum(dim=0).to(similarities))
|
| 293 |
|
| 294 |
selected_scores = similarities.new_full(similarities.shape, -torch.inf)
|
|
|
|
| 319 |
num_gts, assigned_gt_inds, max_overlaps, labels=assigned_labels)
|
| 320 |
|
| 321 |
|
| 322 |
+
__all__ = [
|
| 323 |
+
'DalaAssigner', 'DalaPositiveQuota', 'bbox_similarity_distance',
|
| 324 |
+
'geometry_balanced_similarity', 'level_aware_similarity',
|
| 325 |
+
'normalized_wasserstein_similarity'
|
| 326 |
+
]
|
mmdet_code/mmdetection/projects/EfficientDet/README.md
CHANGED
|
@@ -71,6 +71,32 @@ and head width to 112. Because canonical EfficientDet-D2 uses 768 x 768 inputs,
|
|
| 71 |
the fixed-512 D2 result is an architecture ablation and must not be presented
|
| 72 |
as a canonical EfficientDet-D2 number.
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
### Training commands
|
| 75 |
|
| 76 |
In MMDetection's root directory, run the following command to train the model:
|
|
|
|
| 71 |
the fixed-512 D2 result is an architecture ablation and must not be presented
|
| 72 |
as a canonical EfficientDet-D2 number.
|
| 73 |
|
| 74 |
+
### DALA SimD ablations on EfficientDet-D0
|
| 75 |
+
|
| 76 |
+
The S1--S3 variants keep EfficientNet-B0, BiFPN, anchors, RLA, DWL, input size,
|
| 77 |
+
and losses unchanged. Only the candidate-ranking similarity changes:
|
| 78 |
+
|
| 79 |
+
| Runner key | Similarity |
|
| 80 |
+
|---|---|
|
| 81 |
+
| `dala_efficientdet_d0_s1` | S1 normalized Wasserstein similarity |
|
| 82 |
+
| `dala_efficientdet_d0_s2` | S2 Geometry-Balanced SimD |
|
| 83 |
+
| `dala_efficientdet_d0_s3` | S3 original SimD multiplied by an FPN-level scale penalty |
|
| 84 |
+
|
| 85 |
+
S3 requires per-prior FPN level IDs. `DalaAnchorTargetMixin` preserves those
|
| 86 |
+
IDs before MMDetection flattens multi-level anchors. The original
|
| 87 |
+
`dala_efficientdet_d0` remains the S0 control.
|
| 88 |
+
|
| 89 |
+
The repository runner accepts all three variants together:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
python train_all_levir_baseline.py \
|
| 93 |
+
--models dala_efficientdet_d0_s1,dala_efficientdet_d0_s2,dala_efficientdet_d0_s3 \
|
| 94 |
+
--epochs 50 --batch-size 16 --seed 42 --no-hf-upload
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
For the final experiment, keep RLA/DWL and every training setting identical to
|
| 98 |
+
S0; vary only the three similarity fields exposed by these configs.
|
| 99 |
+
|
| 100 |
### Training commands
|
| 101 |
|
| 102 |
In MMDetection's root directory, run the following command to train the model:
|
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientDet-D0 with DALA S1 normalized Wasserstein ranking."""
|
| 2 |
+
|
| 3 |
+
_base_ = './efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.py'
|
| 4 |
+
|
| 5 |
+
model = dict(
|
| 6 |
+
train_cfg=dict(
|
| 7 |
+
assigner=dict(
|
| 8 |
+
similarity_mode='s1',
|
| 9 |
+
nwd_normalizer=32.0)))
|
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-crop512-300e_coco.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientDet-D0 with DALA S2 Geometry-Balanced SimD."""
|
| 2 |
+
|
| 3 |
+
_base_ = './efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.py'
|
| 4 |
+
|
| 5 |
+
model = dict(
|
| 6 |
+
train_cfg=dict(
|
| 7 |
+
assigner=dict(
|
| 8 |
+
similarity_mode='s2')))
|
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-crop512-300e_coco.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientDet-D0 with DALA S3 FPN-level-penalized SimD."""
|
| 2 |
+
|
| 3 |
+
_base_ = './efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.py'
|
| 4 |
+
|
| 5 |
+
model = dict(
|
| 6 |
+
train_cfg=dict(
|
| 7 |
+
assigner=dict(
|
| 8 |
+
similarity_mode='s3',
|
| 9 |
+
level_lambda=1.0)))
|
mmdet_code/train_all_levir_baseline.py
CHANGED
|
@@ -40,6 +40,20 @@ MODEL_CONFIGS = {
|
|
| 40 |
"projects/EfficientDet/configs/"
|
| 41 |
"efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.py"
|
| 42 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
"dala_efficientdet_d2": (
|
| 44 |
"projects/EfficientDet/configs/"
|
| 45 |
"efficientdet_effb2_bifpn_dala_8xb16-crop512-300e_coco.py"
|
|
@@ -415,7 +429,9 @@ def parse_args() -> argparse.Namespace:
|
|
| 415 |
help=("Comma-separated model keys. DALA keys: dala_faster_rcnn, "
|
| 416 |
"dala_retinanet, dala_fcos, dala_cascade_rcnn. EfficientDet "
|
| 417 |
"keys: efficientdet_d0, efficientdet_d2, "
|
| 418 |
-
"dala_efficientdet_d0, dala_efficientdet_d2
|
|
|
|
|
|
|
| 419 |
)
|
| 420 |
parser.add_argument("--epochs", type=int, default=12)
|
| 421 |
parser.add_argument("--batch-size", type=int, default=4)
|
|
|
|
| 40 |
"projects/EfficientDet/configs/"
|
| 41 |
"efficientdet_effb0_bifpn_dala_8xb16-crop512-300e_coco.py"
|
| 42 |
),
|
| 43 |
+
"dala_efficientdet_d0_s1": (
|
| 44 |
+
"projects/EfficientDet/configs/"
|
| 45 |
+
"efficientdet_effb0_bifpn_dala_s1_nwd_8xb16-crop512-300e_coco.py"
|
| 46 |
+
),
|
| 47 |
+
"dala_efficientdet_d0_s2": (
|
| 48 |
+
"projects/EfficientDet/configs/"
|
| 49 |
+
"efficientdet_effb0_bifpn_dala_s2_geometry_balanced_8xb16-"
|
| 50 |
+
"crop512-300e_coco.py"
|
| 51 |
+
),
|
| 52 |
+
"dala_efficientdet_d0_s3": (
|
| 53 |
+
"projects/EfficientDet/configs/"
|
| 54 |
+
"efficientdet_effb0_bifpn_dala_s3_level_aware_8xb16-"
|
| 55 |
+
"crop512-300e_coco.py"
|
| 56 |
+
),
|
| 57 |
"dala_efficientdet_d2": (
|
| 58 |
"projects/EfficientDet/configs/"
|
| 59 |
"efficientdet_effb2_bifpn_dala_8xb16-crop512-300e_coco.py"
|
|
|
|
| 429 |
help=("Comma-separated model keys. DALA keys: dala_faster_rcnn, "
|
| 430 |
"dala_retinanet, dala_fcos, dala_cascade_rcnn. EfficientDet "
|
| 431 |
"keys: efficientdet_d0, efficientdet_d2, "
|
| 432 |
+
"dala_efficientdet_d0, dala_efficientdet_d2, "
|
| 433 |
+
"dala_efficientdet_d0_s1, dala_efficientdet_d0_s2, "
|
| 434 |
+
"dala_efficientdet_d0_s3."),
|
| 435 |
)
|
| 436 |
parser.add_argument("--epochs", type=int, default=12)
|
| 437 |
parser.add_argument("--batch-size", type=int, default=4)
|