Implement Non-Maximum Suppression (NMS), the post-processing pass that every
object detector runs after the network forward pass: the model emits thousands of overlapping
candidate boxes, and NMS collapses them down to one box per object. Given N boxes in
corner format (x1, y1, x2, y2) together with their confidence scores,
walk the boxes from the highest score to the lowest; every box that has not been suppressed yet
is kept, and it suppresses all lower-scoring boxes whose intersection over union (IoU) with it is
greater than iou_threshold. Write a 1 into keep[i] for a surviving box
and a 0 for a suppressed one.
The overlap of two boxes \(a\) and \(b\) is measured by their intersection over union:
\[ \text{IoU}(a, b) = \frac{|a \cap b|}{|a| + |b| - |a \cap b|} \] \[ |a| = (x_2^a - x_1^a)\,(y_2^a - y_1^a), \qquad |a \cap b| = w \cdot h \] \[ w = \max\!\left(0,\; \min(x_2^a, x_2^b) - \max(x_1^a, x_1^b)\right), \qquad h = \max\!\left(0,\; \min(y_2^a, y_2^b) - \max(y_1^a, y_1^b)\right) \]keep entry to 1 and suppress every box that appears later in the order whose
IoU with it is greater than iou_threshold.keep entry of 0.A suppressed box never suppresses anything itself, so the decisions are chained: whether box \(j\) survives depends on which higher-scoring boxes survived before it.
solve function signature must remain unchangedkeep tensoriou_thresholdkeep is indexed by the original box order, not by the score-sorted orderkeep must be written: 1 for a kept box, 0 for a suppressed boxSix candidates covering three objects, with iou_threshold = 0.5:
Box 2 has the highest score, so it is kept and suppresses box 3 (\(\text{IoU} = \tfrac{1225}{1975} \approx 0.62\)). Box 0 is kept next and suppresses box 1 by the same overlap, and box 4 is kept and suppresses box 5. Boxes from different objects never overlap here, so all three winners survive.
N ≤ 20,000boxes has shape (N, 4) and is stored row-major as
(x1, y1, x2, y2) with x1 < x2 and
y1 < y2scores[i] ≤ 1; equal scores are possibleiou_threshold ≤ 1boxes and scores are 32-bit floating point,
keep is 32-bit signed integerN = 16,384 and
iou_threshold = 0.5