🐛 [FIX] Fix Float16 overflow problem in box_nms#234
Open
TrungDinhT wants to merge 1 commit intoMultimediaTechLab:mainfrom
Open
🐛 [FIX] Fix Float16 overflow problem in box_nms#234TrungDinhT wants to merge 1 commit intoMultimediaTechLab:mainfrom
TrungDinhT wants to merge 1 commit intoMultimediaTechLab:mainfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When running inference with
precision="16-mixed"(or any configuration that produces float16 model outputs),bbox_nmssometimes silently fails to suppress overlapping bounding boxes when the batch contains many images. This results in many duplicate detections surviving NMS for the same object.Root Cause
batched_nms(fromtorchvision.ops) internally separates NMS groups by spatially shifting boxes:This shift is designed to guarantee that boxes from different
(image, class)groups never overlap. However, when box coordinates are float16, the shifted coordinates quickly exceed float16's safe precision range. For example:max_coord ≈ 3500andlabel = 18(image 2, class 2 in a batch of 8):offset = 18 × 3501 + 3500 = 66518, which exceeds float16 precision.IoU > 0.5compute asIoU ≈ 0, so NMS skips suppression and all duplicates survive.The bug is invisible with a single image because
valid_clslabels stay small (0, 1, 2), producing tiny offsets that float16 handles correctly. It surfaces as soon asbatch_idx + valid_cls * Bproduces big enough labels.Fix
Cast
valid_boxandvalid_conto float32 before passing tobatched_nms:This is effectively free - at the NMS stage we are working with a small set of filtered detections, not the full feature map.
Test
Added
test_bbox_nms_float16_precision()which creates the extreme scenario wherebox_nmsfailed to suppress overlapped box due to Float16 overflow. This test fails before this fix and passes after.