Sub topic 15
One-to-one matching with the Hungarian algorithm
This chapter assumes you know what DETR's object queries are (from the previous chapters), how IoU works, and the basics of cross-entropy and L1 losses. You should also be comfortable with NumPy arrays. After it, you should be able to build a matching cost matrix, solve it with SciPy, and explain why this step lets DETR drop anchors and non-maximum suppression (NMS).
The problem: many predictions, few objects
A DETR-style decoder emits a fixed number of predictions, N, one per object query. N is usually 100 or more. An image holds only M ground-truth objects, and M is typically far smaller than N. To compute a loss, each prediction needs a training target. This is the same question as in anchor-based label assignment, but the answer is different.
Anchor-based detectors answer it with a many-to-one rule. Every anchor whose IoU with a ground-truth box passes a threshold becomes a positive. Several anchors therefore chase the same object, and NMS must remove the resulting duplicates at inference.
DETR uses a one-to-one rule. Each ground-truth object is assigned to exactly one prediction. Every other prediction is trained to output the "no object" class. Since the model is never rewarded for producing two boxes on one object, it learns to avoid duplicates, and NMS is unnecessary.
| Property | Threshold-based assignment | Hungarian matching |
|---|---|---|
| Predictions per object | Many | Exactly one |
| Needs anchors | Yes | No |
| Needs NMS at inference | Yes | No |
| Decision is made by | A fixed IoU threshold | Global minimum of a cost |
| Changes during training | Only as anchors are fixed | Yes, as predictions improve |
The assignment problem
Given a cost matrix C with N rows (predictions) and M columns (ground-truth objects), find a one-to-one assignment that minimizes the total cost. The Hungarian algorithm solves this exactly. Its worst-case time is O(n³), where n is the larger matrix dimension. For N around 100 and M around 20, this takes well under a few milliseconds.
The word "global" matters. A greedy rule such as "each ground truth takes its cheapest free prediction" can fail. It lets an early object grab a prediction that a later object needed much more. The Hungarian algorithm considers the whole matrix before committing.
SciPy's linear_sum_assignment accepts rectangular matrices. It returns min(N, M) pairs, so with N ≥ M every ground-truth object gets a prediction. The unmatched rows are the predictions that will be trained as "no object".
import numpy as np
from scipy.optimize import linear_sum_assignment
# Rows: 3 predictions (queries). Columns: 2 ground-truth objects.
# Entries: matching cost (lower is a better match).
cost = np.array([
[0.9, 0.2],
[0.1, 0.8],
[0.5, 0.6],
])
rows, cols = linear_sum_assignment(cost)
print(list(zip(rows.tolist(), cols.tolist()))) # [(0, 1), (1, 0)]The total cost is 0.2 + 0.1 = 0.3. Row 2 is left over, and it is the prediction trained to say "no object".
Building the matching cost
The cost for pairing prediction i with ground truth j combines three terms. DETR defines it as:
- A class term: the negative predicted probability of the ground-truth class. DETR uses the probability, not the log-probability, so this term has a similar scale to the box terms.
- An L1 term: the absolute difference between the predicted and ground-truth box coordinates.
- A generalized IoU (GIoU) term: the negative GIoU between the two boxes.
GIoU is IoU minus a penalty for the empty space in the smallest box enclosing both boxes. Unlike plain IoU, it still gives a useful signal when the boxes do not overlap. The terms are weighted. DETR's defaults are 1 for class, 5 for L1, and 2 for GIoU.
The next script builds the full cost matrix for one image and runs the matching. To keep it short it uses corner-format boxes (x1, y1, x2, y2) normalized to [0, 1]. DETR itself applies L1 to center-format boxes.
import numpy as np
from scipy.optimize import linear_sum_assignment
def giou(a, b):
"""Generalized IoU of two (x1, y1, x2, y2) boxes."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
iou = inter / union
ex1, ey1 = min(a[0], b[0]), min(a[1], b[1])
ex2, ey2 = max(a[2], b[2]), max(a[3], b[3])
enclosing = (ex2 - ex1) * (ey2 - ey1)
return iou - (enclosing - union) / enclosing
def match(probs, pred_boxes, gt_labels, gt_boxes,
w_cls=1.0, w_l1=5.0, w_giou=2.0):
n_q, n_gt = len(pred_boxes), len(gt_boxes)
cost = np.zeros((n_q, n_gt))
for i in range(n_q):
for j in range(n_gt):
c_cls = -probs[i, gt_labels[j]]
c_l1 = np.abs(pred_boxes[i] - gt_boxes[j]).sum()
c_giou = -giou(pred_boxes[i], gt_boxes[j])
cost[i, j] = w_cls * c_cls + w_l1 * c_l1 + w_giou * c_giou
return linear_sum_assignment(cost)
# Classes: 0 = cat, 1 = dog, 2 = no-object
probs = np.array([[0.7, 0.2, 0.1],
[0.1, 0.8, 0.1],
[0.1, 0.1, 0.xes = np.array([[0.10, 0.10, 0.40, 0.40],
[0.55, 0.50, 0.90, 0.90],
[0.00, 0.00, 0.20, 0.20]])
gt_labels = [1, 0] # a dog, then a cat
gt_bo0.5, 0.5, 0.9, 0.9],
[0.1, 0.1, 0.4, 0.45]])
rows, cols = matchxes, gt_labels, gt_boxes)
print(list(zip(rows.tolist(), cols.tolist()))) # [(0, 1), (1, 0)]len(pred_boxes), 2) # default: no-object
targets[rows] = [gt_labels[c] for c in cols]()) # [0, 1, 2]Query 0 matches the cat (ground truth 1), query 1 matches the d), and query 2 gets the no-object target.
Where matching sits in the training step
Matching only decides the targets. The loss is then computed in a second step, using the matched pairs.
The loss has these parts:
- Cross-entropy on all N queries, using the targets from the matching. DETR down-weights the no-object class (by a factor of 10) because most queries are unmatched.
- L1 and GIoU losses on the matched pairs only. Unmatched queries have no box target.
The matching itself is not differentiable. It runs on detached values, and gradients flow only through the losses computed on the resulting pairs.
Edge cases and gotchas
- Images with no objects. M = 0, so the cost matrix is empty. Every query gets the no-object target. Guard for this case in your own code, because some matching implementations fail on empty matrices.
- More objects than queries. If M > N, some ground-truth objects go unmatched and are silently ignored. Choose N comfortably above the largest expected object count.
- Batches. Matching runs separately for each image. Costs from different images are never mixed.
- Auxiliary losses. DETR applies matching and loss at every decoder layer, and each layer gets its own matching.
- Unstable assignments. Early in training the predictions are nearly random, so the matched query for a given object can change from epoch to epoch. The target for a given query keeps shifting. This is one reason DETR converges slowly, and later chapters cover methods that stabilize it.
- Cost versus loss. The matching cost need not equal the training loss. DETR uses probability in the cost and log-probability in the loss.
Check your understanding
Exercise
A cost matrix has 4 predictions (rows) and 2 ground-truth objects (columns). How many predictions get a ground-truth target, how many are trained toward "no object", and why does this remove the need for NMS?
Show answer
Two predictions are matched, one per ground-truth object, and the other two are trained toward "no object". If two queries both predicted the same object, only one could be matched. The other would be penalized as a false positive and so learns to stay quiet. The model therefore learns not to produce duplicates, which is what NMS would otherwise remove.
Exercise
Using the first cost matrix in this chapter, a greedy rule lets ground-truth column 0 pick its cheapest row first, then column 1 picks its cheapest remaining row. Does this give the same result as the Hungarian algorithm?
Show answer
Here it does. Column 0's cheapest row is row 1 (0.1), and column 1's cheapest remaining row is row 0 (0.2). The total is 0.3, which matches the optimum. Greedy search can fail on other matrices, for example when the first column's cheapest row is also the only cheap row for the second column. The Hungarian algorithm is guaranteed to find the minimum.