Skip to content

XYXY to CXCYWH conversion overflows for narrow dtypes #9594

Description

@aswanth-07

Describe the bug

torchvision.transforms.v2.functional.convert_bounding_box_format can return an incorrect center when converting valid XYXY boxes to CXCYWH with a narrow dtype.

The internal _xyxy_to_cxcywh implementation first computes the width, but then evaluates the equivalent expression (x1 * 2 + width) / 2. The intermediate x1 * 2 can overflow even when the input coordinates, width, and mathematically correct center are all representable in the input dtype.

For uint8, the center wraps from 210 to 82. For float16, the center becomes infinity instead of 40960.

import torch
from torchvision import tv_tensors
from torchvision.transforms.v2 import functional as F

cases = [
    (torch.uint8, [200, 10, 220, 30]),
    (torch.float16, [32768, 0, 49152, 32]),
]

for dtype, box in cases:
    output = F.convert_bounding_box_format(
        torch.tensor([box], dtype=dtype),
        old_format=tv_tensors.BoundingBoxFormat.XYXY,
        new_format=tv_tensors.BoundingBoxFormat.CXCYWH,
    )
    print(dtype, output)

Actual output on current main at 34572106:

torch.uint8 tensor([[82, 20, 20, 20]], dtype=torch.uint8)
torch.float16 tensor([[   inf, 1.6000e+01, 1.6384e+04, 3.2000e+01]], dtype=torch.float16)

Expected output:

torch.uint8 tensor([[210, 20, 20, 20]], dtype=torch.uint8)
torch.float16 tensor([[40960, 16, 16384, 32]], dtype=torch.float16)

The overflow can be avoided by evaluating the equivalent but safer expression x1 + width / 2. I would like to contribute that focused change with regression coverage for both in-place and out-of-place conversions.

I searched open and closed issues and pull requests for bounding-box center, uint8, and float16 conversion overflow and did not find an existing report for this path.

AI disclosure: I used Codex to help audit the conversion arithmetic, search for duplicates, reproduce the failure, test the proposed expression, and draft this report. I reviewed the diagnosis, reproduction, and proposed scope and will personally handle follow-up.

Versions

TorchVision: current main at 34572106ad1f0ea95793e379751f8bb0cfeeac1c
PyTorch: 2.13.0+cpu
Python: 3.10.11 (64-bit)
OS: Microsoft Windows 11 Home Single Language 10.0.26200
CUDA available: False
NumPy: 2.2.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions