🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Drop pytorch 1.8 (LTS) support (#2024)
João Gustavo A. Amorimf617c3e54982
diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.pyindex 0977f59cb..86fb728fb 100644--- a/kornia/contrib/vit_mobile.py+++ b/kornia/contrib/vit_mobile.py@@ -4,24 +4,12 @@ import torchfrom torch import nn-class SiLU(nn.Module):- """Module SiLU (Sigmoid Linear Units)-- This implementation is to support pytorch < 1.8, and will be deprecated after 1.8.-- Paper: https://arxiv.org/abs/1702.03118- """-- def forward(self, x: torch.Tensor) -> torch.Tensor:- return x * torch.sigmoid(x)--def conv_1x1_bn(inp: int, oup: int) -> nn.Module:- return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), SiLU())+ return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.SiLU())def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> nn.Module:- return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), SiLU())+ return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.SiLU())class PreNorm(nn.Module):@@ -38,7 +26,7 @@ class FeedForward(nn.Module):def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None:super().__init__()self.net = nn.Sequential(- nn.Linear(dim, hidden_dim), SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout)+ nn.Linear(dim, hidden_dim), nn.SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout))def forward(self, x: torch.Tensor) -> torch.Tensor:@@ -133,7 +121,7 @@ class MV2Block(nn.Module):# depthwisenn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),nn.BatchNorm2d(hidden_dim),- SiLU(),+ nn.SiLU(),# pointwisenn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),nn.BatchNorm2d(oup),@@ -143,11 +131,11 @@ class MV2Block(nn.Module):# pointwisenn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),nn.BatchNorm2d(hidden_dim),- SiLU(),+ nn.SiLU(),# depthwisenn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),nn.BatchNorm2d(hidden_dim),- SiLU(),+ nn.SiLU(),# pointwisenn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),nn.BatchNorm2d(oup),diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex ee5bed195..09a6906ce 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Dict, Optional, Tuple+from typing import Dict, Optional, Tupleimport torchimport torch.nn.functional as F@@ -7,7 +7,6 @@ from kornia.core import Module, Tensor, concatenate, pad, stackfrom kornia.geometry.conversions import normalize_pixel_coordinatesfrom kornia.testing import KORNIA_CHECK_SHAPEfrom kornia.utils import map_location_to_cpu-from packaging import versionfrom .backbones import SOLD2Netfrom .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions@@ -288,14 +287,7 @@ class WunschLineMatcher(Module):topk_lines = torch.argsort(line_scores, dim=1)[:, -self.top_k_candidates :]# topk_lines.shape = (n_lines1, top_k_candidates)- if TYPE_CHECKING:- # TODO: remove this branch if kornia relies on torch>=1.9- top_scores: Tensor- else:- if version.parse(torch.__version__) >= version.parse('1.9.0'):- top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)- else:- NotImplementedError('This method just work with pytorch newer than 1.9.0')+ top_scores = torch.take_along_dim(scores, topk_lines[:, :, None, None], dim=1)# Consider the reversed line segments as welltop_scores = concatenate([top_scores, torch.flip(top_scores, dims=[-1])], 1)diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.pyindex 84a0c9661..e9e3880e1 100755--- a/kornia/nerf/data_utils.py+++ b/kornia/nerf/data_utils.py@@ -164,7 +164,7 @@ def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shufflereturn items[0]if TYPE_CHECKING:- # TODO: remove the type ignore when kornia relies on kornia 1.9.0+ # TODO: remove the type ignore when kornia relies on kornia 1.10return DataLoader(dataset)else:return DataLoader(diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex e837d7adc..0f298f9fd 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -1,13 +1,13 @@"""The testing package contains testing-specific utilities."""-import contextlibimport importlibimport mathfrom abc import ABC, abstractmethodfrom copy import deepcopyfrom itertools import product-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast+from typing import Any, Dict, List, Optional, Tuple, castimport torch+from torch.testing import assert_close as _assert_closefrom kornia.core import Tensor, eye, tensor@@ -255,48 +255,28 @@ def _default_tolerances(*inputs: Any) -> Tuple[float, float]:return max(rtols), max(atols)-if TYPE_CHECKING:- # TODO: remove this branch if kornia relies on torch>=1.9- def assert_close(- actual: Tensor, expected: Tensor, *, rtol: Optional[float] = None, atol: Optional[float] = None, **kwargs: Any- ) -> None:- ...--else:- try:- # torch.testing.assert_close is only available for torch>=1.9- from torch.testing import assert_close as _assert_close-- def assert_close(- actual: Tensor,- expected: Tensor,- *,- rtol: Optional[float] = None,- atol: Optional[float] = None,- **kwargs: Any,- ) -> None:- if rtol is None and atol is None:- # `torch.testing.assert_close` used different default tolerances than `torch.testing.assert_allclose`.- # TODO: remove this special handling as soon as https://github.com/kornia/kornia/issues/1134 is resolved- # Basically, this whole wrapper function can be removed and `torch.testing.assert_close` can be used- # directly.- rtol, atol = _default_tolerances(actual, expected)-- return _assert_close(- actual,- expected,- rtol=rtol,- atol=atol,- # this is the default value for torch>=1.10, but not for torch==1.9- # TODO: remove this if kornia relies on torch>=1.10- check_stride=False,- equal_nan=True,- **kwargs,- )-- except ImportError:- # TODO: remove this branch if kornia relies on torch>=1.9- from torch.testing import assert_allclose as assert_close+def assert_close(+ actual: Tensor, expected: Tensor, *, rtol: Optional[float] = None, atol: Optional[float] = None, **kwargs: Any+) -> None:+ if rtol is None and atol is None:+ # `torch.testing.assert_close` used different default tolerances than `torch.testing.assert_allclose`.+ # TODO: remove this special handling as soon as https://github.com/kornia/kornia/issues/1134 is resolved+ # Basically, this whole wrapper function can be removed and `torch.testing.assert_close` can be used+ # directly.+ rtol, atol = _default_tolerances(actual, expected)++ return _assert_close(+ actual,+ expected,+ rtol=rtol,+ atol=atol,+ # this is the default value for torch>=1.10, but not for torch==1.9+ # TODO: remove this if kornia relies on torch>=1.10+ check_stride=False,+ equal_nan=True,+ **kwargs,+ )+# Logger apidiff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 1eaa3a4d0..f7bb73d6d 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -4,6 +4,7 @@ from inspect import isclass, isfunctionfrom typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union, overloadimport torch+from torch.linalg import inv_exfrom kornia.core import Tensorfrom kornia.utils._compat import torch_version_geq@@ -237,11 +238,6 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of validsolution."""- # Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622- if not torch_version_geq(1, 9):- inv = _torch_inverse_cast(A)- warnings.warn('PyTorch version < 1.9, inverse validness mask maybe not correct', RuntimeWarning)- return inv, torch.ones(len(A), dtype=torch.bool, device=A.device)if not isinstance(A, Tensor):raise AssertionError(f"A must be Tensor. Got: {type(A)}.")@@ -252,16 +248,6 @@ def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:else:dtype = dtype_original- if TYPE_CHECKING:- # TODO: remove this branch when kornia relies on torch >= 1.9- dummy: Tensor = torch.tensor(0)- return dummy, dummy- else:- if torch_version_geq(1, 9):- from torch.linalg import inv_ex # (not available in 1.8)-- inverse, info = inv_ex(A.to(dtype))- mask = info == 0- return inverse.to(dtype_original), mask- else:- NotImplementedError('This function just work with pytorch newer than 1.9.0')+ inverse, info = inv_ex(A.to(dtype))+ mask = info == 0+ return inverse.to(dtype_original), maskdiff --git a/setup.cfg b/setup.cfgindex c8ec67c69..58a9802a2 100644--- a/setup.cfg+++ b/setup.cfg@@ -37,7 +37,7 @@ project_urls =packages = find:install_requires =packaging- torch>=1.8.1+ torch>=1.9.1python_requires = >=3.7setup_requires =pytest-runner