Repository navigation
Add direct XYWH-CXCYWH conversion for better performance - #9326
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/vision/9326
Note: Links to docs will display an error until the docs builds have been completed. ❌ 2 New Failures, 2 Unrelated FailuresAs of commit b4b0eed with merge base 4967c64 ( NEW FAILURES - The following jobs have failed:
BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
zy1git
left a comment
There was a problem hiding this comment.
Thanks for the PR. I left a comment for a minor thing. Feel free to take a look.
|
@raimbekovm Thanks a lot for this PR. Could you please add the parity test against reference implementation (the implementation which needs for intermediate XYXY conversion)? Also, in your description, you mentioned that "Performance improvement: ~2.3x faster for XYWH↔CXCYWH conversions.". Could you please share benchmark script or benchmark configuration (shapes etc.) to show how you get 2.3x faster? And I also notice that you submitted PR#9322. If that PR is correct (I am still reviewing it), the similar fix can be applied here for the function |
|
@zy1git Thanks for the review! Here's the benchmark results and script. Benchmark Results
Average speedup: ~1.9x (ranges from 1.5x to 2.3x depending on tensor size and dtype) The speedup comes from avoiding:
Benchmark Scriptimport torch
import time
# Conversion functions from torchvision/transforms/v2/functional/_meta.py
def _xywh_to_xyxy(xywh, inplace):
xyxy = xywh if inplace else xywh.clone()
xyxy[..., 2:] += xyxy[..., :2]
return xyxy
def _xyxy_to_cxcywh(xyxy, inplace):
if not inplace:
xyxy = xyxy.clone()
xyxy[..., 2:].sub_(xyxy[..., :2])
xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor")
return xyxy
def _cxcywh_to_xyxy(cxcywh, inplace):
if not inplace:
cxcywh = cxcywh.clone()
half_wh = cxcywh[..., 2:].div(-2, rounding_mode=None if cxcywh.is_floating_point() else "floor").abs_()
cxcywh[..., :2].sub_(half_wh)
cxcywh[..., 2:].add_(cxcywh[..., :2])
return cxcywh
def _xyxy_to_xywh(xyxy, inplace):
xywh = xyxy if inplace else xyxy.clone()
xywh[..., 2:] -= xywh[..., :2]
return xywh
# New direct conversion functions
def _xywh_to_cxcywh(xywh, inplace):
if not inplace:
xywh = xywh.clone()
xywh[..., :2].add_(xywh[..., 2:].div(2, rounding_mode=None if xywh.is_floating_point() else "floor"))
return xywh
def _cxcywh_to_xywh(cxcywh, inplace):
if not inplace:
cxcywh = cxcywh.clone()
half_wh = cxcywh[..., 2:].div(-2, rounding_mode=None if cxcywh.is_floating_point() else "floor").abs_()
cxcywh[..., :2].sub_(half_wh)
return cxcywh
def benchmark(func, data, warmup=10, iterations=100):
for _ in range(warmup):
func(data.clone(), inplace=False)
start = time.perf_counter()
for _ in range(iterations):
func(data.clone(), inplace=False)
return (time.perf_counter() - start) / iterations * 1000
# Run benchmark
for num_boxes, dtype in [(100, torch.float32), (1000, torch.float32), (10000, torch.float32), (1000, torch.int64)]:
data = torch.rand(num_boxes, 4, dtype=dtype) * 1000 if dtype.is_floating_point else torch.randint(0, 1000, (num_boxes, 4), dtype=dtype)
direct = benchmark(lambda x, i: _xywh_to_cxcywh(x, i), data)
two_step = benchmark(lambda x, i: _xyxy_to_cxcywh(_xywh_to_xyxy(x, False), False), data)
print(f"{num_boxes} boxes, {dtype}: direct={direct:.4f}ms, two-step={two_step:.4f}ms, speedup={two_step/direct:.2f}x")I've also added the parity test in the latest commit (992ef20). Regarding PR #9322 - I'll apply the similar fix to |
zy1git
left a comment
There was a problem hiding this comment.
left a comment on the test.
| ("old_format", "new_format"), | ||
| [ | ||
| (tv_tensors.BoundingBoxFormat.XYWH, tv_tensors.BoundingBoxFormat.CXCYWH), | ||
| (tv_tensors.BoundingBoxFormat.CXCYWH, tv_tensors.BoundingBoxFormat.XYWH), | ||
| ], | ||
| ) |
There was a problem hiding this comment.
The "new_format" is not passed to the test function. We can remove it, correct?
|
Good point on both!
|
|
@raimbekovm The new commit looks great! Thank you for your contribution! However, it seems that the CI test fails because of a Lint problem. The error is that The ufmt formatter expects lines 184-186 of the _meta.py to be a single line instead of being split across three lines. The thing is that you don't need to manually fix this. If you follow the contributing guide to set up your env, when you commit, the ufmt will do the linting fix automatically. Could you try that? |
|
Fixed! Thanks for the hint about ufmt. |
|
@raimbekovm I looked through the past comments and in this comment, could you please apply the similar fix to _cxcywh_to_xywh since the PR#9322 has been merged? Thank you! |
Use float arithmetic instead of the ceil trick (div(-2, floor).abs_()) to match the fix applied to _cxcywh_to_xyxy in PR pytorch#9322.
|
@zy1git Hi! Applied the fix in 97899fd — replaced the ceil trick ( Note: for integer tensors, the width/height also need to be recomputed after truncation to match the two-step path (CXCYWH → XYXY → XYWH), since Please also merge upstream main into this branch to pick up the #9322 fix for |
|
@raimbekovm Hi, thanks a lot for the commit. Usually, the author can and should merge upstream main to their own branch. Could you please merge that? And it seems that there are some conflicts to resolve. Feel free to let us know if you have any questions. |
…cywh-conversion # Conflicts: # test/test_transforms_v2.py
| ) | ||
| @pytest.mark.parametrize("dtype", [torch.float32, torch.int64]) | ||
| @pytest.mark.parametrize("device", cpu_and_cuda()) | ||
| def test_xywh_cxcywh_direct_conversion_inplace(self, old_format, dtype, device): |
There was a problem hiding this comment.
Thanks for adding this test. We actually already have one for testing the inplace parameter: test_kernel_inplace . The thing is, it's not testing all the branches in the code, because some are only triggered on int or float dtypes. I think we should be able to remove this new test and just extend test_kernel_inplace to parametrize over the dtype as well.
NicolasHug
left a comment
There was a problem hiding this comment.
LGTM, thanks a lot for the PR @raimbekovm !
|
Hey @zy1git! You merged this PR, but no labels were added. |
|
Here is the updated benchmark results:
Benchmark Scriptimport torch
import time
# Import directly from torchvision (not copy-pasted functions)
from torchvision.transforms.v2.functional._meta import (
_xywh_to_cxcywh,
_cxcywh_to_xywh,
_xywh_to_xyxy,
_xyxy_to_cxcywh,
_cxcywh_to_xyxy,
_xyxy_to_xywh,
)
def benchmark(func, data, inplace, warmup=10, iterations=100):
for _ in range(warmup):
func(data.clone(), inplace)
start = time.perf_counter()
for _ in range(iterations):
func(data.clone(), inplace)
return (time.perf_counter() - start) / iterations * 1000
# Configurations matching the author's benchmark results
configs = [
# float32 tests
(100, torch.float32),
(1000, torch.float32),
(10000, torch.float32),
(100000, torch.float32),
# int64 tests
(100, torch.int64),
(1000, torch.int64),
(10000, torch.int64),
]
# Test both inplace=False and inplace=True
for inplace in [False, True]:
print()
print(f"{'='*90}")
print(f" inplace={inplace}")
print(f"{'='*90}")
print(f"{'num_boxes':>10} {'dtype':>13} {'conversion':>18} {'direct':>12} {'two-step':>12} {'speedup':>10}")
print("-" * 80)
for num_boxes, dtype in configs:
# Generate test data (matching author's approach)
data = torch.rand(num_boxes, 4, dtype=dtype) * 1000 if dtype.is_floating_point else torch.randint(0, 1000, (num_boxes, 4), dtype=dtype)
# XYWH -> CXCYWH
direct = benchmark(lambda x, i: _xywh_to_cxcywh(x, i), data, inplace)
two_step = benchmark(lambda x, i: _xyxy_to_cxcywh(_xywh_to_xyxy(x, i), i), data, inplace)
print(f"{num_boxes:>10,} {str(dtype):>13} {'xywh_to_cxcywh':>18} {direct:>10.4f}ms {two_step:>10.4f}ms {two_step/direct:>9.2f}x")
# CXCYWH -> XYWH
cxcywh_data = _xywh_to_cxcywh(data.clone(), inplace=False)
direct = benchmark(lambda x, i: _cxcywh_to_xywh(x, i), cxcywh_data, inplace)
two_step = benchmark(lambda x, i: _xyxy_to_xywh(_cxcywh_to_xyxy(x, i), i), cxcywh_data, inplace)
print(f"{num_boxes:>10,} {str(dtype):>13} {'cxcywh_to_xywh':>18} {direct:>10.4f}ms {two_step:>10.4f}ms {two_step/direct:>9.2f}x") |
|
Thank you @NicolasHug and @zy1git for the reviews! |
|
I've updated the description |
Summary
Implements direct conversion between XYWH and CXCYWH bounding box formats, removing the need for intermediate XYXY conversion. This resolves the TODO comment in
_convert_bounding_box_format().Performance improvement: ~2x faster for XYWH↔CXCYWH conversions by eliminating the intermediate XYXY allocation and extra arithmetic.
Changes
torchvision/transforms/v2/functional/_meta.py_xywh_to_cxcywh()for direct XYWH → CXCYWH conversion_cxcywh_to_xywh()for direct CXCYWH → XYWH conversion, using float arithmetic for integer tensors to match the fix in Fix CXCYWH to XYXY conversion for integer bounding boxes #9322_convert_bounding_box_format()to use direct conversions and removed the TODO commenttest/test_transforms_v2.pytest_xywh_cxcywh_direct_conversion_parity) verifying direct conversions match the two-step path across float32/float64/int32/int64 dtypes and CPU/CUDA devicestest_kernel_inplaceto cover integer dtypes