-
Notifications
You must be signed in to change notification settings - Fork 715
Expand file tree
/
Copy pathmatcher.py
More file actions
227 lines (198 loc) · 11.1 KB
/
matcher.py
File metadata and controls
227 lines (198 loc) · 11.1 KB
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
# ------------------------------------------------------------------------
# RF-DETR
# Copyright (c) 2025 Roboflow. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Copied and modified from LW-DETR (https://github.com/Atten4Vis/LW-DETR)
# Copyright (c) 2024 Baidu. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Conditional DETR (https://github.com/Atten4Vis/ConditionalDETR)
# Copyright (c) 2021 Microsoft. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# ------------------------------------------------------------------------
"""
Modules to compute the matching cost and solve the corresponding LSAP.
"""
import numpy as np
import torch
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from torch import nn
from rfdetr.models.segmentation_head import point_sample
from rfdetr.util.box_ops import batch_dice_loss, batch_sigmoid_ce_loss, box_cxcywh_to_xyxy, generalized_box_iou
class HungarianMatcher(nn.Module):
"""This class computes an assignment between the targets and the predictions of the network
For efficiency reasons, the targets don't include the no_object. Because of this, in general,
there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
while the others are un-matched (and thus treated as non-objects).
"""
def __init__(
self,
cost_class: float = 1,
cost_bbox: float = 1,
cost_giou: float = 1,
focal_alpha: float = 0.25,
use_pos_only: bool = False,
use_position_modulated_cost: bool = False,
mask_point_sample_ratio: int = 16,
cost_mask_ce: float = 1,
cost_mask_dice: float = 1,
):
"""Creates the matcher
Params:
cost_class: This is the relative weight of the classification error in the matching cost
cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
"""
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs can't be 0"
self.focal_alpha = focal_alpha
self.mask_point_sample_ratio = mask_point_sample_ratio
self.cost_mask_ce = cost_mask_ce
self.cost_mask_dice = cost_mask_dice
@torch.no_grad()
def forward(self, outputs, targets, group_detr=1):
"""Performs the matching
Params:
outputs: This is a dict that contains at least these entries:
"pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
"pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
"labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
objects in the target) containing the class labels
"boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
"masks": Tensor of dim [num_target_boxes, H, W] containing the target mask coordinates
group_detr: Number of groups used for matching.
Returns:
A list of size batch_size, containing tuples of (index_i, index_j) where:
- index_i is the indices of the selected predictions (in order)
- index_j is the indices of the corresponding selected targets (in order)
For each batch element, it holds:
len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
"""
bs, num_queries = outputs["pred_logits"].shape[:2]
# We flatten to compute the cost matrices in a batch
flat_pred_logits = outputs["pred_logits"].flatten(0, 1)
out_prob = flat_pred_logits.sigmoid() # [batch_size * num_queries, num_classes]
out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
# Also concat the target labels and boxes
tgt_ids = torch.cat([v["labels"] for v in targets])
tgt_bbox = torch.cat([v["boxes"] for v in targets])
masks_present = "masks" in targets[0]
# Compute the giou cost between boxes
giou = generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
cost_giou = -giou
# Compute the classification cost.
alpha = 0.25
gamma = 2.0
# neg_cost_class = (1 - alpha) * (out_prob ** gamma) * (-(1 - out_prob + 1e-8).log())
# pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
# we refactor these with logsigmoid for numerical stability
neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-F.logsigmoid(-flat_pred_logits))
pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-F.logsigmoid(flat_pred_logits))
cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
# Compute the L1 cost between boxes
cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
if masks_present:
# Resize predicted masks to target mask size if needed
# if out_masks.shape[-2:] != tgt_masks.shape[-2:]:
# # out_masks = F.interpolate(out_masks.unsqueeze(1), size=tgt_masks.shape[-2:], mode="bilinear", align_corners=False).squeeze(1)
# tgt_masks = F.interpolate(tgt_masks.unsqueeze(1).float(), size=out_masks.shape[-2:], mode="bilinear", align_corners=False).squeeze(1)
# # Flatten masks
# pred_masks_logits = out_masks.flatten(1) # [P, HW]
# tgt_masks_flat = tgt_masks.flatten(1).float() # [T, HW]
tgt_masks = torch.cat([v["masks"] for v in targets])
if isinstance(outputs["pred_masks"], torch.Tensor):
out_masks = outputs["pred_masks"].flatten(0, 1)
num_points = out_masks.shape[-2] * out_masks.shape[-1] // self.mask_point_sample_ratio
point_coords = torch.rand(1, num_points, 2, device=out_masks.device)
pred_masks_logits = point_sample(
out_masks.unsqueeze(1), point_coords.repeat(out_masks.shape[0], 1, 1), align_corners=False
).squeeze(1)
else:
# pred_masks_logits = outputs["sparse_matcher_mask_logits"].flatten(0, 1)
# point_coords = outputs["matcher_sample_coords"]
spatial_features = outputs["pred_masks"]["spatial_features"]
query_features = outputs["pred_masks"]["query_features"]
bias = outputs["pred_masks"]["bias"]
num_points = spatial_features.shape[-2] * spatial_features.shape[-1] // self.mask_point_sample_ratio
point_coords = torch.rand(1, num_points, 2, device=spatial_features.device)
pred_masks_logits = point_sample(
spatial_features, point_coords.repeat(spatial_features.shape[0], 1, 1), align_corners=False
)
# print(f"pred_masks_logits.shape: {pred_masks_logits.shape}")
pred_masks_logits = torch.einsum("bcp,bnc->bnp", pred_masks_logits, query_features) + bias
pred_masks_logits = pred_masks_logits.flatten(0, 1)
tgt_masks = tgt_masks.to(pred_masks_logits.dtype)
tgt_masks_flat = point_sample(
tgt_masks.unsqueeze(1),
point_coords.repeat(tgt_masks.shape[0], 1, 1),
align_corners=False,
mode="nearest",
).squeeze(1)
# Binary cross-entropy with logits cost (mean over pixels), computed pairwise efficiently
cost_mask_ce = batch_sigmoid_ce_loss(pred_masks_logits, tgt_masks_flat)
# Dice loss cost (1 - dice coefficient)
cost_mask_dice = batch_dice_loss(pred_masks_logits, tgt_masks_flat)
# Final cost matrix
C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
if masks_present:
C = C + self.cost_mask_ce * cost_mask_ce + self.cost_mask_dice * cost_mask_dice
C = C.view(bs, num_queries, -1).float().cpu() # convert to float because bfloat16 doesn't play nicely with CPU
# We assume any good match will not cause NaN or Inf, so replace invalid
# entries with a finite value that is larger than every valid cost.
finite_mask = torch.isfinite(C)
if not finite_mask.all():
if finite_mask.any():
finite_costs = C[finite_mask]
max_cost = finite_costs.max()
# Add the largest absolute finite cost so the replacement stays
# strictly larger than every valid entry, even if all costs are negative.
replacement_cost = max_cost + finite_costs.abs().max() + 1
else:
replacement_cost = C.new_tensor(1.0)
C[~finite_mask] = replacement_cost
sizes = [len(v["boxes"]) for v in targets]
indices = []
g_num_queries = num_queries // group_detr
C_list = C.split(g_num_queries, dim=1)
for g_i in range(group_detr):
C_g = C_list[g_i]
indices_g = [linear_sum_assignment(c[i]) for i, c in enumerate(C_g.split(sizes, -1))]
if g_i == 0:
indices = indices_g
else:
indices = [
(
np.concatenate([indice1[0], indice2[0] + g_num_queries * g_i]),
np.concatenate([indice1[1], indice2[1]]),
)
for indice1, indice2 in zip(indices, indices_g)
]
return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
def build_matcher(args):
if args.segmentation_head:
return HungarianMatcher(
cost_class=args.set_cost_class,
cost_bbox=args.set_cost_bbox,
cost_giou=args.set_cost_giou,
focal_alpha=args.focal_alpha,
cost_mask_ce=args.mask_ce_loss_coef,
cost_mask_dice=args.mask_dice_loss_coef,
mask_point_sample_ratio=args.mask_point_sample_ratio,
)
else:
return HungarianMatcher(
cost_class=args.set_cost_class,
cost_bbox=args.set_cost_bbox,
cost_giou=args.set_cost_giou,
focal_alpha=args.focal_alpha,
)