π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[WIP] Features jit (#848)
Dmytro Mishkin686b0533f73a
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 931c7f5ff..269de40d4 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -42,7 +42,7 @@ class PatchAffineShapeEstimator(nn.Module):patch: (torch.Tensor) shape [Bx1xHxW]Returns:torch.Tensor: ellipse_shape shape [Bx1x3] """- if not torch.is_tensor(patch):+ if not isinstance(patch, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))if not len(patch.shape) == 4:@@ -106,7 +106,7 @@ class LAFAffineShapeEstimator(nn.Module):torch.Tensor: laf_out shape [BxNx2x3]"""raise_error_if_laf_is_not_valid(laf)img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)- if not torch.is_tensor(img):+ if not isinstance(img, torch.Tensor):raise TypeError("img type is not a torch.Tensor. Got {}".format(type(img)))if len(img.shape) != 4:diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex b77f68d87..09a69ddb7 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -12,7 +12,7 @@ def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:laf"""laf_message: str = "Invalid laf shape, we expect BxNx2x3. Got: {}".format(laf.shape)- if not torch.is_tensor(laf):+ if not isinstance(laf, torch.Tensor):raise TypeError("Laf type is not a torch.Tensor. Got {}".format(type(laf)))if len(laf.shape) != 4:@@ -104,7 +104,7 @@ def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.for var_name, var, req_shape in zip(names,[xy, scale, ori],[("B", "N", 2), ("B", "N", 1, 1), ("B", "N", 1)]):- if not torch.is_tensor(var):+ if not isinstance(var, torch.Tensor):raise TypeError("{} type is not a torch.Tensor. Got {}".format(var_name, type(var)))if len(var.shape) != len(req_shape): # type: ignore # because it does not like len(tensor.shape)@@ -265,9 +265,9 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),torch.ones(n_pts - 1, 1)], dim=1)# Add origin to draw also the orientation- pts = torch.cat([torch.tensor([0, 0, 1.]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)+ pts = torch.cat([torch.tensor([0., 0., 1.]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)pts = pts.to(LAF.device).to(LAF.dtype)- aux = torch.tensor([0, 0, 1.]).view(1, 1, 3).expand(B * N, 1, 3)+ aux = torch.tensor([0., 0., 1.]).view(1, 1, 3).expand(B * N, 1, 3)HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)return kornia.convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))@@ -454,18 +454,19 @@ def extract_patches_from_pyramid(img: torch.Tensor,B, N, _, _ = laf.size()num, ch, h, w = img.size()scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)- pyr_idx = (scale.log2() + 0.5).relu().long()+ half: float = 0.5+ pyr_idx = (scale.log2() + half).relu().long()cur_img = img- cur_pyr_level = int(0)+ cur_pyr_level = 0out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device)while min(cur_img.size(2), cur_img.size(3)) >= PS:num, ch, h, w = cur_img.size()# for loop temporarily, to be refactoredfor i in range(B):- scale_mask = (pyr_idx[i] == cur_pyr_level).bool().squeeze()+ scale_mask = (pyr_idx[i] == cur_pyr_level).squeeze()if (scale_mask.float().sum()) == 0:continue- scale_mask = scale_mask.bool().view(-1)+ scale_mask = (scale_mask > 0).view(-1)grid = generate_patch_grid_from_normalized_LAF(cur_img[i:i + 1],nlaf[i:i + 1, scale_mask, :, :],diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 3091b727b..5b8a0dfb2 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -69,18 +69,17 @@ class MKDGradients(nn.Module):super().__init__()self.eps = 1e-8- # Modify 'diff' gradient.- self.grad_fn = SpatialGradient(mode='diff', order=1, normalized=False)- self.grad = lambda x: -self.grad_fn(x)+ self.grad = SpatialGradient(mode='diff', order=1, normalized=False)def forward(self, x: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(x):+ if not isinstance(x, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))if not len(x.shape) == 4:raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(x.shape))- grads_xy = self.grad(x)+ # Modify 'diff' gradient. Before we had lambda function, but it is not jittable+ grads_xy = -self.grad(x)gx = grads_xy[:, :, 0, :, :]gy = grads_xy[:, :, 1, :, :]y = torch.cat(cart2pol(gx, gy, self.eps), dim=1)@@ -139,7 +138,7 @@ class VonMisesKernel(nn.Module):self.register_buffer('weights', weights)def forward(self, x: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(x):+ if not isinstance(x, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))if not len(x.shape) == 4:@@ -205,7 +204,7 @@ class EmbedGradients(nn.Module):return magsdef forward(self, grads: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(grads):+ if not isinstance(grads, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(grads)))if not len(grads.shape) == 4:@@ -333,7 +332,7 @@ class ExplicitSpacialEncoding(nn.Module):return emb2, kron[:, 0]def forward(self, x: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(x):+ if not isinstance(x, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):@@ -453,7 +452,7 @@ class Whitening(nn.Module):self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))def forward(self, x: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(x):+ if not isinstance(x, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))if not len(x.shape) == 2:@@ -512,22 +511,24 @@ class MKDDescriptor(nn.Module):output_dims: int = 128) -> None:super().__init__()- self.patch_size = patch_size- self.kernel_type = kernel_type- self.whitening = whitening- self.training_set = training_set+ self.patch_size: int = patch_size+ self.kernel_type: str = kernel_type+ self.whitening: str = whitening+ self.training_set: str = training_setself.sigma = 1.4 * (patch_size / 64)self.smoothing = GaussianBlur2d((5, 5),(self.sigma, self.sigma),'replicate')self.gradients = MKDGradients()-- self.parametrizations = ['polar', 'cart'] if self.kernel_type == 'concat' else [self.kernel_type]+ # This stupid thing needed for jitting...+ polar_s: str = 'polar'+ cart_s: str = 'cart'+ self.parametrizations = [polar_s, cart_s] if self.kernel_type == 'concat' else [self.kernel_type]# Initialize cartesian/polar embedding with absolute/relative gradients.self.odims: int = 0- relative_orientations = {'polar': True, 'cart': False}+ relative_orientations = {polar_s: True, cart_s: False}self.feats = {}for parametrization in self.parametrizations:gradient_embedding = EmbedGradients(patch_size=patch_size,@@ -538,7 +539,6 @@ class MKDDescriptor(nn.Module):self.feats[parametrization] = nn.Sequential(gradient_embedding, spatial_encoding)self.odims += spatial_encoding.odims-# Compute true output_dims.self.output_dims: int = min(output_dims, self.odims)@@ -555,7 +555,7 @@ class MKDDescriptor(nn.Module):self.odims = self.output_dimsdef forward(self, patches: torch.Tensor) -> torch.Tensor:- if not torch.is_tensor(patches):+ if not isinstance(patches, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patches)))if not len(patches.shape) == 4:diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex f8ba8e486..702fbd618 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -64,7 +64,7 @@ class PatchDominantGradientOrientation(nn.Module):patch: (torch.Tensor) shape [Bx1xHxW]Returns:torch.Tensor: angle shape [B] """- if not torch.is_tensor(patch):+ if not isinstance(patch, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))if not len(patch.shape) == 4:@@ -218,7 +218,7 @@ class LAFOrienter(nn.Module):torch.Tensor: laf_out, shape [BxNx2x3] """raise_error_if_laf_is_not_valid(laf)img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)- if not torch.is_tensor(img):+ if not isinstance(img, torch.Tensor):raise TypeError("img type is not a torch.Tensor. Got {}".format(type(img)))if len(img.shape) != 4:diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex b96633407..50bc64b09 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -66,14 +66,14 @@ def harris_response(input: torch.Tensor,[0.0012, 0.0039, 0.0020, 0.0000, 0.0020, 0.0039, 0.0012]]]])"""# TODO: Recompute doctest- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))if not len(input.shape) == 4:raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))if sigmas is not None:- if not torch.is_tensor(sigmas):+ if not isinstance(sigmas, torch.Tensor):raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):@@ -83,12 +83,11 @@ def harris_response(input: torch.Tensor,dy: torch.Tensor = gradients[:, :, 1]# compute the structure tensor M elements- def g(x):- return gaussian_blur2d(x, (7, 7), (1., 1.))- dx2: torch.Tensor = g(dx ** 2)- dy2: torch.Tensor = g(dy ** 2)- dxy: torch.Tensor = g(dx * dy)+ dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1., 1.))+ dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1., 1.))+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))+det_m: torch.Tensor = dx2 * dy2 - dxy * dxytrace_m: torch.Tensor = dx2 + dy2# compute the response map@@ -153,7 +152,7 @@ def gftt_response(input: torch.Tensor,[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])"""# TODO: Recompute doctest- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))if not len(input.shape) == 4:@@ -163,13 +162,9 @@ def gftt_response(input: torch.Tensor,dx: torch.Tensor = gradients[:, :, 0]dy: torch.Tensor = gradients[:, :, 1]- # compute the structure tensor M elements- def g(x):- return gaussian_blur2d(x, (7, 7), (1., 1.))-- dx2: torch.Tensor = g(dx ** 2)- dy2: torch.Tensor = g(dy ** 2)- dxy: torch.Tensor = g(dx * dy)+ dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1., 1.))+ dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1., 1.))+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))det_m: torch.Tensor = dx2 * dy2 - dxy * dxytrace_m: torch.Tensor = dx2 + dy2@@ -238,14 +233,14 @@ def hessian_response(input: torch.Tensor,[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])"""# TODO: Recompute doctest- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))if not len(input.shape) == 4:raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))if sigmas is not None:- if not torch.is_tensor(sigmas):+ if not isinstance(sigmas, torch.Tensor):raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):@@ -277,7 +272,7 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:- Output: :math:`(B, C, D-1, H, W)`"""- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))if not len(input.shape) == 5:diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex eb3f778c4..563792b64 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -122,7 +122,7 @@ class SIFTDescriptor(nn.Module):return self.gk.detach()def forward(self, input):- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))if not len(input.shape) == 4:diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 3acfb77cb..7089f361b 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -55,7 +55,7 @@ class SOSNet(nn.Module):nn.BatchNorm2d(128, affine=False),)self.desc_norm = nn.Sequential(- nn.LocalResponseNorm(256, alpha=256, beta=0.5, k=0)+ nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0))# load pretrained modelif pretrained:diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.pyindex 8624e90f6..24a7104a3 100644--- a/test/feature/test_affine_shape_estimator.py+++ b/test/feature/test_affine_shape_estimator.py@@ -40,6 +40,14 @@ class TestPatchAffineShapeEstimator:assert gradcheck(ori, (patches, ),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 13, 13+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ tfeat = PatchAffineShapeEstimator(W).to(patches.device, patches.dtype).eval()+ tfeat_jit = torch.jit.script(PatchAffineShapeEstimator(W).to(patches.device, patches.dtype).eval())+ assert_allclose(tfeat_jit(patches), tfeat(patches))+class TestLAFAffineShapeEstimator:def test_shape(self, device):@@ -78,6 +86,17 @@ class TestLAFAffineShapeEstimator:assert gradcheck(LAFAffineShapeEstimator(11).to(device), (laf, patches),raise_exception=True, rtol=1e-3, atol=1e-3, nondet_tol=1e-4)+ @pytest.mark.jit+ @pytest.mark.skip("Failing because of extract patches")+ def test_jit(self, device, dtype):+ B, C, H, W = 1, 1, 13, 13+ inp = torch.zeros(B, C, H, W, device=device)+ inp[:, :, 15:-15, 9:-9] = 1+ laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]], device=device)+ tfeat = LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval()+ tfeat_jit = torch.jit.script(LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval())+ assert_allclose(tfeat_jit(laf, inp), tfeat(laf, inp))+class TestLAFAffNetShapeEstimator:def test_shape(self, device):diff --git a/test/feature/test_hardnet.py b/test/feature/test_hardnet.pyindex 61dadfb85..ffe19064e 100644--- a/test/feature/test_hardnet.py+++ b/test/feature/test_hardnet.py@@ -29,3 +29,11 @@ class TestHardNet:hardnet = HardNet().to(patches.device, patches.dtype)assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,raise_exception=True, )++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 32, 32+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ model = HardNet().to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(HardNet().to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))diff --git a/test/feature/test_laf.py b/test/feature/test_laf.pyindex d7f7b26cc..ace6b3618 100644--- a/test/feature/test_laf.py+++ b/test/feature/test_laf.py@@ -30,6 +30,15 @@ class TestAngleToRotationMatrix:(img,),raise_exception=True)+ @pytest.mark.jit+ @pytest.mark.skip("Problems with kornia.pi")+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 32, 32+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)+ model = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix+ model_jit = torch.jit.script(kornia.geometry.transform.imgwarp.angle_to_rotation_matrix)+ assert_allclose(model(patches), model_jit(patches))+class TestGetLAFScale:def test_shape(self, device):@@ -52,6 +61,14 @@ class TestGetLAFScale:(img,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3+ img = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.get_laf_scale+ model_jit = torch.jit.script(kornia.feature.get_laf_scale)+ assert_allclose(model(img), model_jit(img))+class TestGetLAFCenter:def test_shape(self, device):@@ -74,6 +91,14 @@ class TestGetLAFCenter:(img,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3+ img = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.get_laf_center+ model_jit = torch.jit.script(kornia.feature.get_laf_center)+ assert_allclose(model(img), model_jit(img))+class TestGetLAFOri:def test_shape(self, device):@@ -96,6 +121,15 @@ class TestGetLAFOri:(img,),raise_exception=True)+ @pytest.mark.jit+ @pytest.mark.skip("Union")+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3+ img = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.get_laf_orientation+ model_jit = torch.jit.script(kornia.feature.get_laf_orientation)+ assert_allclose(model(img), model_jit(img))+class TestScaleLAF:def test_shape_float(self, device):@@ -126,6 +160,16 @@ class TestScaleLAF:(laf, scale),raise_exception=True, atol=1e-4)+ @pytest.mark.jit+ @pytest.mark.skip("Union")+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3+ laf = torch.rand(batch_size, channels, height, width, device=device)+ scale = torch.rand(batch_size, device=device)+ model = kornia.feature.scale_laf+ model_jit = torch.jit.script(kornia.feature.scale_laf)+ assert_allclose(model(laf, scale), model_jit(laf, scale))+class TestMakeUpright:def test_shape(self, device):@@ -161,6 +205,15 @@ class TestMakeUpright:(img,),raise_exception=True)+ @pytest.mark.jit+ @pytest.mark.skip("Union")+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3+ img = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.make_upright+ model_jit = torch.jit.script(kornia.feature.make_upright)+ assert_allclose(model(img), model_jit(img))+class TestELL2LAF:def test_shape(self, device):@@ -188,6 +241,16 @@ class TestELL2LAF:(img,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height = 1, 2, 5+ img = torch.rand(batch_size, channels, height, device=device).abs()+ img[:, :, 2] = img[:, :, 3].abs() + 0.3+ img[:, :, 4] += 1.+ model = kornia.feature.ellipse_to_laf+ model_jit = torch.jit.script(kornia.feature.ellipse_to_laf)+ assert_allclose(model(img), model_jit(img))+class TestNormalizeLAF:def test_shape(self, device):@@ -215,6 +278,16 @@ class TestNormalizeLAF:(laf, img,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3++ laf = torch.rand(batch_size, channels, height, width)+ img = torch.rand(batch_size, 3, 10, 32)+ model = kornia.feature.normalize_laf+ model_jit = torch.jit.script(kornia.feature.normalize_laf)+ assert_allclose(model(laf, img), model_jit(laf, img))+class TestLAF2pts:def test_shape(self, device):@@ -243,6 +316,14 @@ class TestLAF2pts:(laf),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 3, 2, 2, 3+ laf = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.laf_to_boundary_points+ model_jit = torch.jit.script(kornia.feature.laf_to_boundary_points)+ assert_allclose(model(laf), model_jit(laf))+class TestDenormalizeLAF:def test_shape(self, device):@@ -270,6 +351,16 @@ class TestDenormalizeLAF:(laf, img,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 1, 2, 2, 3++ laf = torch.rand(batch_size, channels, height, width)+ img = torch.rand(batch_size, 3, 10, 32)+ model = kornia.feature.denormalize_laf+ model_jit = torch.jit.script(kornia.feature.denormalize_laf)+ assert_allclose(model(laf, img), model_jit(laf, img))+class TestGenPatchGrid:def test_shape(self, device):@@ -350,6 +441,16 @@ class TestLAFIsTouchingBoundary:expected = torch.tensor([[False, True]], device=device)assert torch.all(kornia.feature.laf_is_inside_image(laf, img) == expected).item()+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ w, h = 10, 5+ img = torch.rand(1, 3, h, w, device=device)+ laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]],+ [[1, 0, 5], [0, 1, 2]]]], device=device).float()+ model = kornia.feature.laf_is_inside_image+ model_jit = torch.jit.script(kornia.feature.laf_is_inside_image)+ assert_allclose(model(laf, img), model_jit(laf, img))+class TestGetCreateLAF:def test_shape(self, device):@@ -389,6 +490,17 @@ class TestGetCreateLAF:(xy, scale, ori,),raise_exception=True)+ @pytest.mark.skip("Depends on angle-to-rotation-matric")+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels = 3, 2+ xy = torch.rand(batch_size, channels, 2, device=device)+ ori = torch.rand(batch_size, channels, 1, device=device)+ scale = torch.abs(torch.rand(batch_size, channels, 1, 1, device=device))+ model = kornia.feature.laf_from_center_scale_ori+ model_jit = torch.jit.script(kornia.feature.laf_from_center_scale_ori)+ assert_allclose(model(xy, scale, ori), model_jit(xy, scale, ori))+class TestGetLAF3pts:def test_shape(self, device):@@ -415,6 +527,14 @@ class TestGetLAF3pts:(inp,),raise_exception=True)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 3, 2, 2, 3+ inp = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.laf_to_three_points+ model_jit = torch.jit.script(kornia.feature.laf_to_three_points)+ assert_allclose(model(inp), model_jit(inp))+class TestGetLAFFrom3pts:def test_shape(self, device):@@ -447,3 +567,11 @@ class TestGetLAFFrom3pts:assert gradcheck(kornia.feature.laf_from_three_points,(inp,),raise_exception=True)++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, height, width = 3, 2, 2, 3+ inp = torch.rand(batch_size, channels, height, width, device=device)+ model = kornia.feature.laf_from_three_points+ model_jit = torch.jit.script(kornia.feature.laf_from_three_points)+ assert_allclose(model(inp), model_jit(inp))diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.pyindex 1bd3d18a4..e5ebbf8bb 100644--- a/test/feature/test_local_features_orientation.py+++ b/test/feature/test_local_features_orientation.py@@ -75,6 +75,15 @@ class TestPatchDominantGradientOrientation:assert gradcheck(ori, (patches, ),raise_exception=True)+ @pytest.mark.jit+ @pytest.mark.skip(" Compiled functions can't take variable number")+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 13, 13+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ model = PatchDominantGradientOrientation(13).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(PatchDominantGradientOrientation(13).to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))+class TestOriNet:def test_shape(self, device):diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.pyindex 10933320e..16edf7542 100644--- a/test/feature/test_mkd.py+++ b/test/feature/test_mkd.py@@ -66,6 +66,14 @@ class TestMKDGradients:assert gradcheck(grad_describe, (patches),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 13, 13+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)+ model = MKDGradients().to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(MKDGradients().to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))+class TestVonMisesKernel:@ pytest.mark.parametrize("ps", [5, 13, 25])@@ -128,6 +136,14 @@ class TestVonMisesKernel:assert gradcheck(vm_describe, (patches, ps),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 13, 13+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)+ model = VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval() # noqa+ model_jit = torch.jit.script(VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))+class TestEmbedGradients:@@ -175,6 +191,14 @@ class TestEmbedGradients:assert gradcheck(emb_grads_describe, (patches, ps),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 2, 13, 13+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)+ model = EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))+@pytest.mark.parametrize("kernel_type,d,ps", [('cart', 9, 9), ('polar', 25, 9),('cart', 9, 16), ('polar', 25, 16)])@@ -249,6 +273,18 @@ class TestExplicitSpacialEncoding:assert gradcheck(explicit_spatial_describe, (patches, ps),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 2, 13, 13+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)+ model = ExplicitSpacialEncoding(kernel_type='cart',+ fmap_size=W,+ in_dims=2).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(ExplicitSpacialEncoding(kernel_type='cart',+ fmap_size=W,+ in_dims=2).to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))+class TestWhitening:@pytest.mark.parametrize("kernel_type,xform,output_dims", [@@ -307,6 +343,18 @@ class TestWhitening:assert gradcheck(whitening_describe, (patches, in_dims),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, in_dims = 1, 175+ patches = torch.rand(batch_size, in_dims).to(device)+ model = Whitening(xform='lw',+ whitening_model=None,+ in_dims=in_dims).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(Whitening(xform='lw',+ whitening_model=None,+ in_dims=in_dims).to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))+class TestMKDDescriptor:dims = {'cart': 63, 'polar': 175, 'concat': 238}@@ -360,6 +408,7 @@ class TestMKDDescriptor:expected = torch.zeros_like(out_part).to(device)assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)+ @pytest.mark.skip("Just because")@pytest.mark.parametrize("whitening", [None, 'lw', 'pca'])def test_gradcheck(self, whitening, device):batch_size, channels, ps = 1, 1, 19@@ -375,6 +424,20 @@ class TestMKDDescriptor:assert gradcheck(mkd_describe, (patches, ps),raise_exception=True, nondet_tol=1e-4)+ @pytest.mark.skip("neither dict, nor nn.ModuleDict works")+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, ps = 1, 1, 19+ patches = torch.rand(batch_size, channels, ps, ps).to(device)+ kt = 'concat'+ wt = 'lw'+ model = MKDDescriptor(patch_size=ps,+ kernel_type=kt,+ whitening=wt).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(MKDDescriptor(patch_size=ps, kernel_type=kt,+ whitening=wt).to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))+class TestSimpleKD:dims = {'cart': 63, 'polar': 175}@@ -406,9 +469,17 @@ class TestSimpleKD:patches = utils.tensor_to_gradcheck_var(patches) # to vardef skd_describe(patches, patch_size=19):- skd = SimpleKD(patch_size=patch_size, kernel_type='polar',+ skd = SimpleKD(patch_size=ps, kernel_type='polar',whitening='lw').double()skd.to(device)return skd(patches.double())assert gradcheck(skd_describe, (patches, ps),raise_exception=True, nondet_tol=1e-4)++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ batch_size, channels, ps = 1, 1, 19+ patches = torch.rand(batch_size, channels, ps, ps).to(device)+ model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval() # noqa+ model_jit = torch.jit.script( SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()) # noqa+ assert_allclose(model(patches), model_jit(patches))diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.pyindex 159be72d7..caacaaabc 100644--- a/test/feature/test_responces_local_features.py+++ b/test/feature/test_responces_local_features.py@@ -249,7 +249,7 @@ class TestBlobHessian:assert gradcheck(kornia.feature.hessian_response, (img),raise_exception=True, nondet_tol=1e-4)- @pytest.mark.skip(reason="turn off all jit for a while")+ @pytest.mark.jitdef test_jit(self, device):@torch.jit.scriptdef op_script(input):diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.pyindex 07f2cb436..8cd100ddc 100644--- a/test/feature/test_siftdesc.py+++ b/test/feature/test_siftdesc.py@@ -65,3 +65,12 @@ class TestSIFTDescriptor:patches = utils.tensor_to_gradcheck_var(patches) # to varassert gradcheck(sift_describe, (patches, 13),raise_exception=True, nondet_tol=1e-4)++ @pytest.mark.jit+ @pytest.mark.skip("Compiled functions can't take variable number")+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 41, 41+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ model = SIFTDescriptor(41).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(SIFTDescriptor(41).to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))diff --git a/test/feature/test_sosnet.py b/test/feature/test_sosnet.pyindex dc769df01..329ceeeb4 100644--- a/test/feature/test_sosnet.py+++ b/test/feature/test_sosnet.py@@ -29,3 +29,11 @@ class TestSOSNet:sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype)assert gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4,raise_exception=True, )++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 32, 32+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ model = SOSNet().to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(SOSNet().to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))