Skip to content

Commit e1efbb4

Browse files
Yosua Michael Maranathafacebook-github-bot
Yosua Michael Maranatha
authored andcommitted
[fbsync] [prototype] Speed up autocontrast_image_tensor (#6935)
Summary: * Performance optimization for autocontrast * Fixing tests Reviewed By: NicolasHug Differential Revision: D41265202 fbshipit-source-id: cd1f9f777ecf56168def256a2ef04335a602684b
1 parent 92a11e3 commit e1efbb4

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

test/test_prototype_transforms_consistency.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,8 @@ def __init__(
251251
ArgsKwargs(p=0),
252252
ArgsKwargs(p=1),
253253
],
254+
# Use default tolerances of `torch.testing.assert_close`
255+
closeness_kwargs=dict(rtol=None, atol=None),
254256
),
255257
ConsistencyConfig(
256258
prototype_transforms.RandomAdjustSharpness,

torchvision/prototype/transforms/functional/_color.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -377,17 +377,23 @@ def autocontrast_image_tensor(image: torch.Tensor) -> torch.Tensor:
377377
return image
378378

379379
bound = _FT._max_value(image.dtype)
380-
dtype = image.dtype if torch.is_floating_point(image) else torch.float32
380+
fp = image.is_floating_point()
381+
float_image = image if fp else image.to(torch.float32)
381382

382-
minimum = image.amin(dim=(-2, -1), keepdim=True).to(dtype)
383-
maximum = image.amax(dim=(-2, -1), keepdim=True).to(dtype)
383+
minimum = float_image.amin(dim=(-2, -1), keepdim=True)
384+
maximum = float_image.amax(dim=(-2, -1), keepdim=True)
384385

385-
scale = bound / (maximum - minimum)
386386
eq_idxs = maximum == minimum
387+
inv_scale = maximum.sub_(minimum).div_(bound)
387388
minimum[eq_idxs] = 0.0
388-
scale[eq_idxs] = 1.0
389+
inv_scale[eq_idxs] = 1.0
390+
391+
if fp:
392+
diff = float_image.sub(minimum)
393+
else:
394+
diff = float_image.sub_(minimum)
389395

390-
return (image - minimum).mul_(scale).clamp_(0, bound).to(image.dtype)
396+
return diff.div_(inv_scale).clamp_(0, bound).to(image.dtype)
391397

392398

393399
autocontrast_image_pil = _FP.autocontrast

0 commit comments

Comments
 (0)