Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Enabled Torch1.5.1 cpu support (#796)

shijianjianc33c1f089a68
diff --git a/.github/workflows/tests_cpu_versions.yml b/.github/workflows/tests_cpu_versions.yml
index 05b89c03a..8dc80f8de 100644
--- a/.github/workflows/tests_cpu_versions.yml
+++ b/.github/workflows/tests_cpu_versions.yml
@@ -1,10 +1,10 @@
-name: test-cpu-versions
+name: tests-cpu-versions
on:
- #push:
- # branches:
- # - master
- #pull_request:
+ push:
+ branches:
+ - master
+ # pull_request:
schedule:
- cron: "0 4 * * *"
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 03ca094cc..a9b52cae3 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -183,18 +183,26 @@ class ColorJitter(AugmentationBase2D):
) -> None:
super(ColorJitter, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
keepdim=keepdim)
- self.brightness: torch.Tensor = _range_bound(brightness, 'brightness', center=1., bounds=(0, 2))
- self.contrast: torch.Tensor = _range_bound(contrast, 'contrast', center=1.)
- self.saturation: torch.Tensor = _range_bound(saturation, 'saturation', center=1.)
- self.hue: torch.Tensor = _range_bound(hue, 'hue', bounds=(-0.5, 0.5))
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.hue = hue
def __repr__(self) -> str:
repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ brightness: torch.Tensor = _range_bound(
+ self.brightness, 'brightness', center=1., bounds=(0, 2), device=self.device, dtype=self.dtype)
+ contrast: torch.Tensor = _range_bound(
+ self.contrast, 'contrast', center=1., device=self.device, dtype=self.dtype)
+ saturation: torch.Tensor = _range_bound(
+ self.saturation, 'saturation', center=1., device=self.device, dtype=self.dtype)
+ hue: torch.Tensor = _range_bound(
+ self.hue, 'hue', bounds=(-0.5, 0.5), device=self.device, dtype=self.dtype)
return rg.random_color_jitter_generator(
- batch_shape[0], self.brightness, self.contrast, self.saturation, self.hue, self.same_on_batch,
+ batch_shape[0], brightness, contrast, saturation, hue, self.same_on_batch,
self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
@@ -490,8 +498,8 @@ class RandomAffine(AugmentationBase2D):
shear = shear if isinstance(shear, torch.Tensor) else torch.tensor(shear)
self.shear = torch.stack([
_range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
- torch.tensor([0, 0]) if shear.dim() == 0 or len(shear) == 2 else
- _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
+ torch.tensor([0, 0], device=shear.device, dtype=shear.dtype) if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
])
self.resample: Resample = Resample.get(resample)
self.padding_mode: SamplePadding = SamplePadding.get(padding_mode)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 34555c4b5..925b076dc 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -494,12 +494,12 @@ def random_crop_size_generator(
if not cond_bool.all():
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
- if (in_ratio < min(ratio)):
+ if (in_ratio < ratio.min()):
h_ct = torch.tensor(size[0], device=device, dtype=dtype)
- w_ct = torch.round(h_ct / min(ratio))
- elif (in_ratio > max(ratio)):
+ w_ct = torch.round(h_ct / ratio.min())
+ elif (in_ratio > ratio.min()):
w_ct = torch.tensor(size[1], device=device, dtype=dtype)
- h_ct = torch.round(w_ct * max(ratio))
+ h_ct = torch.round(w_ct * ratio.min())
else: # whole image
h_ct = torch.tensor(size[0], device=device, dtype=dtype)
w_ct = torch.tensor(size[1], device=device, dtype=dtype)
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 810b3a216..e05e63ce4 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Union, List, Callable, Optional
+from typing import Tuple, Union, List, Callable, Optional, cast
import torch
from torch.distributions import Uniform, Beta
@@ -141,10 +141,12 @@ def _transform_output_shape(output: Union[torch.Tensor, Tuple[torch.Tensor, torc
torch.Tensor
"""
is_tuple = isinstance(output, tuple)
+ out_tensor: torch.Tensor
+ trans_matrix: Optional[torch.Tensor]
if is_tuple:
- out_tensor, trans_matrix = output
+ out_tensor, trans_matrix = cast(Tuple[torch.Tensor, torch.Tensor], output)
else:
- out_tensor = output
+ out_tensor = cast(torch.Tensor, output)
trans_matrix = None
if trans_matrix is not None:
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 71c0c8e75..3092d1b3c 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -12,11 +12,12 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[float]], name: str,
center: float = 0., bounds: Tuple[float, float] = (0, float('inf')),
- check: Optional[str] = 'joint') -> torch.Tensor:
+ check: Optional[str] = 'joint', device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.get_default_dtype()) -> torch.Tensor:
r"""Check inputs and compute the corresponding factor bounds
"""
if not isinstance(factor, (torch.Tensor)):
- factor = torch.tensor(factor, dtype=torch.float32)
+ factor = torch.tensor(factor, device=device, dtype=dtype)
factor_bound: torch.Tensor
if factor.dim() == 0:
@@ -25,9 +26,10 @@ def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[fl
# Should be something other than clamp
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
- factor_bound = torch.tensor([center - factor, center + factor], dtype=torch.float32).clamp(bounds[0], bounds[1])
+ factor_bound = torch.tensor(
+ [center - factor, center + factor], device=device, dtype=dtype).clamp(bounds[0], bounds[1])
else:
- factor_bound = factor.to(dtype=torch.float32)
+ factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
if check is not None:
if check == 'joint':
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index c63d68ec1..a85ac768a 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -56,7 +56,10 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
image_hls: torch.Tensor = torch.stack([h, l, s], dim=-3)
- image_hls[torch.isnan(image_hls)] = 0.
+ # JIT indexing is not supported before 1.6.0 https://github.com/pytorch/pytorch/issues/38962
+ # image_hls[torch.isnan(image_hls)] = 0.
+ image_hls = torch.where(
+ torch.isnan(image_hls), torch.tensor(0., device=image_hls.device, dtype=image_hls.dtype), image_hls)
return image_hls
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index 511372003..beb106afb 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -27,16 +27,11 @@ def rgb_to_hsv(image: torch.Tensor) -> torch.Tensor:
raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
.format(image.shape))
- # TODO: enable again for later versions than 1.6.0 or find a different implementation.
- # It turns out that .max(...) does not return the index in the first position when
- # all the inputs have the same value in CUDA.
- # maxc, max_indices = image.max(-3)
- if image.is_cuda and torch.__version__ == '1.6.0':
- maxc, max_indices = image.cpu().max(-3)
- maxc, max_indices = maxc.to(image), max_indices.to(image.device)
- else:
- maxc, max_indices = image.max(-3)
-
+ # The first or last occurance is not guarenteed before 1.6.0
+ # https://github.com/pytorch/pytorch/issues/20414
+ maxc, _ = image.max(-3)
+ maxc_mask = image == maxc.unsqueeze(-3)
+ _, max_indices = ((maxc_mask.cumsum(-3) == 1) & maxc_mask).max(-3)
minc: torch.Tensor = image.min(-3)[0]
v: torch.Tensor = maxc # brightness
@@ -46,7 +41,7 @@ def rgb_to_hsv(image: torch.Tensor) -> torch.Tensor:
# avoid division by zero
deltac = torch.where(
- deltac == 0, torch.ones_like(deltac), deltac)
+ deltac == 0, torch.ones_like(deltac, device=deltac.device, dtype=deltac.dtype), deltac)
maxc_tmp = maxc.unsqueeze(-3) - image
rc: torch.Tensor = maxc_tmp[..., 0, :, :]
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 5bd220ab0..a7600254d 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -514,7 +514,7 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
# and then normalization by step.
lut = (torch.cumsum(histo, 0) + (step // 2)) // step
# Shift lut, prepending with 0.
- lut = torch.cat([torch.zeros(1, device=lut.device), lut[:-1]])
+ lut = torch.cat([torch.zeros(1, device=lut.device, dtype=lut.dtype), lut[:-1]])
# Clip the counts to be in range. This is done
# in the C code for image.point.
return torch.clamp(lut, 0, 255)
diff --git a/setup.py b/setup.py
index 1e980e231..b98306a4f 100644
--- a/setup.py
+++ b/setup.py
@@ -25,7 +25,7 @@ version = '0.4.2' # this a tag for the current development version
# Once a pytorch version (in the future) breaks a kornia version, we could just
# add a maximal version.
kornia_pt_dependencies = {
- '0.4.2': '>=1.6.0',
+ '0.4.2': '>=1.5.1',
'0.4.1': '>=1.6.0',
'0.4.0': '>=1.6.0,<1.7.0',
'0.3.2': '>=1.5.0,<1.6.0',
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index cbfba3ab5..47b629561 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -10,7 +10,7 @@ from torch.testing import assert_allclose
class TestAdjustSaturation:
- def test_saturation_one(self, device):
+ def test_saturation_one(self, device, dtype):
data = torch.tensor([[[.5, .5],
[.5, .5]],
@@ -18,15 +18,14 @@ class TestAdjustSaturation:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device) # 3x2x2
- data = data.to(device)
- expected = data.clone()
+ expected = data
f = kornia.enhance.AdjustSaturation(1.)
assert_allclose(f(data), expected)
- def test_saturation_one_batch(self):
+ def test_saturation_one_batch(self, device, dtype):
data = torch.tensor([[[[.5, .5],
[.5, .5]],
@@ -43,13 +42,13 @@ class TestAdjustSaturation:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]]) # 2x3x2x2
+ [.25, .25]]]], device=device) # 2x3x2x2
expected = data
f = kornia.enhance.AdjustSaturation(torch.ones(2))
assert_allclose(f(data), expected)
- def test_gradcheck(self):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 2, 3, 4, 5
img = torch.rand(batch_size, channels, height, width)
img = tensor_to_gradcheck_var(img) # to var