Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: reduce redundant MPS test work (#4167)

Dmytro Mishkin5c5981fcca35
diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.py
index 0d726000f..4f49a1602 100644
--- a/tests/contrib/test_kmeans.py
+++ b/tests/contrib/test_kmeans.py
@@ -24,9 +24,10 @@ from testing.base import BaseTester
class TestKMeans(BaseTester):
- @pytest.mark.parametrize("num_clusters", [3, 10, 1])
- @pytest.mark.parametrize("tolerance", [10e-4, 10e-5, 10e-1])
- @pytest.mark.parametrize("max_iterations", [10, 1000])
+ @pytest.mark.parametrize(
+ ("num_clusters", "tolerance", "max_iterations"),
+ [(3, 1e-4, 3), (10, 1e-3, 1000), (1, 1.0, 10)],
+ )
def test_smoke(self, device, dtype, num_clusters, tolerance, max_iterations):
N = 1000
D = 2
@@ -46,7 +47,7 @@ class TestKMeans(BaseTester):
assert out2.dtype == dtype
@pytest.mark.parametrize("num_clusters", [3])
- @pytest.mark.parametrize("tolerance", [10e-4])
+ @pytest.mark.parametrize("tolerance", [1e-3])
@pytest.mark.parametrize("max_iterations", [100])
def test_cardinality(self, device, dtype, num_clusters, tolerance, max_iterations):
N = 1000
@@ -67,24 +68,24 @@ class TestKMeans(BaseTester):
# case: cluster_center = 0:
with pytest.raises(BaseError) as errinfo:
- kornia.contrib.KMeans(0, None, 10e-4, 10, 0)
+ kornia.contrib.KMeans(0, None, 1e-3, 10, 0)
assert "num_clusters can't be 0" in str(errinfo.value)
# case: cluster centers is not a 2D tensor
with pytest.raises(ShapeError) as errinfo:
starting_centers = torch.rand((2, 3, 5), device=device, dtype=dtype)
- kmeans = kornia.contrib.KMeans(None, starting_centers, 10e-4, 100, 0)
+ kmeans = kornia.contrib.KMeans(None, starting_centers, 1e-3, 100, 0)
assert "Shape dimension mismatch" in str(errinfo.value)
# case: input data is not a 2D tensor
with pytest.raises(ShapeError) as errinfo:
- kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)
+ kmeans = kornia.contrib.KMeans(3, None, 1e-3, 100, 0)
kmeans.fit(torch.rand((1000, 5, 60), dtype=dtype, device=device))
assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)
# case: column dimensions of cluster centers and data to be predicted do not match
with pytest.raises(Exception) as errinfo:
- kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)
+ kmeans = kornia.contrib.KMeans(3, None, 1e-3, 100, 0)
kmeans.fit(torch.rand((1000, 5), dtype=dtype))
kmeans.predict(torch.rand((10, 7), dtype=dtype))
assert "7 != 5" in str(errinfo)
@@ -109,7 +110,7 @@ class TestKMeans(BaseTester):
def test_module(self, device, dtype):
x = TestKMeans._create_data(device, dtype)
- kmeans = kornia.contrib.KMeans(3, None, 10e-4, 10000, 2023)
+ kmeans = kornia.contrib.KMeans(3, None, 1e-3, 10000, 2023)
kmeans.fit(x)
centers = kmeans.cluster_centers
@@ -130,7 +131,7 @@ class TestKMeans(BaseTester):
def test_dynamo(self, device, dtype, torch_optimizer):
x = TestKMeans._create_data(device, dtype)
- kmeans_params = (3, None, 10e-4, 10000, 2023)
+ kmeans_params = (3, None, 1e-3, 10000, 2023)
predict_param = torch.tensor([[-14, 16], [45, 12]], dtype=dtype, device=device)
kmeans = kornia.contrib.KMeans(*kmeans_params)
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index 2ea2ae721..3649310b7 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -36,14 +36,25 @@ class TestEqualization(BaseTester):
assert res.device == img.device
assert res.dtype == img.dtype
- @pytest.mark.parametrize("B, C", [(None, 1), (None, 3), (1, 1), (1, 3), (4, 1), (4, 3)])
- def test_cardinality(self, B, C, device, dtype):
+ @pytest.mark.parametrize(
+ ("B", "C", "grid_size"),
+ [
+ (None, 1, (2, 2)),
+ (None, 3, (2, 2)),
+ (1, 1, (2, 2)),
+ (1, 3, (2, 2)),
+ (4, 1, (2, 2)),
+ (4, 3, (2, 2)),
+ (4, 3, (8, 8)),
+ ],
+ )
+ def test_cardinality(self, B, C, grid_size, device, dtype):
H, W = 10, 20
if B is None:
img = torch.rand(C, H, W, device=device, dtype=dtype)
else:
img = torch.rand(B, C, H, W, device=device, dtype=dtype)
- res = enhance.equalize_clahe(img)
+ res = enhance.equalize_clahe(img, grid_size=grid_size)
assert res.shape == img.shape
@pytest.mark.parametrize("clip, grid", [(0.0, None), (None, (2, 2)), (2.0, (2, 2))])
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index cd4e3a748..f02c23240 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -33,8 +33,7 @@ class TestGuidedBlur(BaseTester):
@pytest.mark.parametrize("guide_dim", [1, 3])
@pytest.mark.parametrize("input_dim", [1, 3])
@pytest.mark.parametrize("kernel_size", [5, (3, 5)])
- @pytest.mark.parametrize("eps", [0.1, 0.01])
- def test_smoke(self, batch_size, guide_dim, input_dim, kernel_size, eps, device, dtype):
+ def test_smoke(self, batch_size, guide_dim, input_dim, kernel_size, device, dtype):
H, W = 8, 16
guide = torch.randn(batch_size, guide_dim, H, W, device=device, dtype=dtype)
inp = torch.randn(batch_size, input_dim, H, W, device=device, dtype=dtype)
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index 10826f90c..c5994a882 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -21,6 +21,7 @@ from kornia.losses.mutual_information import (
MIKernel,
MILossFromRef,
NMILossFromRef,
+ _normalize_signal,
mutual_information_loss,
mutual_information_loss_2d,
normalized_mutual_information_loss,
@@ -140,57 +141,53 @@ class TestMutualInformationLoss(BaseTester):
for _ in range(10):
self.value_ranges_check(device, dtype)
+ def test_trivial_signal_normalizes_to_zero(self, device, dtype):
+ signal = torch.tensor([[0.25, 0.25, 0.25], [0.75, 0.75, 0.75]], device=device, dtype=dtype)
+
+ self.assert_close(_normalize_signal(signal, num_bins=64), torch.zeros_like(signal))
+
@pytest.mark.parametrize("kernel", [MIKernel.xu, MIKernel.rectangular, MIKernel.truncated_gaussian])
- @pytest.mark.parametrize("dim_param", range(5))
- def test_batch_consistency(self, device, dtype, kernel, dim_param):
+ @pytest.mark.parametrize("dims", [(5,), (3, 1), (2, 8), (2, 1, 8), (2, 1, 2, 8), (2, 1, 2, 1, 8)])
+ def test_batch_consistency(self, device, dtype, kernel, dims):
torch.manual_seed(0) # Fix seed for reproducibility
- # Create random dimensions
- dims = torch.randint(low=1, high=8, size=(dim_param + 1,))
- dims = tuple(map(int, dims))
-
- for _ in range(3):
- img1 = torch.rand(dims, device=device, dtype=dtype)
- img2 = torch.rand(dims, device=device, dtype=dtype)
-
- # flatten batch dims
- unique_batch_dim_1 = img1.reshape((-1,) + img1.shape[-1:])
- unique_batch_dim_2 = img2.reshape((-1,) + img1.shape[-1:])
-
- # Compute batch loss
- loss_batch = mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
- normalized_loss_batch = normalized_mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
-
- # Compute iterative loss for verification
- losses = []
- normalized_losses = []
- for i in range(unique_batch_dim_1.shape[0]):
- loss = mutual_information_loss(
- unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
- )
- normalized_loss = normalized_mutual_information_loss(
- unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
- )
- losses.append(loss)
- normalized_losses.append(normalized_loss)
-
- loss_iterative = torch.stack(losses)
- normalized_loss_iterative = torch.stack(normalized_losses)
-
- # Compare
- assert loss_batch.shape == dims[:-1], (
- f"The shape of the batched losses for mi is wrong: {loss_batch.shape} vs {dims[:-1]}."
- )
- assert normalized_loss_batch.shape == dims[:-1], (
- f"The shape of the batched losses for nmi is wrong: {normalized_loss_batch.shape} vs {dims[:-1]}."
- )
+ img1 = torch.rand(dims, device=device, dtype=dtype)
+ img2 = torch.rand(dims, device=device, dtype=dtype)
+
+ # flatten batch dims
+ unique_batch_dim_1 = img1.reshape((-1,) + img1.shape[-1:])
+ unique_batch_dim_2 = img2.reshape((-1,) + img2.shape[-1:])
+
+ # Compute batch loss
+ loss_batch = mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
+ normalized_loss_batch = normalized_mutual_information_loss(img1, img2, num_bins=64, kernel_function=kernel)
- assert torch.allclose(loss_batch.flatten(), loss_iterative, atol=1e-4), (
- f"Batch mismatch for mi! Batch: {loss_batch}, Iterative: {loss_iterative}"
+ # Compute iterative loss for verification
+ losses = []
+ normalized_losses = []
+ for i in range(unique_batch_dim_1.shape[0]):
+ loss = mutual_information_loss(
+ unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
)
- assert torch.allclose(normalized_loss_batch.flatten(), normalized_loss_iterative, atol=1e-4), (
- f"Batch mismatch for nmi! Batch: {normalized_loss_batch}, Iterative: {normalized_loss_iterative}"
+ normalized_loss = normalized_mutual_information_loss(
+ unique_batch_dim_1[i], unique_batch_dim_2[i], num_bins=64, kernel_function=kernel
)
+ losses.append(loss)
+ normalized_losses.append(normalized_loss)
+
+ loss_iterative = torch.stack(losses)
+ normalized_loss_iterative = torch.stack(normalized_losses)
+
+ # Compare
+ assert loss_batch.shape == dims[:-1], (
+ f"The shape of the batched losses for mi is wrong: {loss_batch.shape} vs {dims[:-1]}."
+ )
+ assert normalized_loss_batch.shape == dims[:-1], (
+ f"The shape of the batched losses for nmi is wrong: {normalized_loss_batch.shape} vs {dims[:-1]}."
+ )
+
+ self.assert_close(loss_batch.flatten(), loss_iterative)
+ self.assert_close(normalized_loss_batch.flatten(), normalized_loss_iterative)
def test_module(self, device, dtype):
pred = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
diff --git a/tests/models/test_vision_transformer.py b/tests/models/test_vision_transformer.py
index 6e87c8b5c..160f3bf3b 100644
--- a/tests/models/test_vision_transformer.py
+++ b/tests/models/test_vision_transformer.py
@@ -24,16 +24,24 @@ from testing.base import BaseTester
class TestVisionTransformer(BaseTester):
- @pytest.mark.parametrize("B", [1, 2])
- @pytest.mark.parametrize("H", [1, 3, 8])
- @pytest.mark.parametrize("D", [240, 768])
- @pytest.mark.parametrize("image_size", [32, 224])
+ @pytest.mark.parametrize(
+ ("B", "H", "D", "image_size"),
+ [
+ (2, 1, 240, 32),
+ (1, 1, 768, 224),
+ (2, 3, 768, 32),
+ (1, 3, 240, 224),
+ (2, 8, 240, 224),
+ (1, 8, 768, 32),
+ ],
+ )
def test_smoke(self, device, dtype, B, H, D, image_size):
patch_size = 16
+ depth = 2
T = image_size**2 // patch_size**2 + 1 # tokens size
img = torch.rand(B, 3, image_size, image_size, device=device, dtype=dtype)
- vit = VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)
+ vit = VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D, depth=depth).to(device, dtype)
out = vit(img)
assert isinstance(out, torch.Tensor)
@@ -41,7 +49,7 @@ class TestVisionTransformer(BaseTester):
feats = vit.encoder_results
assert isinstance(feats, list)
- assert len(feats) == 12
+ assert len(feats) == depth
for f in feats:
assert f.shape == (B, T, D)
@@ -60,3 +68,4 @@ class TestVisionTransformer(BaseTester):
vit = VisionTransformer(backbone=backbone_mock, num_heads=8).to(device, dtype)
out = vit(img)
assert out.shape == (1, 197, 128)
+ assert len(vit.encoder_results) == 12