Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(enhance): vectorize per-sample posterize (16x GPU, now fullgraph) (#3824)

Edgar Riba079380646407
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 5078b5bec..36e8e0941 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -809,27 +809,24 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
if len(bits.shape) == 0 or (len(bits.shape) == 1 and len(bits) == 1):
return _posterize_one(input, bits)
- res = []
if len(bits.shape) == 1:
if bits.shape[0] != input.shape[0]:
raise AssertionError(
f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."
)
- for i in range(input.shape[0]):
- res.append(_posterize_one(input[i], bits[i]))
- return torch.stack(res, dim=0)
+ # Broadcast the per-sample bits over (B, C, H, W) and posterize in one vectorised call
+ # instead of a Python loop over the batch (which launched a kernel per sample).
+ return _posterize_one(input, bits.view(-1, *([1] * (input.ndim - 1))))
if bits.shape != input.shape[: len(bits.shape)]:
raise AssertionError(
"Batch and channel must be equal between bits and input. "
f"Got {bits.shape}, {input.shape[: len(bits.shape)]}."
)
- _input = input.view(-1, *input.shape[len(bits.shape) :])
- _bits = bits.flatten()
- for i in range(input.shape[0]):
- res.append(_posterize_one(_input[i], _bits[i]))
- return torch.stack(res, dim=0).reshape(*input.shape)
+ # Broadcast per-(batch, channel) bits over the spatial dims and posterize in one call.
+ _bits = bits.view(*bits.shape, *([1] * (input.ndim - bits.ndim)))
+ return _posterize_one(input, _bits)
@perform_keep_shape_image