π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): validate batch_size and matrix operands in kornia.core.utils (#5456)
Adarsh Mishrad95b1b6f2cf2
diff --git a/changelog.d/5456.fixed.md b/changelog.d/5456.fixed.mdnew file mode 100644index 000000000..368fad474--- /dev/null+++ b/changelog.d/5456.fixed.md@@ -0,0 +1,3 @@+`kornia.core.utils.batched_forward` now rejects a non-positive `batch_size` instead of failing later with+`ZeroDivisionError` or an empty-list `torch.cat` error, and `safe_solve_with_mask` / `_torch_solve_cast` reject a+non-tensor operand with `TypeCheckError` like their siblings `_torch_inverse_cast` and `safe_inverse_with_mask`. (#5456)diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex aec398a77..b83715f21 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -365,6 +365,8 @@ def _torch_solve_cast(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:- kornia.geometry.transform.thin_plate_spline- kornia.geometry.epipolar.essential"""+ KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")+ KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")if is_mps_tensor_safe(A):dtype = torch.float32else:@@ -383,6 +385,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor"""# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622KORNIA_CHECK_IS_TENSOR(B, "B must be torch.Tensor")+ KORNIA_CHECK_IS_TENSOR(A, "A must be torch.Tensor")dtype: torch.dtype = B.dtypeif dtype not in (torch.float32, torch.float64):dtype = torch.float32@@ -566,6 +569,7 @@ def batched_forward(True"""+ KORNIA_CHECK(batch_size > 0, f"batch_size must be positive, got {batch_size}")model_dev = model.to(device)B: int = len(data)bs: int = batch_sizediff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex 8b45251bc..75fb47cd7 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -18,7 +18,7 @@import pytestimport torch-from kornia.core.exceptions import DeviceError, TypeCheckError+from kornia.core.exceptions import BaseError, DeviceError, TypeCheckErrorfrom kornia.core.utils import (_adjugate_closed_form,_extract_device_dtype,@@ -28,6 +28,7 @@ from kornia.core.utils import (_torch_linalg_svdvals,_torch_solve_cast,_torch_svd_cast,+ batched_forward,is_autocast_enabled,is_exporting,is_mps_tensor_safe,@@ -416,6 +417,15 @@ class TestSvdCast:class TestSolveCast:+ def test_rejects_non_tensor_A(self):+ # A was unchecked while its sibling safe_inverse_with_mask checks A (#5201).+ with pytest.raises(TypeCheckError, match=r"A must be torch.Tensor"):+ _torch_solve_cast([[1.0]], torch.ones(2, 2))++ def test_rejects_non_tensor_B(self):+ with pytest.raises(TypeCheckError, match=r"B must be torch.Tensor"):+ _torch_solve_cast(torch.eye(2), [[1.0]])+def test_smoke(self, device, dtype):torch.manual_seed(0)# Exercise a reproducible, well-conditioned system instead of letting a random draw@@ -432,6 +442,10 @@ class TestSolveCast:class TestSolveWithMask:+ def test_rejects_non_tensor_A(self):+ with pytest.raises(TypeCheckError, match=r"A must be torch.Tensor"):+ safe_solve_with_mask(torch.ones(2, 3), [[1.0]])+def test_smoke(self, device, dtype):torch.manual_seed(0) # issue kornia#2027A = torch.randn(2, 3, 1, 4, 4, device=device, dtype=dtype)@@ -455,6 +469,29 @@ class TestSolveWithMask:assert torch.equal(mask, torch.zeros_like(mask))+class TestBatchedForwardBatchSize:+ def test_rejects_zero_batch_size(self):+ # batch_size=0 divided by zero inside the micro-batch loop (#5201).+ model = torch.nn.Linear(2, 3)+ data = torch.rand(5, 2)+ with pytest.raises(BaseError, match="batch_size must be positive, got 0"):+ batched_forward(model, data, torch.device("cpu"), batch_size=0)++ def test_rejects_negative_batch_size(self):+ model = torch.nn.Linear(2, 3)+ data = torch.rand(5, 2)+ with pytest.raises(BaseError, match="batch_size must be positive, got -1"):+ batched_forward(model, data, torch.device("cpu"), batch_size=-1)++ def test_valid_batch_sizes_keep_the_output(self):+ model = torch.nn.Linear(2, 3)+ data = torch.rand(5, 2)+ expected = model(data)+ # 1 is the smallest valid size; 5 == len(data) takes the single-call path+ for bs in (1, 2, 5, 128):+ assert_close(batched_forward(model, data, torch.device("cpu"), batch_size=bs), expected)++class TestInverseWithMask:def test_smoke(self, device, dtype):x = torch.tensor([[4.0, 7.0], [2.0, 6.0]], device=device, dtype=dtype)