Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): accept broadcastable tensor weights in add_weighted (#5349)

Rızgar Ozanc5b27d34cd6e
diff --git a/changelog.d/5349.fixed.md b/changelog.d/5349.fixed.md
new file mode 100644
index 000000000..67dc3614f
--- /dev/null
+++ b/changelog.d/5349.fixed.md
@@ -0,0 +1 @@
+`add_weighted` and `AddWeighted` now accept tensor `alpha`, `beta` and `gamma` that broadcast to the input shape, such as a 0-d scalar or a per-image `(B, 1, 1, 1)` weight. Before, a tensor coefficient had to match the input shape exactly, even though the docstring said broadcastable shapes were allowed. Shapes that would change the output shape are still rejected.
diff --git a/docs/export_support/cases_misc.py b/docs/export_support/cases_misc.py
index 5889b021a..46bcd7d7b 100644
--- a/docs/export_support/cases_misc.py
+++ b/docs/export_support/cases_misc.py
@@ -219,14 +219,14 @@ add(
g,
KE.AddWeighted(torch.full((1, 3, 32, 40), 0.6), torch.full((1, 3, 32, 40), 0.4), torch.full((1, 3, 32, 40), 0.1)),
[IMG, IMG2],
- note="tensor alpha/beta/gamma must equal src shape (kornia check); constructed -> constants",
+ note="tensor alpha/beta/gamma must broadcast to src shape (kornia check); constructed -> constants",
)
add(
"enhance.add_weighted[live_weights]",
g,
KE.add_weighted,
[IMG, torch.full((1, 3, 32, 40), 0.6), IMG2, torch.full((1, 3, 32, 40), 0.4), torch.full((1, 3, 32, 40), 0.1)],
- note="alpha/beta/gamma live tensors (must be full src shape)",
+ note="alpha/beta/gamma live tensors (full src shape here; broadcastable shapes also work)",
)
add("enhance.AdjustBrightness", g, KE.AdjustBrightness(0.2), [IMG])
add("enhance.AdjustBrightnessAccumulative", g, KE.AdjustBrightnessAccumulative(0.2), [IMG])
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index dca9a5a48..e630426a7 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -14593,7 +14593,7 @@
"export_detail": "",
"graph_breaks": 0,
"name": "enhance.AddWeighted[tensor]",
- "note": "tensor alpha/beta/gamma must equal src shape (kornia check); constructed -> constants",
+ "note": "tensor alpha/beta/gamma must broadcast to src shape (kornia check); constructed -> constants",
"onnx": "ok",
"onnx_detail": "",
"operator": "AddWeighted",
@@ -14610,7 +14610,7 @@
"export_detail": "",
"graph_breaks": 0,
"name": "enhance.add_weighted[live_weights]",
- "note": "alpha/beta/gamma live tensors (must be full src shape)",
+ "note": "alpha/beta/gamma live tensors (full src shape here; broadcastable shapes also work)",
"onnx": "ok",
"onnx_detail": "",
"operator": "add_weighted",
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 3e2854f07..9847f422e 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -23,6 +23,12 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
+def _broadcasts_to(shape: torch.Size, target: torch.Size) -> bool:
+ if len(shape) > len(target):
+ return False
+ return all(dim in (1, tdim) for dim, tdim in zip(reversed(shape), reversed(target)))
+
+
def add_weighted(
src1: torch.Tensor,
alpha: Union[float, torch.Tensor],
@@ -34,11 +40,9 @@ def add_weighted(
Convention:
src1 and src2 must have exactly the same shape; a Python number coefficient applies to
- every element. See :class:`AddWeighted` for the module wrapper.
-
- .. warning::
- Tensor alpha, beta and gamma must have src1's exact shape: a 0-d or broadcastable
- tensor raises (`#5325 <https://github.com/kornia/kornia/issues/5325>`_).
+ every element. A tensor coefficient must broadcast to src1's shape without changing it,
+ such as a 0-d scalar or a per-image (B, 1, 1, 1) weight; a mismatched or extra leading axis
+ raises. See :class:`AddWeighted` for the module wrapper.
.. image:: _static/img/add_weighted.png
@@ -49,10 +53,10 @@ def add_weighted(
Args:
src1: torch.Tensor with an arbitrary shape, equal to shape of src2.
- alpha: weight of the src1 elements as Union[float, torch.Tensor].
+ alpha: weight of the src1 elements, a float or a tensor broadcastable to the src1 shape.
src2: torch.Tensor with an arbitrary shape, equal to shape of src1.
- beta: weight of the src2 elements as Union[float, torch.Tensor].
- gamma: scalar added to each sum as Union[float, torch.Tensor].
+ beta: weight of the src2 elements, a float or a tensor broadcastable to the src1 shape.
+ gamma: value added to each sum, a float or a tensor broadcastable to the src1 shape.
Returns:
Weighted torch.Tensor with shape equal to src1 and src2 shapes.
@@ -69,14 +73,12 @@ def add_weighted(
KORNIA_CHECK_IS_TENSOR(src2)
KORNIA_CHECK(src1.shape == src2.shape, f"src1 and src2 have different shapes. Got {src1.shape} and {src2.shape}")
- if isinstance(alpha, torch.Tensor):
- KORNIA_CHECK(src1.shape == alpha.shape, "alpha has a different shape than src.")
-
- if isinstance(beta, torch.Tensor):
- KORNIA_CHECK(src1.shape == beta.shape, "beta has a different shape than src.")
-
- if isinstance(gamma, torch.Tensor):
- KORNIA_CHECK(src1.shape == gamma.shape, "gamma has a different shape than src.")
+ for name, coef in (("alpha", alpha), ("beta", beta), ("gamma", gamma)):
+ if isinstance(coef, torch.Tensor):
+ KORNIA_CHECK(
+ _broadcasts_to(coef.shape, src1.shape),
+ f"{name} with shape {tuple(coef.shape)} does not broadcast to the src shape {tuple(src1.shape)}.",
+ )
return src1 * alpha + src2 * beta + gamma
@@ -85,8 +87,7 @@ class AddWeighted(nn.Module):
r"""Calculate the weighted sum of two Tensors.
Convention:
- See :func:`add_weighted`, including its tensor-coefficient defect
- (`#5325 <https://github.com/kornia/kornia/issues/5325>`_).
+ See :func:`add_weighted`.
The function calculates the weighted sum of two Tensors as follows:
@@ -94,9 +95,9 @@ class AddWeighted(nn.Module):
out = src1 * alpha + src2 * beta + gamma
Args:
- alpha: weight of the src1 elements as Union[float, torch.Tensor].
- beta: weight of the src2 elements as Union[float, torch.Tensor].
- gamma: scalar added to each sum as Union[float, torch.Tensor].
+ alpha: weight of the src1 elements, a float or a tensor broadcastable to the src1 shape.
+ beta: weight of the src2 elements, a float or a tensor broadcastable to the src1 shape.
+ gamma: value added to each sum, a float or a tensor broadcastable to the src1 shape.
Shape:
- Input1: torch.Tensor with an arbitrary shape, equal to shape of Input2.
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index c096cc370..a5344524b 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -25,8 +25,7 @@ from testing.base import BaseTester
class TestEnhanceConventions(BaseTester):
- @pytest.mark.xfail(strict=True, reason="#5325: 0-d tensor coefficients are rejected")
- def test_wart_add_weighted_scalar_tensor_coefficient_5325(self, device, dtype):
+ def test_convention_add_weighted_scalar_tensor_coefficient_5325(self, device, dtype):
src = torch.arange(6, device=device, dtype=dtype).reshape(2, 3)
alpha = torch.tensor(0.5, device=device, dtype=dtype)
self.assert_close(
diff --git a/tests/enhance/test_core.py b/tests/enhance/test_core.py
index 1a42bb578..6474ad053 100644
--- a/tests/enhance/test_core.py
+++ b/tests/enhance/test_core.py
@@ -106,6 +106,30 @@ class TestAddWeighted(BaseTester):
gamma = gamma.to(src1)
self.assert_close(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
+ @pytest.mark.parametrize("coef_shape", [(), (1,), (5,), (2, 1, 1, 1), (1, 3, 1, 1), (3, 5, 5)])
+ def test_broadcastable_tensor_coefficients(self, device, dtype, coef_shape):
+ src1 = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)
+ src2 = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)
+ alpha = torch.rand(coef_shape, device=device, dtype=dtype)
+ beta = torch.rand(coef_shape, device=device, dtype=dtype)
+ gamma = torch.rand(coef_shape, device=device, dtype=dtype)
+
+ actual = TestAddWeighted.fcn(src1, alpha, src2, beta, gamma)
+
+ assert actual.shape == src1.shape
+ self.assert_close(actual, src1 * alpha + src2 * beta + gamma)
+ self.assert_close(kornia.enhance.AddWeighted(alpha, beta, gamma)(src1, src2), actual)
+
+ @pytest.mark.parametrize("name", ["alpha", "beta", "gamma"])
+ @pytest.mark.parametrize("coef_shape", [(4,), (3, 1, 1, 1), (1, 2, 3, 5, 5)])
+ def test_non_broadcastable_tensor_coefficient(self, device, dtype, name, coef_shape):
+ src1 = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)
+ src2 = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)
+ coefs = {"alpha": 0.5, "beta": 0.5, "gamma": 0.0}
+ coefs[name] = torch.rand(coef_shape, device=device, dtype=dtype)
+ with pytest.raises(Exception, match=name):
+ TestAddWeighted.fcn(src1, coefs["alpha"], src2, coefs["beta"], coefs["gamma"])
+
def test_dynamo(self, device, dtype, torch_optimizer):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
inputs = (src1, alpha, src2, beta, gamma)