Skip to content

Add direct XYWH-CXCYWH conversion for better performance - #9326

Merged
zy1git merged 17 commits into
pytorch:mainfrom
raimbekovm:feat/direct-xywh-cxcywh-conversion
Feb 24, 2026
Merged

zy1git merged 17 commits into
pytorch:mainfrom
raimbekovm:feat/direct-xywh-cxcywh-conversion

Conversation

@raimbekovm

@raimbekovm raimbekovm commented Jan 5, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Added _xywh_to_cxcywh() for direct XYWH → CXCYWH conversion
  • Added _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
  • Updated _convert_bounding_box_format() to use direct conversions and removed the TODO comment

test/test_transforms_v2.py

  • Added parity test (test_xywh_cxcywh_direct_conversion_parity) verifying direct conversions match the two-step path across float32/float64/int32/int64 dtypes and CPU/CUDA devices
  • Extended test_kernel_inplace to cover integer dtypes

@pytorch-bot

pytorch-bot Bot commented Jan 5, 2026 •

Copy link
Copy Markdown

🔗 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 Failures

As of commit b4b0eed with merge base 4967c64 (image):

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.

@meta-cla meta-cla Bot added the cla signed label Jan 5, 2026

@zy1git zy1git left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. I left a comment for a minor thing. Feel free to take a look.

@zy1git

zy1git commented Jan 14, 2026

Copy link
Copy Markdown
Contributor

@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 _cxcywh_to_xywh.

@raimbekovm

Copy link
Copy Markdown
Contributor Author

@zy1git Thanks for the review! Here's the benchmark results and script.

Benchmark Results

num_boxes dtype conversion direct two-step speedup
100 float32 xywh_to_cxcywh 0.0043ms 0.0095ms 2.24x
100 float32 cxcywh_to_xywh 0.0043ms 0.0088ms 2.04x
1,000 float32 xywh_to_cxcywh 0.0059ms 0.0135ms 2.29x
1,000 float32 cxcywh_to_xywh 0.0059ms 0.0126ms 2.15x
10,000 float32 xywh_to_cxcywh 0.0333ms 0.0778ms 2.34x
10,000 float32 cxcywh_to_xywh 0.0470ms 0.0885ms 1.88x
100,000 float32 xywh_to_cxcywh 0.2155ms 0.3804ms 1.77x
100,000 float32 cxcywh_to_xywh 0.1969ms 0.3562ms 1.81x
1,000 int64 xywh_to_cxcywh 0.0085ms 0.0176ms 2.06x
1,000 int64 cxcywh_to_xywh 0.0100ms 0.0177ms 1.76x
10,000 int64 xywh_to_cxcywh 0.0741ms 0.1192ms 1.61x
10,000 int64 cxcywh_to_xywh 0.0808ms 0.1229ms 1.52x

Average speedup: ~1.9x (ranges from 1.5x to 2.3x depending on tensor size and dtype)

The speedup comes from avoiding:

  1. Intermediate XYXY tensor allocation
  2. Extra arithmetic operations in the two-step path
Benchmark Script
import 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 _cxcywh_to_xywh once that PR is merged.

@zy1git zy1git left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left a comment on the test.

Comment thread test/test_transforms_v2.py Outdated
Comment on lines +4416 to +4421
("old_format", "new_format"),
[
(tv_tensors.BoundingBoxFormat.XYWH, tv_tensors.BoundingBoxFormat.CXCYWH),
(tv_tensors.BoundingBoxFormat.CXCYWH, tv_tensors.BoundingBoxFormat.XYWH),
],
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "new_format" is not passed to the test function. We can remove it, correct?

@raimbekovm

Copy link
Copy Markdown
Contributor Author

Good point on both!

  1. _xywh_to_cxcywh doesn't need half_wh since it's just a simple div(2).add() — no ceil trick like in _cxcywh_to_xywh. Let me know if you'd still prefer it for consistency.

  2. You're right, new_format is unused — I'll remove it.

@zy1git

zy1git commented Jan 23, 2026 •

Copy link
Copy Markdown
Contributor

@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?

@raimbekovm

Copy link
Copy Markdown
Contributor Author

Fixed! Thanks for the hint about ufmt.

@zy1git

zy1git commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

@raimbekovm
Hi,

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.
@raimbekovm

Copy link
Copy Markdown
Contributor Author

@zy1git Hi! Applied the fix in 97899fd — replaced the ceil trick (div(-2, floor).abs_()) with float arithmetic in _cxcywh_to_xywh, similar to what PR #9322 did for _cxcywh_to_xyxy.

Note: for integer tensors, the width/height also need to be recomputed after truncation to match the two-step path (CXCYWH → XYXY → XYWH), since trunc(x2) - trunc(x1) may differ from the original w.

Please also merge upstream main into this branch to pick up the #9322 fix for _cxcywh_to_xyxy — otherwise the parity test will fail because the two-step reference path still uses the old ceil trick on this branch.

@zy1git

zy1git commented Feb 16, 2026

Copy link
Copy Markdown
Contributor

@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
@raimbekovm

Copy link
Copy Markdown
Contributor Author

@zy1git Done! Merged upstream main and resolved the conflict in test/test_transforms_v2.py — kept both the parity test and the odd dimensions regression test from #9322.

Comment thread test/test_transforms_v2.py Outdated
)
@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):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in this commit

@NicolasHug NicolasHug left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks a lot for the PR @raimbekovm !

@zy1git
zy1git merged commit 0cf8cab into pytorch:main Feb 24, 2026
58 of 62 checks passed
@github-actions

Copy link
Copy Markdown

Hey @zy1git!

You merged this PR, but no labels were added.
The list of valid labels is available at https://github.com/pytorch/vision/blob/main/.github/process_commit.py

@zy1git

zy1git commented Feb 24, 2026 •

Copy link
Copy Markdown
Contributor

Here is the updated benchmark results:
inplace is False:

num_boxes dtype conversion direct two-step speedup
100 float32 xywh_to_cxcywh 0.0111ms 0.0260ms 2.33x
100 float32 cxcywh_to_xywh 0.0110ms 0.0229ms 2.08x
1,000 float32 xywh_to_cxcywh 0.0183ms 0.0425ms 2.33x
1,000 float32 cxcywh_to_xywh 0.0176ms 0.0370ms 2.10x
10,000 float32 xywh_to_cxcywh 0.0850ms 0.2135ms 2.51x
10,000 float32 cxcywh_to_xywh 0.0855ms 0.1789ms 2.09x
100,000 float32 xywh_to_cxcywh 0.7422ms 1.8354ms 2.47x
100,000 float32 cxcywh_to_xywh 0.7439ms 1.5758ms 2.12x
100 int64 xywh_to_cxcywh 0.0106ms 0.0240ms 2.27x
100 int64 cxcywh_to_xywh 0.0266ms 0.0255ms 0.96x
1,000 int64 xywh_to_cxcywh 0.0188ms 0.0451ms 2.40x
1,000 int64 cxcywh_to_xywh 0.0455ms 0.0423ms 0.93x
10,000 int64 xywh_to_cxcywh 0.1126ms 0.2694ms 2.39x
10,000 int64 cxcywh_to_xywh 0.2441ms 0.2175ms 0.89x

inplace is True:

num_boxes dtype conversion direct two-step speedup
100 float32 xywh_to_cxcywh 0.0095ms 0.0234ms 2.46x
100 float32 cxcywh_to_xywh 0.0097ms 0.0204ms 2.11x
1,000 float32 xywh_to_cxcywh 0.0158ms 0.0392ms 2.47x
1,000 float32 cxcywh_to_xywh 0.0162ms 0.0340ms 2.10x
10,000 float32 xywh_to_cxcywh 0.0792ms 0.1979ms 2.50x
10,000 float32 cxcywh_to_xywh 0.0800ms 0.1676ms 2.10x
100,000 float32 xywh_to_cxcywh 0.7098ms 1.8169ms 2.56x
100,000 float32 cxcywh_to_xywh 0.8071ms 1.5355ms 1.90x
100 int64 xywh_to_cxcywh 0.0086ms 0.0212ms 2.48x
100 int64 cxcywh_to_xywh 0.0289ms 0.0266ms 0.92x
1,000 int64 xywh_to_cxcywh 0.0170ms 0.0430ms 2.53x
1,000 int64 cxcywh_to_xywh 0.0531ms 0.0446ms 0.84x
10,000 int64 xywh_to_cxcywh 0.1030ms 0.2534ms 2.46x
10,000 int64 cxcywh_to_xywh 0.2614ms 0.2245ms 0.86x
Benchmark Script
import 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")

@raimbekovm

Copy link
Copy Markdown
Contributor Author

Thank you @NicolasHug and @zy1git for the reviews!

@raimbekovm

Copy link
Copy Markdown
Contributor Author

I've updated the description

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants