Vvaann commited on
Commit
40f326d
·
verified ·
1 Parent(s): c28f0ef

Upload 2 files

Browse files
Files changed (2) hide show
  1. anchor_generator.py +38 -0
  2. assigner.py +179 -0
anchor_generator.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from utils.general import check_version
4
+
5
+ TORCH_1_10 = check_version(torch.__version__, '1.10.0')
6
+
7
+
8
+ def make_anchors(feats, strides, grid_cell_offset=0.5):
9
+ """Generate anchors from features."""
10
+ anchor_points, stride_tensor = [], []
11
+ assert feats is not None
12
+ dtype, device = feats[0].dtype, feats[0].device
13
+ for i, stride in enumerate(strides):
14
+ _, _, h, w = feats[i].shape
15
+ sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset # shift x
16
+ sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset # shift y
17
+ sy, sx = torch.meshgrid(sy, sx, indexing='ij') if TORCH_1_10 else torch.meshgrid(sy, sx)
18
+ anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))
19
+ stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))
20
+ return torch.cat(anchor_points), torch.cat(stride_tensor)
21
+
22
+
23
+ def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
24
+ """Transform distance(ltrb) to box(xywh or xyxy)."""
25
+ lt, rb = torch.split(distance, 2, dim)
26
+ x1y1 = anchor_points - lt
27
+ x2y2 = anchor_points + rb
28
+ if xywh:
29
+ c_xy = (x1y1 + x2y2) / 2
30
+ wh = x2y2 - x1y1
31
+ return torch.cat((c_xy, wh), dim) # xywh bbox
32
+ return torch.cat((x1y1, x2y2), dim) # xyxy bbox
33
+
34
+
35
+ def bbox2dist(anchor_points, bbox, reg_max):
36
+ """Transform bbox(xyxy) to dist(ltrb)."""
37
+ x1y1, x2y2 = torch.split(bbox, 2, -1)
38
+ return torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1).clamp(0, reg_max - 0.01) # dist (lt, rb)
assigner.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from utils.metrics import bbox_iou
6
+
7
+
8
+ def select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):
9
+ """select the positive anchor center in gt
10
+
11
+ Args:
12
+ xy_centers (Tensor): shape(h*w, 4)
13
+ gt_bboxes (Tensor): shape(b, n_boxes, 4)
14
+ Return:
15
+ (Tensor): shape(b, n_boxes, h*w)
16
+ """
17
+ n_anchors = xy_centers.shape[0]
18
+ bs, n_boxes, _ = gt_bboxes.shape
19
+ lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2) # left-top, right-bottom
20
+ bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)
21
+ # return (bbox_deltas.min(3)[0] > eps).to(gt_bboxes.dtype)
22
+ return bbox_deltas.amin(3).gt_(eps)
23
+
24
+
25
+ def select_highest_overlaps(mask_pos, overlaps, n_max_boxes):
26
+ """if an anchor box is assigned to multiple gts,
27
+ the one with the highest iou will be selected.
28
+
29
+ Args:
30
+ mask_pos (Tensor): shape(b, n_max_boxes, h*w)
31
+ overlaps (Tensor): shape(b, n_max_boxes, h*w)
32
+ Return:
33
+ target_gt_idx (Tensor): shape(b, h*w)
34
+ fg_mask (Tensor): shape(b, h*w)
35
+ mask_pos (Tensor): shape(b, n_max_boxes, h*w)
36
+ """
37
+ # (b, n_max_boxes, h*w) -> (b, h*w)
38
+ fg_mask = mask_pos.sum(-2)
39
+ if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
40
+ mask_multi_gts = (fg_mask.unsqueeze(1) > 1).repeat([1, n_max_boxes, 1]) # (b, n_max_boxes, h*w)
41
+ max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
42
+ is_max_overlaps = F.one_hot(max_overlaps_idx, n_max_boxes) # (b, h*w, n_max_boxes)
43
+ is_max_overlaps = is_max_overlaps.permute(0, 2, 1).to(overlaps.dtype) # (b, n_max_boxes, h*w)
44
+ mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos) # (b, n_max_boxes, h*w)
45
+ fg_mask = mask_pos.sum(-2)
46
+ # find each grid serve which gt(index)
47
+ target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
48
+ return target_gt_idx, fg_mask, mask_pos
49
+
50
+
51
+ class TaskAlignedAssigner(nn.Module):
52
+ def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):
53
+ super().__init__()
54
+ self.topk = topk
55
+ self.num_classes = num_classes
56
+ self.bg_idx = num_classes
57
+ self.alpha = alpha
58
+ self.beta = beta
59
+ self.eps = eps
60
+
61
+ @torch.no_grad()
62
+ def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
63
+ """This code referenced to
64
+ https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
65
+
66
+ Args:
67
+ pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)
68
+ pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)
69
+ anc_points (Tensor): shape(num_total_anchors, 2)
70
+ gt_labels (Tensor): shape(bs, n_max_boxes, 1)
71
+ gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)
72
+ mask_gt (Tensor): shape(bs, n_max_boxes, 1)
73
+ Returns:
74
+ target_labels (Tensor): shape(bs, num_total_anchors)
75
+ target_bboxes (Tensor): shape(bs, num_total_anchors, 4)
76
+ target_scores (Tensor): shape(bs, num_total_anchors, num_classes)
77
+ fg_mask (Tensor): shape(bs, num_total_anchors)
78
+ """
79
+ self.bs = pd_scores.size(0)
80
+ self.n_max_boxes = gt_bboxes.size(1)
81
+
82
+ if self.n_max_boxes == 0:
83
+ device = gt_bboxes.device
84
+ return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device),
85
+ torch.zeros_like(pd_bboxes).to(device),
86
+ torch.zeros_like(pd_scores).to(device),
87
+ torch.zeros_like(pd_scores[..., 0]).to(device))
88
+
89
+ mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,
90
+ mask_gt)
91
+
92
+ target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)
93
+
94
+ # assigned target
95
+ target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)
96
+
97
+ # normalize
98
+ align_metric *= mask_pos
99
+ pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) # b, max_num_obj
100
+ pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) # b, max_num_obj
101
+ norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
102
+ target_scores = target_scores * norm_align_metric
103
+
104
+ return target_labels, target_bboxes, target_scores, fg_mask.bool()
105
+
106
+ def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
107
+
108
+ # get anchor_align metric, (b, max_num_obj, h*w)
109
+ align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes)
110
+ # get in_gts mask, (b, max_num_obj, h*w)
111
+ mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)
112
+ # get topk_metric mask, (b, max_num_obj, h*w)
113
+ mask_topk = self.select_topk_candidates(align_metric * mask_in_gts,
114
+ topk_mask=mask_gt.repeat([1, 1, self.topk]).bool())
115
+ # merge all mask to a final mask, (b, max_num_obj, h*w)
116
+ mask_pos = mask_topk * mask_in_gts * mask_gt
117
+
118
+ return mask_pos, align_metric, overlaps
119
+
120
+ def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes):
121
+
122
+ gt_labels = gt_labels.to(torch.long) # b, max_num_obj, 1
123
+ ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
124
+ ind[0] = torch.arange(end=self.bs).view(-1, 1).repeat(1, self.n_max_boxes) # b, max_num_obj
125
+ ind[1] = gt_labels.squeeze(-1) # b, max_num_obj
126
+ # get the scores of each grid for each gt cls
127
+ bbox_scores = pd_scores[ind[0], :, ind[1]] # b, max_num_obj, h*w
128
+
129
+ overlaps = bbox_iou(gt_bboxes.unsqueeze(2), pd_bboxes.unsqueeze(1), xywh=False, CIoU=True).squeeze(3).clamp(0)
130
+ align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)
131
+ return align_metric, overlaps
132
+
133
+ def select_topk_candidates(self, metrics, largest=True, topk_mask=None):
134
+ """
135
+ Args:
136
+ metrics: (b, max_num_obj, h*w).
137
+ topk_mask: (b, max_num_obj, topk) or None
138
+ """
139
+
140
+ num_anchors = metrics.shape[-1] # h*w
141
+ # (b, max_num_obj, topk)
142
+ topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=largest)
143
+ if topk_mask is None:
144
+ topk_mask = (topk_metrics.max(-1, keepdim=True) > self.eps).tile([1, 1, self.topk])
145
+ # (b, max_num_obj, topk)
146
+ topk_idxs = torch.where(topk_mask, topk_idxs, 0)
147
+ # (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)
148
+ is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(-2)
149
+ # filter invalid bboxes
150
+ # assigned topk should be unique, this is for dealing with empty labels
151
+ # since empty labels will generate index `0` through `F.one_hot`
152
+ # NOTE: but what if the topk_idxs include `0`?
153
+ is_in_topk = torch.where(is_in_topk > 1, 0, is_in_topk)
154
+ return is_in_topk.to(metrics.dtype)
155
+
156
+ def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):
157
+ """
158
+ Args:
159
+ gt_labels: (b, max_num_obj, 1)
160
+ gt_bboxes: (b, max_num_obj, 4)
161
+ target_gt_idx: (b, h*w)
162
+ fg_mask: (b, h*w)
163
+ """
164
+
165
+ # assigned target labels, (b, 1)
166
+ batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]
167
+ target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w)
168
+ target_labels = gt_labels.long().flatten()[target_gt_idx] # (b, h*w)
169
+
170
+ # assigned target boxes, (b, max_num_obj, 4) -> (b, h*w)
171
+ target_bboxes = gt_bboxes.view(-1, 4)[target_gt_idx]
172
+
173
+ # assigned target scores
174
+ target_labels.clamp(0)
175
+ target_scores = F.one_hot(target_labels, self.num_classes) # (b, h*w, 80)
176
+ fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes) # (b, h*w, 80)
177
+ target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)
178
+
179
+ return target_labels, target_bboxes, target_scores