π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Fix] Fixes jit tests in feature for pytorch 1.6 (#858)
Edgar Ribab0f168951564
diff --git a/.github/workflows/tests_cpu.yml b/.github/workflows/tests_cpu.ymlindex 3fb2b73d9..df0a9abd9 100644--- a/.github/workflows/tests_cpu.yml+++ b/.github/workflows/tests_cpu.yml@@ -9,7 +9,7 @@ on:- cron: "0 4 * * *"jobs:- tests-cpu:+ tests-cpu-os-versions-fast:runs-on: ${{ matrix.os }}strategy:fail-fast: false@@ -39,3 +39,34 @@ jobs:uses: codecov/codecov-action@v1with:file: ./coverage.xml++ tests-cpu-version-fast:+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest]+ python-version: [3.7]+ pytorch-version: [1.6.0, 1.7.0, 1.7.1]++ steps:+ - uses: actions/checkout@v2+ - name: Setup conda dependencies+ uses: conda-incubator/setup-miniconda@v2+ with:+ auto-update-conda: true+ python-version: ${{ matrix.python-version }}+ - name: Install dependencies+ shell: bash -l {0}+ run: |+ conda install curl make -c conda-forge+ conda install pytorch=${{ matrix.pytorch-version }} cpuonly -c pytorch+ pip install -r requirements-dev.txt+ make install+ - name: Run Tests+ shell: bash -l {0}+ run: pytest -v --device cpu --dtype float32,float64 --cov=kornia --cov-report xml ./test+ - name: Upload coverage+ uses: codecov/codecov-action@v1+ with:+ file: ./coverage.xmldiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 54dc12018..14778b9d1 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -67,7 +67,7 @@ class PatchAffineShapeEstimator(nn.Module):bad_mask = ((ellipse_shape < self.eps).float().sum(dim=2, keepdim=True) >= 2).to(ellipse_shape.dtype)# We will replace degenerate shape with circular shapes.circular_shape = torch.tensor([1.0, 0., 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3)- ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask # type: ignore+ ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask# normalizationellipse_shape = ellipse_shape / ellipse_shape.max(dim=2, keepdim=True)[0]return ellipse_shapediff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex f9ade3d2b..78b323681 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -74,7 +74,7 @@ class HardNet(nn.Module):# training totally unstable.return (x - mp.detach()) / (sp.detach() + eps)- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, input: torch.Tensor) -> torch.Tensor:x_norm: torch.Tensor = self._normalize_input(input)x_features: torch.Tensor = self.features(x_norm)x_out = x_features.view(x_features.size(0), -1)diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 5b8a0dfb2..2038c5fca 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -141,10 +141,14 @@ class VonMisesKernel(nn.Module):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:++ if not len(x.shape) == 4 or x.shape[1] != 1:raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(x.shape))- emb0 = self.emb0.to(x).repeat(x.size(0), 1, 1, 1) # type: ignore++ # TODO: unify the two lines below when pytorch 1.6 support is dropped+ emb0: torch.Tensor = torch.jit.annotate(torch.Tensor, self.emb0)+ emb0 = emb0.to(x).repeat(x.size(0), 1, 1, 1)frange = self.frange.to(x) * xemb1 = torch.cos(frange)emb2 = torch.sin(frange)@@ -310,7 +314,7 @@ class ExplicitSpacialEncoding(nn.Module):# Store precomputed embedding.self.register_buffer('emb', emb.unsqueeze(0))- self.d_emb: int = self.emb.shape[1] # type: ignore+ self.d_emb: int = emb.shape[0]self.out_dims: int = self.in_dims * self.d_embself.odims: int = self.out_dims@@ -328,7 +332,8 @@ class ExplicitSpacialEncoding(nn.Module):def init_kron(self) -> Tuple[torch.Tensor, torch.Tensor]:"""Initialize helper variables to calculate kronecker. """kron = get_kron_order(self.in_dims, self.d_emb)- emb2 = torch.index_select(self.emb, 1, kron[:, 1]) # type: ignore+ _emb = torch.jit.annotate(torch.Tensor, self.emb)+ emb2 = torch.index_select(_emb, 1, kron[:, 1])return emb2, kron[:, 0]def forward(self, x: torch.Tensor) -> torch.Tensor:@@ -338,7 +343,8 @@ class ExplicitSpacialEncoding(nn.Module):if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):raise ValueError("Invalid input shape, we expect Bx{}xHxW. Got: {}".format(self.in_dims, x.shape))- emb1 = torch.index_select(x, 1, self.idx1) # type: ignore+ idx1 = torch.jit.annotate(torch.Tensor, self.idx1)+ emb1 = torch.index_select(x, 1, idx1)output = emb1 * self.emb2output = output.sum(dim=(2, 3))if self.do_l2:@@ -611,8 +617,8 @@ class SimpleKD(nn.Module):output_dims: int = 128) -> None:super().__init__()- relative = kernel_type == 'polar'- sigma = 1.4 * (patch_size / 64)+ relative: bool = kernel_type == 'polar'+ sigma: float = 1.4 * (patch_size / 64)# Sequence of modules.smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex f4d91708d..c07d30e14 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -18,7 +18,7 @@ urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/Oriclass PassLAF(nn.Module):"""Dummy module to use instead of local feature orientation or affine shape estimator"""- def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:"""Args:laf: torch.Tensor: 4d tensor@@ -90,16 +90,17 @@ class PatchDominantGradientOrientation(nn.Module):wo1_big = o_big - bo0_bigbo0_big = bo0_big % self.num_ang_binsbo1_big = (bo0_big + 1) % self.num_ang_bins- wo0_big = (1.0 - wo1_big) * mag # type: ignore+ wo0_big = (1.0 - wo1_big) * magwo1_big = wo1_big * mag- ang_bins = []+ ang_bins_list = []for i in range(0, self.num_ang_bins):- ang_bins.append(F.adaptive_avg_pool2d((bo0_big == i).to(patch.dtype) * wo0_big +- (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1)))- ang_bins = torch.cat(ang_bins, 1).view(-1, 1, self.num_ang_bins) # type: ignore- ang_bins = self.angular_smooth(ang_bins) # type: ignore- values, indices = ang_bins.view(-1, self.num_ang_bins).max(1) # type: ignore- angle = -((2. * pi * indices.to(patch.dtype) / float(self.num_ang_bins)) - pi) # type: ignore+ ang_bins_i = F.adaptive_avg_pool2d((bo0_big == i).to(patch.dtype) * wo0_big ++ (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1))+ ang_bins_list.append(ang_bins_i)+ ang_bins = torch.cat(ang_bins_list, 1).view(-1, 1, self.num_ang_bins)+ ang_bins = self.angular_smooth(ang_bins)+ values, indices = ang_bins.view(-1, self.num_ang_bins).max(1)+ angle = -((2. * pi * indices.to(patch.dtype) / float(self.num_ang_bins)) - pi)return angle@@ -171,7 +172,7 @@ class OriNet(nn.Module):# training totally unstable.return (x - mp.detach()) / (sp.detach() + eps)- def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, patch: torch.Tensor) -> torch.Tensor:"""Args:patch: (torch.Tensor) shape [Bx1xHxW]Returns:@@ -194,14 +195,15 @@ class LAFOrienter(nn.Module):def __init__(self,patch_size: int = 32,num_angular_bins: int = 36,- angle_detector: Optional[nn.Module] = None): # type: ignore+ angle_detector: Optional[nn.Module] = None):super(LAFOrienter, self).__init__()self.patch_size = patch_sizeself.num_ang_bins = num_angular_bins+ self.angle_detector: nn.Moduleif angle_detector is None:- self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins) # type: ignore+ self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins)else:- self.angle_detector = angle_detector # type: ignore+ self.angle_detector = angle_detectorreturndef __repr__(self):diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 7089f361b..049f08fd4 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -66,7 +66,7 @@ class SOSNet(nn.Module):return- def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor: # type: ignore+ def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:descr = self.desc_norm(self.layers(input) + eps)descr = descr.view(descr.size(0), -1)return descr