Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Lambda function module (#1346)

Sravan Chittupalli3fef315965fa
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index ea42c3862..8573193dd 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -22,3 +22,8 @@ Image Classification
.. autoclass:: VisionTransformer
.. autoclass:: ClassificationHead
+
+Lambda
+--------------------
+
+.. autoclass:: Lambda
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 778a36d40..70f710c22 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -6,6 +6,7 @@ from kornia.contrib.extract_patches import (
extract_tensor_patches,
ExtractTensorPatches,
)
+from kornia.contrib.lambda_module import Lambda
from kornia.contrib.vit import VisionTransformer
__all__ = [
@@ -15,5 +16,6 @@ __all__ = [
"combine_tensor_patches",
"CombineTensorPatches",
"VisionTransformer",
- "ClassificationHead"
+ "ClassificationHead",
+ "Lambda"
]
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
new file mode 100644
index 000000000..cf3b36109
--- /dev/null
+++ b/kornia/contrib/lambda_module.py
@@ -0,0 +1,25 @@
+from typing import Callable
+
+import torch
+import torch.nn as nn
+
+
+class Lambda(nn.Module):
+ """Applies user-defined lambda as a transform.
+
+ Args:
+ func: Callable function.
+
+ Returns:
+ A torch.Tensor which is the output of the user-defined lambda
+ """
+
+ def __init__(self, func: Callable) -> None:
+ super().__init__()
+ if not callable(func):
+ raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")
+
+ self.func = func
+
+ def forward(self, img: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ return self.func(img, *args, **kwargs)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index be9aac2a4..7eafe2b54 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -276,3 +276,44 @@ class TestCombineTensorPatches:
torch.arange(16., device=device, dtype=dtype).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))
input = utils.tensor_to_gradcheck_var(patches) # to var
assert gradcheck(kornia.contrib.combine_tensor_patches, (input, (2, 2), (2, 2)), raise_exception=True)
+
+
+class TestLambdaModule:
+
+ def add_2_layer(self, tensor):
+ return tensor + 2
+
+ def add_x_mul_y(self, tensor, x, y=2):
+ return torch.mul(tensor + x , y)
+
+ def test_smoke(self, device, dtype):
+ B, C, H, W = 1, 3, 4, 5
+ input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ func = self.add_2_layer
+ if not callable(func):
+ raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")
+ assert isinstance(kornia.contrib.Lambda(func)(input), torch.Tensor)
+
+ @pytest.mark.parametrize("x", [3, 2, 5])
+ def test_lambda_with_arguments(self, x, device, dtype):
+ B, C, H, W = 2, 3, 5, 7
+ input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ func = self.add_x_mul_y
+ lambda_module = kornia.contrib.Lambda(func)
+ out = lambda_module(input, x)
+ assert isinstance(out, torch.Tensor)
+
+ @pytest.mark.parametrize("shape", [(1, 3, 2, 3), (2, 3, 5, 7)])
+ def test_lambda(self, shape, device, dtype):
+ B, C, H, W = shape
+ input = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ func = kornia.bgr_to_grayscale
+ lambda_module = kornia.contrib.Lambda(func)
+ out = lambda_module(input)
+ assert isinstance(out, torch.Tensor)
+
+ def test_grad(self, device, dtype):
+ B, C, H, W = 1, 3, 4, 5
+ input = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
+ func = kornia.bgr_to_grayscale
+ assert gradcheck(kornia.contrib.Lambda(func), (input,), raise_exception=True)