🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Update ruff configs (#2358)
João Gustavo A. Amorime98fd8c9e695
diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex 23b9e2182..d042a78ef 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -604,7 +604,6 @@ def main():cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)sig = f"{fn_name}({', '.join([str(a) for a in args])})"print(f"Generated image example for response function {fn_name}")- img_korniaif __name__ == "__main__":diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.pyindex 53efdf4bd..f0aad424e 100644--- a/kornia/augmentation/_2d/geometric/affine.py+++ b/kornia/augmentation/_2d/geometric/affine.py@@ -89,9 +89,11 @@ class RandomAffine(GeometricAugmentationBase2D):) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator: rg.AffineGenerator = rg.AffineGenerator(degrees, translate, scale, shear)- self.flags = dict(- resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners- )+ self.flags = {+ "resample": Resample.get(resample),+ "padding_mode": SamplePadding.get(padding_mode),+ "align_corners": align_corners,+ }def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:return get_affine_matrix2d(diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.pyindex 22f26b562..95c32cb09 100644--- a/kornia/augmentation/_2d/geometric/center_crop.py+++ b/kornia/augmentation/_2d/geometric/center_crop.py@@ -79,13 +79,13 @@ class CenterCrop(GeometricAugmentationBase2D):else:raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")- self.flags = dict(- resample=Resample.get(resample),- cropping_mode=cropping_mode,- align_corners=align_corners,- size=self.size,- padding_mode="zeros",- )+ self.flags = {+ "resample": Resample.get(resample),+ "cropping_mode": cropping_mode,+ "align_corners": align_corners,+ "size": self.size,+ "padding_mode": "zeros",+ }def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex 74c27d56d..7efa6a86b 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -89,16 +89,16 @@ class RandomCrop(GeometricAugmentationBase2D):# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)self._param_generator = rg.CropGenerator(size)- self.flags = dict(- size=size,- padding=padding,- pad_if_needed=pad_if_needed,- fill=fill,- padding_mode=padding_mode,- resample=Resample.get(resample),- align_corners=align_corners,- cropping_mode=cropping_mode,- )+ self.flags = {+ "size": size,+ "padding": padding,+ "pad_if_needed": pad_if_needed,+ "fill": fill,+ "padding_mode": padding_mode,+ "resample": Resample.get(resample),+ "align_corners": align_corners,+ "cropping_mode": cropping_mode,+ }def compute_padding(self, shape: Tuple[int, ...], flags: Optional[Dict[str, Any]] = None) -> List[int]:flags = self.flags if flags is None else flagsdiff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.pyindex f3ff07101..686a10566 100644--- a/kornia/augmentation/_2d/geometric/elastic_transform.py+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py@@ -59,14 +59,14 @@ class RandomElasticTransform(AugmentationBase2D):) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(- kernel_size=kernel_size,- sigma=sigma,- alpha=alpha,- align_corners=align_corners,- resample=Resample.get(resample),- padding_mode=padding_mode,- )+ self.flags = {+ "kernel_size": kernel_size,+ "sigma": sigma,+ "alpha": alpha,+ "align_corners": align_corners,+ "resample": Resample.get(resample),+ "padding_mode": padding_mode,+ }def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:B, _, H, W = shape@@ -74,7 +74,7 @@ class RandomElasticTransform(AugmentationBase2D):noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W)else:noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype)- return dict(noise=noise * 2 - 1)+ return {"noise": noise * 2 - 1}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.pyindex 2c90840ae..5c18f0db8 100644--- a/kornia/augmentation/_2d/geometric/pad.py+++ b/kornia/augmentation/_2d/geometric/pad.py@@ -49,7 +49,7 @@ class PadTo(GeometricAugmentationBase2D):self, size: Tuple[int, int], pad_mode: str = "constant", pad_value: Union[int, float] = 0, keepdim: bool = False) -> None:super().__init__(p=1.0, same_on_batch=True, p_batch=1.0, keepdim=keepdim)- self.flags = dict(size=size, pad_mode=pad_mode, pad_value=pad_value)+ self.flags = {"size": size, "pad_mode": pad_mode, "pad_value": pad_value}# TODO: It is incorrect to return identity# TODO: Having a resampled version with ``warp_affine``diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.pyindex a14984994..67050c1b7 100644--- a/kornia/augmentation/_2d/geometric/perspective.py+++ b/kornia/augmentation/_2d/geometric/perspective.py@@ -68,7 +68,7 @@ class RandomPerspective(GeometricAugmentationBase2D):super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator = rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)- self.flags: Dict[str, Any] = dict(align_corners=align_corners, resample=Resample.get(resample))+ self.flags: Dict[str, Any] = {"align_corners": align_corners, "resample": Resample.get(resample)}def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex 4271f3e2e..58d83f5f4 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -35,9 +35,13 @@ class Resize(GeometricAugmentationBase2D):) -> None:super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)self._param_generator = rg.ResizeGenerator(resize_to=size, side=side)- self.flags = dict(- size=size, side=side, resample=Resample.get(resample), align_corners=align_corners, antialias=antialias- )+ self.flags = {+ "size": size,+ "side": side,+ "resample": Resample.get(resample),+ "align_corners": align_corners,+ "antialias": antialias,+ }def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:if params["output_size"] == input.shape[-2:]:diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex 8dc381ded..34663b8b6 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -74,13 +74,13 @@ class RandomResizedCrop(GeometricAugmentationBase2D):# Since PyTorch does not support ragged tensor. So cropping function happens all the time.super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)self._param_generator = rg.ResizedCropGenerator(size, scale, ratio)- self.flags = dict(- size=size,- resample=Resample.get(resample),- align_corners=align_corners,- cropping_mode=cropping_mode,- padding_mode="zeros",- )+ self.flags = {+ "size": size,+ "resample": Resample.get(resample),+ "align_corners": align_corners,+ "cropping_mode": cropping_mode,+ "padding_mode": "zeros",+ }def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:if flags["cropping_mode"] in ("resample", "slice"):diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.pyindex fc01ca0bd..53be6fe1a 100644--- a/kornia/augmentation/_2d/geometric/rotation.py+++ b/kornia/augmentation/_2d/geometric/rotation.py@@ -71,7 +71,7 @@ class RandomRotation(GeometricAugmentationBase2D):super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator = rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0)))- self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)+ self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:# TODO: Update to use `get_rotation_matrix2d`diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.pyindex e9e0585ee..68876b57a 100644--- a/kornia/augmentation/_2d/geometric/shear.py+++ b/kornia/augmentation/_2d/geometric/shear.py@@ -69,9 +69,11 @@ class RandomShear(GeometricAugmentationBase2D):) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator: rg.ShearGenerator = rg.ShearGenerator(shear)- self.flags = dict(- resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners- )+ self.flags = {+ "resample": Resample.get(resample),+ "padding_mode": SamplePadding.get(padding_mode),+ "align_corners": align_corners,+ }def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:return get_shear_matrix2d(diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.pyindex 0aa2f1f1c..24f4f814a 100644--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py@@ -46,14 +46,14 @@ class RandomThinPlateSpline(AugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(align_corners=align_corners)+ self.flags = {"align_corners": align_corners}self.dist = torch.distributions.Uniform(-scale, scale)def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:B, _, _, _ = shapesrc = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2dst = src + self.dist.rsample(src.shape)- return dict(src=src, dst=dst)+ return {"src": src, "dst": dst}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.pyindex 9e730668d..2ce50fb85 100644--- a/kornia/augmentation/_2d/geometric/translate.py+++ b/kornia/augmentation/_2d/geometric/translate.py@@ -68,9 +68,11 @@ class RandomTranslate(GeometricAugmentationBase2D):) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator: rg.TranslateGenerator = rg.TranslateGenerator(translate_x, translate_y)- self.flags = dict(- resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners- )+ self.flags = {+ "resample": Resample.get(resample),+ "padding_mode": SamplePadding.get(padding_mode),+ "align_corners": align_corners,+ }def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:translations = stack([params["translate_x"], params["translate_y"]], dim=-1)diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.pyindex dddab9cd3..4d421c0cb 100644--- a/kornia/augmentation/_2d/intensity/box_blur.py+++ b/kornia/augmentation/_2d/intensity/box_blur.py@@ -46,7 +46,7 @@ class RandomBoxBlur(IntensityAugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(kernel_size=kernel_size, border_type=border_type, normalized=normalized)+ self.flags = {"kernel_size": kernel_size, "border_type": border_type, "normalized": normalized}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.pyindex 72ece0537..573ab9220 100644--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py@@ -40,7 +40,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:B, C, _, _ = shapechannels = torch.rand(B, C).argsort(dim=1)- return dict(channels=channels)+ return {"channels": channels}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.pyindex 323b83e8c..7b4189eae 100644--- a/kornia/augmentation/_2d/intensity/denormalize.py+++ b/kornia/augmentation/_2d/intensity/denormalize.py@@ -58,7 +58,7 @@ class Denormalize(IntensityAugmentationBase2D):if isinstance(std, (tuple, list)):std = torch.tensor(std)- self.flags = dict(mean=mean, std=std)+ self.flags = {"mean": mean, "std": std}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.pyindex 32449cded..96745da41 100644--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py@@ -72,7 +72,7 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):category=DeprecationWarning,)- self.flags = dict(kernel_size=kernel_size, separable=separable, border_type=BorderType.get(border_type))+ self.flags = {"kernel_size": kernel_size, "separable": separable, "border_type": BorderType.get(border_type)}self._param_generator = rg.RandomGaussianBlurGenerator(sigma)def apply_transform(diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.pyindex bed3e5ff7..99f9396a5 100644--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py@@ -45,7 +45,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):self, mean: float = 0.0, std: float = 1.0, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(mean=mean, std=std)+ self.flags = {"mean": mean, "std": std}def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:return {}diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.pyindex 229e5c43b..72f27e34b 100644--- a/kornia/augmentation/_2d/intensity/invert.py+++ b/kornia/augmentation/_2d/intensity/invert.py@@ -48,7 +48,7 @@ class RandomInvert(IntensityAugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(max_val=max_val)+ self.flags = {"max_val": max_val}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.pyindex 044d80ab1..5c93a33ad 100644--- a/kornia/augmentation/_2d/intensity/median_blur.py+++ b/kornia/augmentation/_2d/intensity/median_blur.py@@ -43,7 +43,7 @@ class RandomMedianBlur(IntensityAugmentationBase2D):self, kernel_size: Tuple[int, int] = (3, 3), same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(kernel_size=kernel_size)+ self.flags = {"kernel_size": kernel_size}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex 0a8176fc8..a6a68840a 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -78,7 +78,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)- self.flags = dict(border_type=BorderType.get(border_type), resample=Resample.get(resample))+ self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)}def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:params = super().generate_parameters(batch_shape)diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.pyindex 5ae1f8a41..e3b1908c8 100644--- a/kornia/augmentation/_2d/intensity/normalize.py+++ b/kornia/augmentation/_2d/intensity/normalize.py@@ -59,7 +59,7 @@ class Normalize(IntensityAugmentationBase2D):if isinstance(std, (tuple, list)):std = torch.tensor(std)- self.flags = dict(mean=mean, std=std)+ self.flags = {"mean": mean, "std": std}def apply_transform(self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Tensor | None = Nonediff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.pyindex 52f6d76be..d804cc931 100644--- a/kornia/augmentation/_2d/intensity/random_snow.py+++ b/kornia/augmentation/_2d/intensity/random_snow.py@@ -42,8 +42,8 @@ class RandomSnow(IntensityAugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)- KORNIA_CHECK(all([0 <= el <= 1 for el in snow_coefficient]), "Snow coefficient values must be between 0 and 1.")- KORNIA_CHECK(all([1 <= el for el in brightness]), "Brightness values must be greater than 1.")+ KORNIA_CHECK(all(0 <= el <= 1 for el in snow_coefficient), "Snow coefficient values must be between 0 and 1.")+ KORNIA_CHECK(all(1 <= el for el in brightness), "Brightness values must be greater than 1.")self._param_generator = rg.PlainUniformGenerator((snow_coefficient, "snow_coefficient", 0.5, (0.0, 1.0)), (brightness, "brightness", None, None)diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.pyindex 4f9046822..d43ad4c45 100644--- a/kornia/augmentation/_2d/mix/jigsaw.py+++ b/kornia/augmentation/_2d/mix/jigsaw.py@@ -49,7 +49,7 @@ class RandomJigsaw(MixAugmentationBaseV2):) -> None:super().__init__(p=p, p_batch=1.0, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)self._param_generator = rg.JigsawGenerator(grid, ensure_perm)- self.flags = dict(grid=grid)+ self.flags = {"grid": grid}def apply_transform(self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = Nonediff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex c4c060741..4f687f3af 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -77,15 +77,15 @@ class RandomMosaic(MixAugmentationBaseV2):self.start_ratio_range = start_ratio_rangeself._param_generator = rg.MosaicGenerator(output_size, mosaic_grid, start_ratio_range)- self.flags = dict(- mosaic_grid=mosaic_grid,- output_size=output_size,- min_bbox_size=min_bbox_size,- padding_mode=padding_mode,- resample=Resample.get(resample),- align_corners=align_corners,- cropping_mode=cropping_mode,- )+ self.flags = {+ "mosaic_grid": mosaic_grid,+ "output_size": output_size,+ "min_bbox_size": min_bbox_size,+ "padding_mode": padding_mode,+ "resample": Resample.get(resample),+ "align_corners": align_corners,+ "cropping_mode": cropping_mode,+ }def apply_transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:raise NotImplementedErrordiff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.pyindex 88e959825..fc9ff204e 100644--- a/kornia/augmentation/_3d/geometric/affine.py+++ b/kornia/augmentation/_3d/geometric/affine.py@@ -121,7 +121,7 @@ class RandomAffine3D(GeometricAugmentationBase3D):self.translate = translateself.scale = scale- self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)+ self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}self._param_generator = rg.AffineGenerator3D(degrees, translate, scale, shears)def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.pyindex e7d2308e2..337726a3f 100644--- a/kornia/augmentation/_3d/geometric/center_crop.py+++ b/kornia/augmentation/_3d/geometric/center_crop.py@@ -75,7 +75,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):self.size = (size, size, size)else:raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")- self.flags = dict(align_corners=align_corners, resample=Resample.get(resample))+ self.flags = {"align_corners": align_corners, "resample": Resample.get(resample)}def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:return rg.center_crop_generator3d(diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.pyindex 77558a01c..ac9400b13 100644--- a/kornia/augmentation/_3d/geometric/crop.py+++ b/kornia/augmentation/_3d/geometric/crop.py@@ -77,15 +77,15 @@ class RandomCrop3D(GeometricAugmentationBase3D):) -> None:# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)- self.flags = dict(- size=size,- padding=padding,- pad_if_needed=pad_if_needed,- padding_mode=padding_mode,- fill=fill,- resample=Resample.get(resample),- align_corners=align_corners,- )+ self.flags = {+ "size": size,+ "padding": padding,+ "pad_if_needed": pad_if_needed,+ "padding_mode": padding_mode,+ "fill": fill,+ "resample": Resample.get(resample),+ "align_corners": align_corners,+ }self._param_generator = rg.CropGenerator3D(size, None)def precrop_padding(self, input: Tensor, flags: Optional[Dict[str, Any]] = None) -> Tensor:diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.pyindex 975f791c5..5fbf965b9 100644--- a/kornia/augmentation/_3d/geometric/perspective.py+++ b/kornia/augmentation/_3d/geometric/perspective.py@@ -73,7 +73,7 @@ class RandomPerspective3D(GeometricAugmentationBase3D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)- self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)+ self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}self._param_generator = rg.PerspectiveGenerator3D(distortion_scale)def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.pyindex d4a868cda..9b8fe703a 100644--- a/kornia/augmentation/_3d/geometric/rotation.py+++ b/kornia/augmentation/_3d/geometric/rotation.py@@ -85,7 +85,7 @@ class RandomRotation3D(GeometricAugmentationBase3D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)- self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)+ self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}self._param_generator = rg.RotationGenerator3D(degrees)def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.pyindex db07de5ed..7bc7c227e 100644--- a/kornia/augmentation/_3d/intensity/motion_blur.py+++ b/kornia/augmentation/_3d/intensity/motion_blur.py@@ -91,7 +91,7 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(border_type=BorderType.get(border_type), resample=Resample.get(resample))+ self.flags = {"border_type": BorderType.get(border_type), "resample": Resample.get(resample)}self._param_generator = rg.MotionBlurGenerator3D(kernel_size, angle, direction)def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 212d70add..fa653c060 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -1,6 +1,5 @@# Lazy loading auto module-import kornia.augmentation.auto as auto-import kornia.augmentation.container as container+from kornia.augmentation import auto, containerfrom kornia.augmentation._2d import (CenterCrop,ColorJiggle,diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.pyindex f0d444d77..225b77ce4 100644--- a/kornia/augmentation/auto/operations/base.py+++ b/kornia/augmentation/auto/operations/base.py@@ -80,7 +80,7 @@ class OperationBase(Module):def _init_magnitude(self, initial_magnitude: Optional[List[Tuple[str, Optional[float]]]]) -> None:if isinstance(initial_magnitude, (list, tuple)):- if not all([isinstance(ini_mag, (list, tuple)) and len(ini_mag) == 2 for ini_mag in initial_magnitude]):+ if not all(isinstance(ini_mag, (list, tuple)) and len(ini_mag) == 2 for ini_mag in initial_magnitude):raise ValueError(f"`initial_magnitude` shall be a list of 2-element tuples. Got {initial_magnitude}")if len(initial_magnitude) != 1:raise NotImplementedError("Multi magnitudes operations are not yet supported.")@@ -106,11 +106,10 @@ class OperationBase(Module):self.op._p_batch_gen = RelaxedBernoulli(self.temperature, self.probability)else:self.op._p_gen = RelaxedBernoulli(self.temperature, self.probability)+ elif self._is_batch_operation:+ self.op._p_batch_gen = Bernoulli(self.probability)else:- if self._is_batch_operation:- self.op._p_batch_gen = Bernoulli(self.probability)- else:- self.op._p_gen = Bernoulli(self.probability)+ self.op._p_gen = Bernoulli(self.probability)def train(self: T, mode: bool = True) -> T:self._update_probability_gen(relaxation=mode)diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.pyindex 99b54868e..849fc2b15 100644--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py@@ -3,9 +3,9 @@ from typing import Iterator, List, Optional, Tupleimport torchfrom torch.distributions import Categorical-import kornia.augmentation.auto.rand_augment.ops as opsfrom kornia.augmentation.auto.base import SUBPLOLICY_CONFIG, PolicyAugmentBasefrom kornia.augmentation.auto.operations.policy import PolicySequential+from kornia.augmentation.auto.rand_augment import opsfrom kornia.augmentation.container.params import ParamItemfrom kornia.core import Modulediff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 3c8e34f5d..0c90949e7 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -76,7 +76,7 @@ class _BasicAugmentationBase(Module):def __repr__(self) -> str:txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"if isinstance(self._param_generator, RandomGeneratorBase):- txt = f"{str(self._param_generator)}, {txt}"+ txt = f"{self._param_generator!s}, {txt}"for k, v in self.flags.items():if isinstance(v, Enum):txt += f", {k}={v.name.lower()}"@@ -123,12 +123,11 @@ class _BasicAugmentationBase(Module):batch_prob = zeros(1) + 1elif p_batch == 0:batch_prob = zeros(1)- else:+ elif isinstance(self._p_batch_gen, (RelaxedBernoulli,)):# NOTE: there is no simple way to know if the sampler has `rsample` or not- if isinstance(self._p_batch_gen, (RelaxedBernoulli,)):- batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch)- else:- batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch)+ batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch)+ else:+ batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch)if batch_prob.sum() == 1:elem_prob: Tensor@@ -136,11 +135,10 @@ class _BasicAugmentationBase(Module):elem_prob = zeros(batch_shape[0]) + 1elif p == 0:elem_prob = zeros(batch_shape[0])+ elif isinstance(self._p_gen, (RelaxedBernoulli,)):+ elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch)else:- if isinstance(self._p_gen, (RelaxedBernoulli,)):- elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch)- else:- elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch)+ elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch)batch_prob = batch_prob * elem_probelse:batch_prob = batch_prob.repeat(batch_shape[0])diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 6dd8b18b1..a68448829 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -17,6 +17,10 @@ from .video import VideoSequential__all__ = ["AugmentationSequential"]+_BOXES_OPTIONS = {DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH}+_KEYPOINTS_OPTIONS = {DataKey.KEYPOINTS}+_IMG_MSK_OPTIONS = {DataKey.INPUT, DataKey.MASK}+class AugmentationSequential(ImageSequential):r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.@@ -143,13 +147,6 @@ class AugmentationSequential(ImageSequential):[torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])]"""- _transform_matrix: Optional[Tensor]- _transform_matrices: List[Tensor] = []-- _boxes_options = {DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH}- _keypoints_options = {DataKey.KEYPOINTS}- _img_msk_options = {DataKey.INPUT, DataKey.MASK}-def __init__(self,*args: Union[_AugmentationBase, ImageSequential],@@ -159,8 +156,13 @@ class AugmentationSequential(ImageSequential):random_apply: Union[int, bool, Tuple[int, int]] = False,random_apply_weights: Optional[List[float]] = None,transformation_matrix: str = "silence",- extra_args: Dict[DataKey, Dict[str, Any]] = {DataKey.MASK: dict(resample=Resample.NEAREST, align_corners=None)},+ extra_args: Dict[DataKey, Dict[str, Any]] = {+ DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}+ },) -> None:+ self._transform_matrix: Optional[Tensor]+ self._transform_matrices: List[Tensor] = []+super().__init__(*args,same_on_batch=same_on_batch,@@ -197,7 +199,7 @@ class AugmentationSequential(ImageSequential):# NOTE: only for images are supported for 3D.if isinstance(arg, K.AugmentationBase3D):self.contains_3d_augmentation = True- self._transform_matrix: Optional[Tensor] = None+ self._transform_matrix = Noneself.extra_args = extra_argsdef clear_state(self) -> None:@@ -294,11 +296,11 @@ class AugmentationSequential(ImageSequential):def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:inp: List[DataType] = []for arg, dcate in zip(args, data_keys):- if DataKey.get(dcate) in self._img_msk_options:+ if DataKey.get(dcate) in _IMG_MSK_OPTIONS:inp.append(arg)- elif DataKey.get(dcate) in self._keypoints_options:+ elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:inp.append(self._preproc_keypoints(arg, dcate))- elif DataKey.get(dcate) in self._boxes_options:+ elif DataKey.get(dcate) in _BOXES_OPTIONS:inp.append(self._preproc_boxes(arg, dcate))else:raise NotImplementedError(f"input type of {dcate} is not implemented.")@@ -309,12 +311,12 @@ class AugmentationSequential(ImageSequential):) -> List[DataType]:out: List[DataType] = []for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys):- if DataKey.get(dcate) in self._img_msk_options:+ if DataKey.get(dcate) in _IMG_MSK_OPTIONS:# It is tensor type already.out.append(out_arg)# TODO: may add the float to integer (for masks), etc.- elif DataKey.get(dcate) in self._keypoints_options:+ elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:_out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)if is_autocast_enabled() and isinstance(in_arg, (Tensor, Keypoints)):if isinstance(_out_k, list):@@ -323,7 +325,7 @@ class AugmentationSequential(ImageSequential):_out_k = _out_k.type(in_arg.dtype)out.append(_out_k)- elif DataKey.get(dcate) in self._boxes_options:+ elif DataKey.get(dcate) in _BOXES_OPTIONS:_out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)if is_autocast_enabled() and isinstance(in_arg, (Tensor, Boxes)):if isinstance(_out_b, list):diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex d96c8ca27..8cc81e0c5 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -3,7 +3,7 @@ from itertools import zip_longestfrom typing import Any, Dict, Iterator, List, Optional, Tupleimport torch-import torch.nn as nn+from torch import nnimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBase@@ -54,7 +54,7 @@ class BasicSequentialBase(nn.Sequential):path or resolves to something that is not an``Module``"""- if target == "":+ if len(target) == 0:return selfatoms: List[str] = target.split(".")diff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.pyindex 6b436b444..a0da5296b 100644--- a/kornia/augmentation/container/dispatcher.py+++ b/kornia/augmentation/container/dispatcher.py@@ -1,7 +1,6 @@from typing import List, Tuple, Union-import torch.nn as nn-from torch import Tensor+from torch import Tensor, nnfrom .augment import AugmentationSequentialdiff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.pyindex 42f307723..772230a9d 100644--- a/kornia/augmentation/random_generator/_2d/affine.py+++ b/kornia/augmentation/random_generator/_2d/affine.py@@ -178,4 +178,11 @@ class AffineGenerator(RandomGeneratorBase):sx = tensor([0] * batch_size, device=_device, dtype=_dtype)sy = tensor([0] * batch_size, device=_device, dtype=_dtype)- return dict(translations=translations, center=center, scale=_scale, angle=angle, shear_x=sx, shear_y=sy)+ return {+ "translations": translations,+ "center": center,+ "scale": _scale,+ "angle": angle,+ "shear_x": sx,+ "shear_y": sy,+ }diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.pyindex 2004dde4c..9e1228fed 100644--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py@@ -81,10 +81,10 @@ class ColorJiggleGenerator(RandomGeneratorBase):contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)- return dict(- brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),- hue_factor=hue_factor.to(device=_device, dtype=_dtype),- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),- order=self.randperm(4).to(device=_device, dtype=_dtype).long(),- )+ return {+ "brightness_factor": brightness_factor.to(device=_device, dtype=_dtype),+ "contrast_factor": contrast_factor.to(device=_device, dtype=_dtype),+ "hue_factor": hue_factor.to(device=_device, dtype=_dtype),+ "saturation_factor": saturation_factor.to(device=_device, dtype=_dtype),+ "order": self.randperm(4).to(device=_device, dtype=_dtype).long(),+ }diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.pyindex 31f92a020..b2f61d322 100644--- a/kornia/augmentation/random_generator/_2d/color_jitter.py+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py@@ -85,10 +85,10 @@ class ColorJitterGenerator(RandomGeneratorBase):contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)- return dict(- brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),- hue_factor=hue_factor.to(device=_device, dtype=_dtype),- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),- order=self.randperm(4).to(device=_device, dtype=_dtype).long(),- )+ return {+ "brightness_factor": brightness_factor.to(device=_device, dtype=_dtype),+ "contrast_factor": contrast_factor.to(device=_device, dtype=_dtype),+ "hue_factor": hue_factor.to(device=_device, dtype=_dtype),+ "saturation_factor": saturation_factor.to(device=_device, dtype=_dtype),+ "order": self.randperm(4).to(device=_device, dtype=_dtype).long(),+ }diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.pyindex 944826964..ba4a24cbc 100644--- a/kornia/augmentation/random_generator/_2d/crop.py+++ b/kornia/augmentation/random_generator/_2d/crop.py@@ -51,9 +51,10 @@ class CropGenerator(RandomGeneratorBase):_device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])if batch_size == 0:- return dict(- src=zeros([0, 4, 2], device=_device, dtype=_dtype), dst=zeros([0, 4, 2], device=_device, dtype=_dtype)- )+ return {+ "src": zeros([0, 4, 2], device=_device, dtype=_dtype),+ "dst": zeros([0, 4, 2], device=_device, dtype=_dtype),+ }input_size = (batch_shape[-2], batch_shape[-1])if not isinstance(self.size, Tensor):@@ -127,7 +128,7 @@ class CropGenerator(RandomGeneratorBase):_input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)- return dict(src=crop_src, dst=crop_dst, input_size=_input_size, output_size=_output_size)+ return {"src": crop_src, "dst": crop_dst, "input_size": _input_size, "output_size": _output_size}class ResizedCropGenerator(CropGenerator):@@ -202,11 +203,11 @@ class ResizedCropGenerator(CropGenerator):_device, _dtype = _extract_device_dtype([self.scale, self.ratio])if batch_size == 0:- return dict(- src=zeros([0, 4, 2], device=_device, dtype=_dtype),- dst=zeros([0, 4, 2], device=_device, dtype=_dtype),- size=zeros([0, 2], device=_device, dtype=_dtype),- )+ return {+ "src": zeros([0, 4, 2], device=_device, dtype=_dtype),+ "dst": zeros([0, 4, 2], device=_device, dtype=_dtype),+ "size": zeros([0, 2], device=_device, dtype=_dtype),+ }rand = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)area = (rand * (self.scale[1] - self.scale[0]) + self.scale[0]) * size[0] * size[1]@@ -309,4 +310,4 @@ def center_crop_generator(_input_size = tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)_output_size = tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)- return dict(src=points_src, dst=points_dst, input_size=_input_size, output_size=_output_size)+ return {"src": points_src, "dst": points_dst, "input_size": _input_size, "output_size": _output_size}diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex 8e7470460..fa3f2ea17 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -86,10 +86,10 @@ class CutmixGenerator(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)if batch_size == 0:- return dict(- mix_pairs=zeros([0, 3], device=_device, dtype=torch.long),- crop_src=zeros([0, 4, 2], device=_device, dtype=_dtype),- )+ return {+ "mix_pairs": zeros([0, 3], device=_device, dtype=torch.long),+ "crop_src": zeros([0, 4, 2], device=_device, dtype=_dtype),+ }with torch.no_grad():batch_probs: torch.Tensor = _adapted_sampling(@@ -132,8 +132,8 @@ class CutmixGenerator(RandomGeneratorBase):# (B * num_mix, 4, 2) => (num_mix, batch_size, 4, 2)crop_src = crop_src.view(self.num_mix, batch_size, 4, 2)- return dict(- mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),- crop_src=crop_src.floor().to(device=_device, dtype=_dtype),- image_shape=as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),- )+ return {+ "mix_pairs": mix_pairs.to(device=_device, dtype=torch.long),+ "crop_src": crop_src.floor().to(device=_device, dtype=_dtype),+ "image_shape": as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.pyindex 7d61773f1..ff841c468 100644--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py@@ -53,4 +53,4 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([self.sigma])sigma = _adapted_rsampling((batch_size,), self.sigma_sampler, same_on_batch)- return dict(sigma=sigma.to(device=_device, dtype=_dtype))+ return {"sigma": sigma.to(device=_device, dtype=_dtype)}diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.pyindex 7080ce18f..9858cfb3e 100644--- a/kornia/augmentation/random_generator/_2d/jigsaw.py+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py@@ -54,4 +54,4 @@ class JigsawGenerator(RandomGeneratorBase):rand_ids = torch.stack([randperm(perm_times, ensure_perm=self.ensure_perm, device=self._device) for _ in range(batch_size)])- return dict(permutation=rand_ids)+ return {"permutation": rand_ids}diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.pyindex 75edb2844..67c294b13 100644--- a/kornia/augmentation/random_generator/_2d/mixup.py+++ b/kornia/augmentation/random_generator/_2d/mixup.py@@ -59,7 +59,7 @@ class MixupGenerator(RandomGeneratorBase):mixup_lambdas: torch.Tensor = _adapted_rsampling((batch_size,), self.lambda_sampler, same_on_batch)mixup_lambdas = mixup_lambdas * batch_probs- return dict(- mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),- mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype),- )+ return {+ "mixup_pairs": mixup_pairs.to(device=_device, dtype=torch.long),+ "mixup_lambdas": mixup_lambdas.to(device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.pyindex 988db79d6..ee36e82ec 100644--- a/kornia/augmentation/random_generator/_2d/mosaic.py+++ b/kornia/augmentation/random_generator/_2d/mosaic.py@@ -100,9 +100,9 @@ class MosaicGenerator(RandomGeneratorBase):batch_shapes = torch.zeros([0, 3], device=_device, dtype=torch.long)else:batch_shapes = torch.stack([torch.as_tensor(batch_shape[1:], device=_device) for _ in range(batch_size)])- return dict(- permutation=mosiac_ids.to(device=_device, dtype=torch.long),- src=crop_src,- dst=crop_dst,- batch_shapes=batch_shapes,- )+ return {+ "permutation": mosiac_ids.to(device=_device, dtype=torch.long),+ "src": crop_src,+ "dst": crop_dst,+ "batch_shapes": batch_shapes,+ }diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.pyindex 06a02aaea..b8e4aa4c2 100644--- a/kornia/augmentation/random_generator/_2d/motion_blur.py+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py@@ -81,8 +81,8 @@ class MotionBlurGenerator(RandomGeneratorBase):direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1- return dict(- ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),- angle_factor=angle_factor.to(device=_device, dtype=_dtype),- direction_factor=direction_factor.to(device=_device, dtype=_dtype),- )+ return {+ "ksize_factor": ksize_factor.to(device=_device, dtype=torch.int32),+ "angle_factor": angle_factor.to(device=_device, dtype=_dtype),+ "direction_factor": direction_factor.to(device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex e7ae0aba8..de7066b2b 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -83,4 +83,4 @@ class PerspectiveGenerator(RandomGeneratorBase):end_points = start_points + offset- return dict(start_points=start_points, end_points=end_points)+ return {"start_points": start_points, "end_points": end_points}diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.pyindex 0da9d065f..823084b4d 100644--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py@@ -27,4 +27,4 @@ class PlanckianJitterGenerator(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)pl_idx = _adapted_rsampling((batch_size,), self.pl_idx_dist, same_on_batch)- return dict(idx=pl_idx.long())+ return {"idx": pl_idx.long()}diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.pyindex 1434629ae..88012c5c8 100644--- a/kornia/augmentation/random_generator/_2d/posterize.py+++ b/kornia/augmentation/random_generator/_2d/posterize.py@@ -52,4 +52,4 @@ class PosterizeGenerator(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)_device, _ = _extract_device_dtype([self.bits_factor if isinstance(self.bits_factor, Tensor) else None])bits_factor = _adapted_rsampling((batch_size,), self.bit_sampler, same_on_batch)- return dict(bits_factor=bits_factor.round().to(device=_device, dtype=torch.int32))+ return {"bits_factor": bits_factor.round().to(device=_device, dtype=torch.int32)}diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.pyindex efddb5569..e342049e6 100644--- a/kornia/augmentation/random_generator/_2d/probability.py+++ b/kornia/augmentation/random_generator/_2d/probability.py@@ -41,7 +41,7 @@ class ProbabilityGenerator(RandomGeneratorBase):def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:batch_size = batch_shape[0]probs_mask: Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()- return dict(probs=probs_mask)+ return {"probs": probs_mask}def random_prob_generator(diff --git a/kornia/augmentation/random_generator/_2d/random_rain.py b/kornia/augmentation/random_generator/_2d/random_rain.pyindex dedf08711..df170252b 100644--- a/kornia/augmentation/random_generator/_2d/random_rain.py+++ b/kornia/augmentation/random_generator/_2d/random_rain.py@@ -69,9 +69,9 @@ class RainGenerator(RandomGeneratorBase):self.coordinates_sampler,same_on_batch=same_on_batch,).to(device=_device)- return dict(- number_of_drops_factor=number_of_drops_factor,- coordinates_factor=coordinates_factor,- drop_height_factor=drop_height_factor,- drop_width_factor=drop_width_factor,- )+ return {+ 'number_of_drops_factor': number_of_drops_factor,+ 'coordinates_factor': coordinates_factor,+ 'drop_height_factor': drop_height_factor,+ 'drop_width_factor': drop_width_factor,+ }diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.pyindex 31bb198ed..5cd4b0eca 100644--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py@@ -126,10 +126,10 @@ class RectangleEraseGenerator(RandomGeneratorBase):xs = xs_ratio * (width - widths + 1)ys = ys_ratio * (height - heights + 1)- return dict(- widths=widths.floor(),- heights=heights.floor(),- xs=xs.floor(),- ys=ys.floor(),- values=tensor([self.value] * batch_size, device=_device, dtype=_dtype),- )+ return {+ "widths": widths.floor(),+ "heights": heights.floor(),+ "xs": xs.floor(),+ "ys": ys.floor(),+ "values": tensor([self.value] * batch_size, device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.pyindex 157ef5ef2..89615ee23 100644--- a/kornia/augmentation/random_generator/_2d/resize.py+++ b/kornia/augmentation/random_generator/_2d/resize.py@@ -52,10 +52,10 @@ class ResizeGenerator(RandomGeneratorBase):_dtype = self.dtypeif batch_size == 0:- return dict(- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),- )+ return {+ "src": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),+ "dst": torch.zeros([0, 4, 2], device=_device, dtype=_dtype),+ }input_size = h, w = (batch_shape[-2], batch_shape[-1])@@ -91,4 +91,4 @@ class ResizeGenerator(RandomGeneratorBase):_input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)_output_size = tensor(output_size, device=_device, dtype=torch.long).expand(batch_size, -1)- return dict(src=src, dst=dst, input_size=_input_size, output_size=_output_size)+ return {"src": src, "dst": dst, "input_size": _input_size, "output_size": _output_size}diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.pyindex ccc2a6659..5f9fa8804 100644--- a/kornia/augmentation/random_generator/_2d/shear.py+++ b/kornia/augmentation/random_generator/_2d/shear.py@@ -85,4 +85,4 @@ class ShearGenerator(RandomGeneratorBase):sx = sx.to(device=_device, dtype=_dtype)sy = sy.to(device=_device, dtype=_dtype)- return dict(center=center, shear_x=sx, shear_y=sy)+ return {"center": center, "shear_x": sx, "shear_y": sy}diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.pyindex 68986cc91..3dd7867e5 100644--- a/kornia/augmentation/random_generator/_2d/translate.py+++ b/kornia/augmentation/random_generator/_2d/translate.py@@ -91,4 +91,4 @@ class TranslateGenerator(RandomGeneratorBase):else:translate_y = torch.zeros((batch_size,), device=_device, dtype=_dtype)- return dict(translate_x=translate_x, translate_y=translate_y)+ return {"translate_x": translate_x, "translate_y": translate_y}diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.pyindex 2903d69e2..c5ad03e29 100644--- a/kornia/augmentation/random_generator/_3d/affine.py+++ b/kornia/augmentation/random_generator/_3d/affine.py@@ -205,15 +205,15 @@ class AffineGenerator3D(RandomGeneratorBase):else:sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)- return dict(- translations=torch.as_tensor(translations, device=_device, dtype=_dtype),- center=torch.as_tensor(center, device=_device, dtype=_dtype),- scale=torch.as_tensor(scale, device=_device, dtype=_dtype),- angles=torch.as_tensor(angles, device=_device, dtype=_dtype),- sxy=torch.as_tensor(sxy, device=_device, dtype=_dtype),- sxz=torch.as_tensor(sxz, device=_device, dtype=_dtype),- syx=torch.as_tensor(syx, device=_device, dtype=_dtype),- syz=torch.as_tensor(syz, device=_device, dtype=_dtype),- szx=torch.as_tensor(szx, device=_device, dtype=_dtype),- szy=torch.as_tensor(szy, device=_device, dtype=_dtype),- )+ return {+ 'translations': torch.as_tensor(translations, device=_device, dtype=_dtype),+ 'center': torch.as_tensor(center, device=_device, dtype=_dtype),+ 'scale': torch.as_tensor(scale, device=_device, dtype=_dtype),+ 'angles': torch.as_tensor(angles, device=_device, dtype=_dtype),+ 'sxy': torch.as_tensor(sxy, device=_device, dtype=_dtype),+ 'sxz': torch.as_tensor(sxz, device=_device, dtype=_dtype),+ 'syx': torch.as_tensor(syx, device=_device, dtype=_dtype),+ 'syz': torch.as_tensor(syz, device=_device, dtype=_dtype),+ 'szx': torch.as_tensor(szx, device=_device, dtype=_dtype),+ 'szy': torch.as_tensor(szy, device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.pyindex 9a2449156..cf3bbd184 100644--- a/kornia/augmentation/random_generator/_3d/crop.py+++ b/kornia/augmentation/random_generator/_3d/crop.py@@ -75,13 +75,14 @@ class CropGenerator3D(RandomGeneratorBase):if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():raise ValueError(- f"input_size {(depth, height, width)} cannot be smaller than crop size {str(size)} in any dimension."+ f"input_size {(depth, height, width)} cannot be smaller than crop size {size!s} in any dimension.")if batch_size == 0:- return dict(- src=zeros([0, 8, 3], device=_device, dtype=_dtype), dst=zeros([0, 8, 3], device=_device, dtype=_dtype)- )+ return {+ "src": zeros([0, 8, 3], device=_device, dtype=_dtype),+ "dst": zeros([0, 8, 3], device=_device, dtype=_dtype),+ }x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)y_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)@@ -132,7 +133,7 @@ class CropGenerator3D(RandomGeneratorBase):dtype=_dtype,).repeat(batch_size, 1, 1)- return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))+ return {"src": crop_src.to(device=_device), "dst": crop_dst.to(device=_device)}def center_crop_generator3d(@@ -171,7 +172,7 @@ def center_crop_generator3d(raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")if batch_size == 0:- return dict(src=zeros([0, 8, 3]), dst=zeros([0, 8, 3]))+ return {"src": zeros([0, 8, 3]), "dst": zeros([0, 8, 3])}# unpack input sizesdst_d, dst_h, dst_w = sizesrc_d, src_h, src_w = (depth, height, width)@@ -232,4 +233,4 @@ def center_crop_generator3d(device=device,dtype=torch.long,).expand(batch_size, -1, -1)- return dict(src=points_src, dst=points_dst)+ return {"src": points_src, "dst": points_dst}diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.pyindex 86b7def36..c5e0e17ea 100644--- a/kornia/augmentation/random_generator/_3d/motion_blur.py+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py@@ -90,8 +90,8 @@ class MotionBlurGenerator3D(RandomGeneratorBase):direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1- return dict(- ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),- angle_factor=angle_factor.to(device=_device, dtype=_dtype),- direction_factor=direction_factor.to(device=_device, dtype=_dtype),- )+ return {+ 'ksize_factor': ksize_factor.to(device=_device, dtype=torch.int32),+ 'angle_factor': angle_factor.to(device=_device, dtype=_dtype),+ 'direction_factor': direction_factor.to(device=_device, dtype=_dtype),+ }diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.pyindex 6bfef2c93..02f014923 100644--- a/kornia/augmentation/random_generator/_3d/perspective.py+++ b/kornia/augmentation/random_generator/_3d/perspective.py@@ -86,4 +86,4 @@ class PerspectiveGenerator3D(RandomGeneratorBase):)end_points = start_points + factor * rand_val * pts_norm- return dict(start_points=start_points, end_points=end_points)+ return {"start_points": start_points, "end_points": end_points}diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.pyindex c50254dad..5f043686d 100644--- a/kornia/augmentation/random_generator/_3d/rotation.py+++ b/kornia/augmentation/random_generator/_3d/rotation.py@@ -61,8 +61,12 @@ class RotationGenerator3D(RandomGeneratorBase):_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([self.degrees])- return dict(- yaw=_adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch).to(device=_device, dtype=_dtype),- pitch=_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch).to(device=_device, dtype=_dtype),- roll=_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch).to(device=_device, dtype=_dtype),- )+ return {+ "yaw": _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch).to(device=_device, dtype=_dtype),+ "pitch": _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ ),+ "roll": _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ ),+ }diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex baae71b9e..e17bf6467 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -314,13 +314,12 @@ def override_parameters(for k, v in params_override.items():if k in params_override:out[k] = v+ elif if_none_exist == 'ignore':+ pass+ elif if_none_exist == 'raise':+ raise RuntimeError(f"Param `{k}` not existed in `{params_override}`.")else:- if if_none_exist == 'ignore':- pass- elif if_none_exist == 'raise':- raise RuntimeError(f"Param `{k}` not existed in `{params_override}`.")- else:- raise ValueError(f"`{if_none_exist}` is not a valid option.")+ raise ValueError(f"`{if_none_exist}` is not a valid option.")return outdiff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex 2ac94ef7e..73b2fb467 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -140,7 +140,7 @@ def _tuple_range_reader(f"Got {input_range}")else:- if isinstance(input_range, (float, int)):+ if isinstance(input_range, (float, int)): # noqa: PLR5501if input_range < 0:raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")input_range_tmp = tensor([-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1)diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex d6c9f51f2..9b08432a4 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -13,7 +13,7 @@ RGBColor = List[float]def _list_color_to_tensor(colors: List[RGBColor], dtype: Optional[torch.dtype], device: Optional[torch.device]) -> Tensor:- return tensor([color for color in colors], dtype=dtype, device=device).T+ return tensor(list(colors), dtype=dtype, device=device).Tclass ColorMap(ABC):diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 70889b582..67266849e 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -107,20 +107,20 @@ def hls_to_rgb(image: Tensor) -> Tensor:_HLS2RGB = tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1im: Tensor = image.unsqueeze(-4)- h: Tensor = im[..., 0, :, :]- l: Tensor = im[..., 1, :, :]- s: Tensor = im[..., 2, :, :]- h = h * (6 / math.pi) # h * 360 / (2 * math.pi) / 30- a = s * torch.min(l, 1.0 - l)+ h_ch: Tensor = im[..., 0, :, :]+ l_ch: Tensor = im[..., 1, :, :]+ s_ch: Tensor = im[..., 2, :, :]+ h_ch = h_ch * (6 / math.pi) # h * 360 / (2 * math.pi) / 30+ a = s_ch * torch.min(l_ch, 1.0 - l_ch)# kr = (0 + h) % 12# kg = (8 + h) % 12# kb = (4 + h) % 12- k: Tensor = (h + _HLS2RGB) % 12+ k: Tensor = (h_ch + _HLS2RGB) % 12# l - a * max(min(min(k - 3.0, 9.0 - k), 1), -1)mink = torch.min(k - 3.0, 9.0 - k)- return torch.addcmul(l, a, mink.clamp_(min=-1.0, max=1.0), value=-1)+ return torch.addcmul(l_ch, a, mink.clamp_(min=-1.0, max=1.0), value=-1)class RgbToHls(Module):diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex 95d618e8c..6ce62083d 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -1,7 +1,7 @@import mathimport torch-import torch.nn as nn+from torch import nndef rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:diff --git a/kornia/color/lab.py b/kornia/color/lab.pyindex d944d898c..69c6bf86c 100644--- a/kornia/color/lab.py+++ b/kornia/color/lab.py@@ -5,7 +5,7 @@ https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16import torch-import torch.nn as nn+from torch import nnfrom .rgb import linear_rgb_to_rgb, rgb_to_linear_rgbfrom .xyz import rgb_to_xyz, xyz_to_rgbdiff --git a/kornia/color/luv.py b/kornia/color/luv.pyindex 4acafabfe..58309ae3d 100644--- a/kornia/color/luv.py+++ b/kornia/color/luv.py@@ -7,7 +7,7 @@ https://github.com/scikit-image/scikit-image/blob/a48bf6774718c64dade4548153ae16from typing import Tupleimport torch-import torch.nn as nn+from torch import nnfrom .rgb import linear_rgb_to_rgb, rgb_to_linear_rgbfrom .xyz import rgb_to_xyz, xyz_to_rgbdiff --git a/kornia/color/raw.py b/kornia/color/raw.pyindex ae610b307..f62d63c2a 100644--- a/kornia/color/raw.py+++ b/kornia/color/raw.py@@ -1,7 +1,7 @@from enum import Enumimport torch-import torch.nn as nn+from torch import nnclass CFA(Enum):diff --git a/kornia/color/rgb.py b/kornia/color/rgb.pyindex e8b4d377f..606316ad0 100644--- a/kornia/color/rgb.py+++ b/kornia/color/rgb.py@@ -1,7 +1,7 @@from typing import Union, castimport torch-import torch.nn as nn+from torch import nndef rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:diff --git a/kornia/color/xyz.py b/kornia/color/xyz.pyindex f54ad6c90..5d66465f1 100644--- a/kornia/color/xyz.py+++ b/kornia/color/xyz.py@@ -1,5 +1,5 @@import torch-import torch.nn as nn+from torch import nndef rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.pyindex 61f4ee063..4e9fe5d85 100644--- a/kornia/color/ycbcr.py+++ b/kornia/color/ycbcr.py@@ -1,6 +1,5 @@import torch-import torch.nn as nn-from torch import Tensor+from torch import Tensor, nndef _rgb_to_y(r: Tensor, g: Tensor, b: Tensor) -> Tensor:diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 6172cce5b..7f9dddd8b 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -1,7 +1,7 @@from typing import Tupleimport torch-import torch.nn as nn+from torch import nndef rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.pyindex 7fdbe87ed..5ff641c4b 100644--- a/kornia/contrib/distance_transform.py+++ b/kornia/contrib/distance_transform.py@@ -1,7 +1,7 @@import mathimport torch-import torch.nn as nn+from torch import nnfrom kornia.filters import filter2dfrom kornia.utils import create_meshgriddiff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.pyindex bae3708dc..b7054cfa9 100644--- a/kornia/contrib/face_detection.py+++ b/kornia/contrib/face_detection.py@@ -4,8 +4,8 @@ from enum import Enumfrom typing import Dict, List, Optional, Tupleimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.geometry.bbox import nms as nms_korniafrom kornia.utils.helpers import map_location_to_cpudiff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.pyindex 6aef55a52..ab9a5ac31 100644--- a/kornia/contrib/image_stitching.py+++ b/kornia/contrib/image_stitching.py@@ -39,7 +39,7 @@ class ImageStitcher(Module):self.estimator = estimatorself.blending_method = blending_methodif estimator not in ['ransac', 'vanilla']:- raise NotImplementedError(f"Unsupported estimator {estimator}. Use ‘ransac’ or ‘vanilla’ instead.")+ raise NotImplementedError(f"Unsupported estimator {estimator}. Use `ransac` or `vanilla` instead.")if estimator == "ransac":self.ransac = RANSAC('homography')@@ -58,7 +58,7 @@ class ImageStitcher(Module):homo, _ = self.ransac(keypoints2, keypoints1)homo = homo[None]else:- raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use ‘ransac’ or ‘vanilla’ instead.")+ raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use `ransac` or `vanilla` instead.")return homodef estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor:@@ -77,7 +77,7 @@ class ImageStitcher(Module):if self.blending_method == "naive":out = where(mask == 1, src_img, dst_img)else:- raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use ‘naive’.")+ raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use `naive`.")return outdef preprocess(self, image_1: Tensor, image_2: Tensor) -> Dict[str, Tensor]:diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.pyindex 1cb34ee1e..625fdb61e 100644--- a/kornia/contrib/lambda_module.py+++ b/kornia/contrib/lambda_module.py@@ -23,7 +23,7 @@ class Lambda(Module):def __init__(self, func: Callable[..., Tensor]) -> None:super().__init__()if not callable(func):- raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")+ raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}")self.func = funcdiff --git a/kornia/contrib/models/common.py b/kornia/contrib/models/common.pyindex d5f201385..40ab7e58d 100644--- a/kornia/contrib/models/common.py+++ b/kornia/contrib/models/common.py@@ -24,7 +24,7 @@ class ConvNormAct(nn.Sequential):padding = (kernel_size - 1) // 2self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, 1, groups, False)self.norm = nn.BatchNorm2d(out_channels)- self.act = dict(relu=nn.ReLU, silu=nn.SiLU, none=nn.Identity)[act](inplace=True)+ self.act = {"relu": nn.ReLU, "silu": nn.SiLU, "none": nn.Identity}[act](inplace=True)# Lightly adapted from@@ -36,7 +36,7 @@ class MLP(Module):super().__init__()self.num_layers = num_layersh = [hidden_dim] * (num_layers - 1)- self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim, *h], [*h, output_dim]))self.sigmoid_output = sigmoid_outputdef forward(self, x: Tensor) -> Tensor:diff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.pyindex ff69a5293..d9d382f78 100644--- a/kornia/contrib/models/rt_detr/model.py+++ b/kornia/contrib/models/rt_detr/model.py@@ -171,4 +171,4 @@ class RTDETR(ModelBase[RTDETRConfig]):fmaps = self.backbone(images)fmaps = self.neck(fmaps)logits, boxes = self.head(fmaps)- return dict(logits=logits, boxes=boxes)+ return {"logits": logits, "boxes": boxes}diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.pyindex 14b300143..a8c8e8d77 100644--- a/kornia/contrib/models/sam/architecture/image_encoder.py+++ b/kornia/contrib/models/sam/architecture/image_encoder.py@@ -18,6 +18,7 @@ class ImageEncoderViT(Module):def __init__(self,img_size: int = 1024,+ *,patch_size: int = 16,in_chans: int = 3,embed_dim: int = 768,diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex e15eabcd3..ac725ef53 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -29,7 +29,7 @@ class ResizePreProcessor(Module):# NOTE: antialias=False is used in F.interpolate()original_sizes = [(img.shape[1], img.shape[2]) for img in imgs]resized_imgs = [F.interpolate(img.unsqueeze(0), self.size, mode=self.interpolation_mode) for img in imgs]- return concatenate(resized_imgs), dict(original_size=original_sizes)+ return concatenate(resized_imgs), {"original_size": original_sizes}class ObjectDetector:diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.pyindex 7b813661f..1e990526a 100644--- a/kornia/contrib/vit_mobile.py+++ b/kornia/contrib/vit_mobile.py@@ -53,7 +53,7 @@ class Attention(Module):qkv = self.to_qkv(x).chunk(3, dim=-1)b, p, n, hd = qkv[0].shape- q, k, v = map(lambda t: t.reshape(b, p, n, self.heads, hd // self.heads).transpose(2, 3), qkv)+ q, k, v = (t.reshape(b, p, n, self.heads, hd // self.heads).transpose(2, 3) for t in qkv)dots = torch.matmul(q, k.transpose(-1, -2)) * self.scaleattn = self.attend(dots)diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex b6b9582d0..95b8b0ed7 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -224,7 +224,7 @@ def adjust_gamma(input: Tensor, gamma: Union[float, Tensor], gain: Union[float,Args:input: Image to be adjusted in the shape of :math:`(*, H, W)`.- gamma: Non negative real number, same as γ\gammaγ in the equation.+ gamma: Non negative real number, same as y\gammay in the equation.gamma larger than 1 make the shadows darker, while gamma smaller than 1 makedark regions lighter.gain: The constant multiplier.@@ -1149,7 +1149,7 @@ class AdjustGamma(Module):The input image is expected to be in the range of [0, 1].Args:- gamma: Non negative real number, same as γ\gammaγ in the equation.+ gamma: Non negative real number, same as y\gammay in the equation.gamma larger than 1 make the shadows darker, while gamma smaller than 1 makedark regions lighter.gain: The constant multiplier.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 7a837a16f..1a5e95e46 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -297,10 +297,10 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->tiles_equalized[:, 1:-1, gh - 1] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))# border region (w)- l, r, _, _ = preinterp_tiles_equalized[:, 0, 1:-1].unbind(2)- tiles_equalized[:, 0, 1:-1] = torch.addcmul(r, tiw, torch.sub(l, r))- l, r, _, _ = preinterp_tiles_equalized[:, gw - 1, 1:-1].unbind(2)- tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(r, tiw, torch.sub(l, r))+ left, right, _, _ = preinterp_tiles_equalized[:, 0, 1:-1].unbind(2)+ tiles_equalized[:, 0, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right))+ left, right, _, _ = preinterp_tiles_equalized[:, gw - 1, 1:-1].unbind(2)+ tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right))# same type as the inputreturn tiles_equalized.div(255.0)diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex e639c8b57..0a00046b5 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -3,7 +3,7 @@from typing import List, Tuple, Unionimport torch-import torch.nn as nn+from torch import nn__all__ = ["normalize", "normalize_min_max", "denormalize", "Normalize", "Denormalize"]diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 4e3d6e409..57b6fc20c 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -3,7 +3,7 @@ import warningsfrom typing import Dict, Optionalimport torch-import torch.nn as nn+from torch import nnfrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.filters.kernels import get_gaussian_kernel2ddiff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex f376f8e32..736e0e7a7 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -1,7 +1,7 @@from typing import Callable, Dict, List, Optional, Typeimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Module, Tensor, concatenate, stackfrom kornia.utils.helpers import map_location_to_cpudiff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.pyindex 57999fdc3..ee0a434ce 100644--- a/kornia/feature/disk/_unets/blocks.py+++ b/kornia/feature/disk/_unets/blocks.py@@ -1,6 +1,6 @@import torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.core import Module, Tensordiff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.pyindex ce5a761df..1492154d2 100644--- a/kornia/feature/disk/_unets/unet.py+++ b/kornia/feature/disk/_unets/unet.py@@ -1,4 +1,4 @@-import torch.nn as nn+from torch import nnfrom kornia.core import Module, Tensor@@ -16,13 +16,13 @@ class Unet(Module):self.down = downself.in_features = in_features- down_dims = [in_features] + down+ down_dims = [in_features, *down]self.path_down = nn.ModuleList()for i, (d_in, d_out) in enumerate(zip(down_dims[:-1], down_dims[1:])):down_block = ThinUnetDownBlock(d_in, d_out, size=size, is_first=i == 0)self.path_down.append(down_block)- bot_dims = [down[-1]] + up+ bot_dims = [down[-1], *up]hor_dims = down_dims[-2::-1]self.path_up = nn.ModuleList()for i, (d_bot, d_hor, d_out) in enumerate(zip(bot_dims, hor_dims, up)):diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 2df949353..2b75b923d 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -1,8 +1,8 @@from typing import Dictimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.testing import is_mps_tensor_safediff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex ba38cc9f9..4e4210977 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -1,7 +1,7 @@from typing import Dictimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Module, Parameter, Tensor, tensor, zerosfrom kornia.utils.helpers import map_location_to_cpu@@ -217,7 +217,6 @@ class HyNet(Module):pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=map_location_to_cpu)self.load_state_dict(pretrained_dict, strict=True)self.eval()- returndef forward(self, x: Tensor) -> Tensor:x = self.layer1(x)diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex 8c1f0f799..69137019e 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -1,8 +1,8 @@from typing import List, Optionalimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom typing_extensions import TypedDictfrom kornia.core import Module, Tensor, concatenatediff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.pyindex 0cdd076a9..e1cfec90c 100644--- a/kornia/feature/loftr/backbone/resnet_fpn.py+++ b/kornia/feature/loftr/backbone/resnet_fpn.py@@ -1,5 +1,5 @@-import torch.nn as nnimport torch.nn.functional as F+from torch import nndef conv1x1(in_planes, out_planes, stride=1):diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.pyindex 5ea07c5b8..42fe10d06 100644--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py@@ -1,6 +1,6 @@import torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnclass FinePreprocess(nn.Module):diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.pyindex 0b1c37ec1..cf731e833 100644--- a/kornia/feature/loftr/loftr_module/transformer.py+++ b/kornia/feature/loftr/loftr_module/transformer.py@@ -2,7 +2,7 @@ import copyfrom typing import Optionalimport torch-import torch.nn as nn+from torch import nnfrom .linear_attention import FullAttention, LinearAttentiondiff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.pyindex d59bc69d9..611ead675 100644--- a/kornia/feature/loftr/utils/coarse_matching.py+++ b/kornia/feature/loftr/utils/coarse_matching.py@@ -1,8 +1,8 @@from typing import Any, Dict, Optional, Unionimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.core import Module, Tensor@@ -117,7 +117,7 @@ class CoarseMatching(Module):_, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)# normalize- feat_c0, feat_c1 = map(lambda feat: feat / feat.shape[-1] ** 0.5, [feat_c0, feat_c1])+ feat_c0, feat_c1 = (feat / feat.shape[-1] ** 0.5 for feat in [feat_c0, feat_c1])if self.match_type == 'dual_softmax':sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature@@ -236,14 +236,14 @@ class CoarseMatching(Module):)mconf_gt = torch.zeros(len(data['spv_b_ids']), device=_device) # set conf of gt paddings to all zero- b_ids, i_ids, j_ids, mconf = map(- lambda x, y: torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0),- *zip(+ b_ids, i_ids, j_ids, mconf = ( # type: ignore+ torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0) # type: ignore[has-type]+ for x, y in zip([b_ids, data['spv_b_ids']],[i_ids, data['spv_i_ids']],[j_ids, data['spv_j_ids']],[mconf, mconf_gt],- ),+ ))# These matches select patches that feed into fine-level networkdiff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.pyindex 09f6db016..a26894344 100644--- a/kornia/feature/loftr/utils/fine_matching.py+++ b/kornia/feature/loftr/utils/fine_matching.py@@ -1,7 +1,7 @@import mathimport torch-import torch.nn as nn+from torch import nnfrom kornia.geometry.subpix import dsntfrom kornia.utils.grid import create_meshgriddiff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.pyindex 3625cec59..76bbeb39b 100644--- a/kornia/feature/loftr/utils/supervision.py+++ b/kornia/feature/loftr/utils/supervision.py@@ -42,7 +42,7 @@ def spvs_coarse(data, config):scale = config['LOFTR']['RESOLUTION'][0]scale0 = scale * data['scale0'][:, None] if 'scale0' in data else scalescale1 = scale * data['scale1'][:, None] if 'scale0' in data else scale- h0, w0, h1, w1 = map(lambda x: x // scale, [H0, W0, H1, W1])+ h0, w0, h1, w1 = (x // scale for x in [H0, W0, H1, W1])# 2. warp grids# create kpts in meshgrid and resize them to image resolutiondiff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex c768ae60e..918c96f12 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -298,11 +298,10 @@ class DescriptorMatcher(Module):th: threshold on distance ratio, or other quality measure."""- known_modes = ['nn', 'mnn', 'snn', 'smnn']-def __init__(self, match_mode: str = 'snn', th: float = 0.8) -> None:super().__init__()_match_mode: str = match_mode.lower()+ self.known_modes = ['nn', 'mnn', 'snn', 'smnn']if _match_mode not in self.known_modes:raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")self.match_mode = _match_mode@@ -345,11 +344,10 @@ class GeometryAwareDescriptorMatcher(Module):th: threshold on distance ratio, or other quality measure."""- known_modes = ['fginn', "adalam"]-def __init__(self, match_mode: str = 'fginn', params: Dict[str, Tensor] = {}) -> None:super().__init__()_match_mode: str = match_mode.lower()+ self.known_modes = ['fginn', "adalam"]if _match_mode not in self.known_modes:raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")self.match_mode = _match_modediff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 5de7e384d..ec794ab2d 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -1,8 +1,8 @@from typing import Any, Dict, List, Tuple, Unionimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.constants import pifrom kornia.core import Tensor, tensor, zerosdiff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex ad0ac6f5b..d6bade110 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -1,8 +1,8 @@from typing import Dict, Optionalimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEdiff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex a722f1e2c..51bb70d6a 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -299,7 +299,6 @@ class BlobDoG(Module):def __init__(self) -> None:super().__init__()- returndef __repr__(self) -> str:return self.__class__.__name__@@ -344,7 +343,6 @@ class CornerHarris(Module):else:self.register_buffer('k', k)self.grads_mode: str = grads_mode- returndef __repr__(self) -> str:return f'{self.__class__.__name__}(k={self.k}, grads_mode={self.grads_mode})'@@ -364,7 +362,6 @@ class CornerGFTT(Module):def __init__(self, grads_mode: str = 'sobel') -> None:super().__init__()self.grads_mode: str = grads_mode- returndef __repr__(self) -> str:return f'{self.__class__.__name__}(grads_mode={self.grads_mode})'@@ -384,7 +381,6 @@ class BlobHessian(Module):def __init__(self, grads_mode: str = 'sobel') -> None:super().__init__()self.grads_mode: str = grads_mode- returndef __repr__(self) -> str:return f'{self.__class__.__name__}(grads_mode={self.grads_mode})'diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 73b627210..b88bc918f 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -2,7 +2,7 @@ import mathfrom typing import Tupleimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Module, Tensor, concatenate, eye, normalizefrom kornia.core.check import KORNIA_CHECK_SHAPE@@ -121,7 +121,6 @@ class SIFTDescriptor(Module):bias=False,)self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))- returndef get_pooling_kernel(self) -> Tensor:return self.pk.weight.detach()@@ -260,7 +259,6 @@ class DenseSIFTDescriptor(Module):self.PoolingConv.weight.data.copy_(_get_reshape_kernel(num_ang_bins, num_spatial_bins, num_spatial_bins).float())- returndef get_pooling_kernel(self) -> Tensor:return self.bin_pooling_kernel.weight.detach()diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.pyindex a0640ce05..03892353e 100644--- a/kornia/feature/sold2/backbones.py+++ b/kornia/feature/sold2/backbones.py@@ -2,8 +2,8 @@from typing import Any, Dict, List, Optional, Tuple, Type, Unionimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom torch.nn.functional import pixel_shuffle, softmaxfrom kornia.core import Modulediff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 173f050f8..7d13bfa86 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -1,7 +1,7 @@from typing import Dictimport torch-import torch.nn as nn+from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpu@@ -63,7 +63,6 @@ class SOSNet(nn.Module):pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=map_location_to_cpu)self.load_state_dict(pretrained_dict, strict=True)self.eval()- returndef forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex eabce3e0b..59a0549f3 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -1,7 +1,7 @@from typing import Dictimport torch-import torch.nn as nn+from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.utils.helpers import map_location_to_cpudiff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex bc6e9d973..0e9ec18f7 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -5,8 +5,8 @@ from __future__ import annotationsfrom collections import OrderedDictimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.core import Module, Tensor, concatenatefrom kornia.core.check import KORNIA_CHECKdiff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex e6c73ee39..a7157e25a 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -212,7 +212,6 @@ class SpatialGradient3d(Module):self.order: int = orderself.mode: str = modeself.kernel = get_spatial_gradient_kernel3d(mode, order)- returndef __repr__(self) -> str:return f"{self.__class__.__name__}(order={self.order}, mode={self.mode})"diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex caf9ae370..1438e84d1 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -36,14 +36,14 @@ def validate_bbox(boxes: torch.Tensor) -> bool:if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1), atol=1e-4):raise ValueError(- f"Boxes must have be rectangular, while get widths {str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1)}"- f" and {str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1)}"+ f"Boxes must have be rectangular, while get widths {boxes[:, 1, 0] - boxes[:, 0, 0] + 1!s}"+ f" and {boxes[:, 2, 0] - boxes[:, 3, 0] + 1!s}")if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1), atol=1e-4):raise ValueError(- f"Boxes must be rectangular, while getting heights {str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1)}"- f" and {str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1)}"+ f"Boxes must be rectangular, while getting heights {boxes[:, 2, 1] - boxes[:, 0, 1] + 1!s}"+ f" and {boxes[:, 3, 1] - boxes[:, 1, 1] + 1!s}")return Truediff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 833055af9..ba0b16db6 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -511,9 +511,7 @@ class Boxes:boxes = _boxes_to_polygons(boxes[..., 0], boxes[..., 1], boxes[..., 2], boxes[..., 3])if self._N is not None and not as_padded_sequence:- boxes = list(- torch.nn.functional.pad(o, (len(o.shape) - 1) * [0, 0] + [0, -n]) for o, n in zip(boxes, self._N)- )+ boxes = [torch.nn.functional.pad(o, (len(o.shape) - 1) * [0, 0] + [0, -n]) for o, n in zip(boxes, self._N)]else:boxes = boxes if self._is_batched else boxes.squeeze(0)return boxesdiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 67324d6b1..7d923cd4f 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -581,7 +581,7 @@ def quaternion_to_rotation_matrix()# this slightly awkward construction of the output shape is to satisfy torchscript- output_shape = list(quaternion.shape[:-1]) + [3, 3]+ output_shape = [*list(quaternion.shape[:-1]), 3, 3]matrix = matrix_flat.reshape(output_shape)return matrixdiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex efd3e4fd1..348ef925c 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -124,7 +124,7 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensr"""Get Motion (R's and t's ) from Essential matrix.Computes and return four possible poses exist for the decomposition of the Essential- matrix. The possible solutions are :math:`[R1,t], [R1,−t], [R2,t], [R2,−t]`.+ matrix. The possible solutions are :math:`[R1,t], [R1,-t], [R2,t], [R2,-t]`.Args:E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.@@ -264,7 +264,7 @@ def relative_camera_motion(Given the motion parameters of two cameras, computes the motion parameters of the secondone assuming the first one to be at the origin. If :math:`T1` and :math:`T2` are the camera motions,- the computed relative motion is :math:`T = T_{2}T^{−1}_{1}`.+ the computed relative motion is :math:`T = T_{2}T^{-1}_{1}`.Args:R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.pyindex 5cc506c4a..0fec2e7e6 100644--- a/kornia/geometry/epipolar/scene.py+++ b/kornia/geometry/epipolar/scene.py@@ -42,4 +42,4 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:# project points3d and backproject to image planepoints2d = transform_points(P, points3d.expand(num_views, -1, -1))- return dict(K=K, R=rot_mat, t=tvec, P=P, points3d=points3d, points2d=points2d)+ return {"K": K, "R": rot_mat, "t": tvec, "P": P, "points3d": points3d, "points2d": points2d}diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 54b1fb14c..44bbff995 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -332,7 +332,7 @@ class Quaternion(Module):"""rand_shape = (batch_size,) if batch_size is not None else ()- r1, r2, r3 = rand((3,) + rand_shape, device=device, dtype=dtype)+ r1, r2, r3 = rand((3, *rand_shape), device=device, dtype=dtype)q1 = (1.0 - r1).sqrt() * ((2 * pi * r2).sin())q2 = (1.0 - r1).sqrt() * ((2 * pi * r2).cos())q3 = r1.sqrt() * (2 * pi * r3).sin()diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 614c6a6b7..802294675 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -35,8 +35,6 @@ class RANSAC(Module):max_local_iterations: number of local optimization (polishing) iterations."""- supported_models = ['homography', 'fundamental', 'homography_from_linesegments']-def __init__(self,model_type: str = 'homography',@@ -47,6 +45,7 @@ class RANSAC(Module):max_lo_iters: int = 5,):super().__init__()+ self.supported_models = ['homography', 'fundamental', 'homography_from_linesegments']self.inl_th = inl_thself.max_iter = max_iterself.batch_size = batch_sizediff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex f764d0cb9..78a7ff9d7 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -200,7 +200,6 @@ class ConvSoftArgmax3d(Module):self.eps = epsself.output_value = output_valueself.strict_maxima_bonus = strict_maxima_bonus- returndef __repr__(self) -> str:return (@@ -618,7 +617,6 @@ class ConvQuadInterp3d(Module):super().__init__()self.strict_maxima_bonus = strict_maxima_bonusself.eps = eps- returndef __repr__(self) -> str:return f"{self.__class__.__name__}(strict_maxima_bonus={self.strict_maxima_bonus})"diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex e26d019e8..2a5ad21e5 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -1,7 +1,7 @@from typing import Optional, Tuple, Unionimport torch-import torch.nn as nn+from torch import nnfrom kornia.filters import gaussian_blur2dfrom kornia.utils import _extract_device_dtypediff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.pyindex bbe4986da..7d524713c 100644--- a/kornia/geometry/transform/image_registrator.py+++ b/kornia/geometry/transform/image_registrator.py@@ -2,9 +2,8 @@ from abc import abstractmethodfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Unionimport torch-import torch.nn as nnimport torch.nn.functional as F-import torch.optim as optim+from torch import nn, optimfrom kornia.core import Module, Tensorfrom kornia.geometry.conversions import angle_to_rotation_matrix, convert_affinematrix_to_homography@@ -137,7 +136,6 @@ class ImageRegistrator(Module):>>> registrator = ImageRegistrator('similarity')>>> homo = registrator.register(img_src, img_dst)"""- known_models = ['homography', 'similarity', 'translation', 'scale', 'rotation']# TODO: resolve better type, potentially using factory.def __init__(@@ -152,6 +150,7 @@ class ImageRegistrator(Module):warper: Optional[Type[BaseWarper]] = None,) -> None:super().__init__()+ self.known_models = ['homography', 'similarity', 'translation', 'scale', 'rotation']# We provide pre-defined combinations or allow user to supply model# together with warperif not isinstance(model_type, str):@@ -159,24 +158,23 @@ class ImageRegistrator(Module):raise ValueError("You must supply warper together with custom model")self.warper = warperself.model = model_type+ elif model_type.lower() == "homography":+ self.warper = HomographyWarper+ self.model = Homography()+ elif model_type.lower() == "similarity":+ self.warper = HomographyWarper+ self.model = Similarity(True, True, True)+ elif model_type.lower() == "translation":+ self.warper = HomographyWarper+ self.model = Similarity(False, False, True)+ elif model_type.lower() == "rotation":+ self.warper = HomographyWarper+ self.model = Similarity(True, False, False)+ elif model_type.lower() == "scale":+ self.warper = HomographyWarper+ self.model = Similarity(False, True, False)else:- if model_type.lower() == "homography":- self.warper = HomographyWarper- self.model = Homography()- elif model_type.lower() == "similarity":- self.warper = HomographyWarper- self.model = Similarity(True, True, True)- elif model_type.lower() == "translation":- self.warper = HomographyWarper- self.model = Similarity(False, False, True)- elif model_type.lower() == "rotation":- self.warper = HomographyWarper- self.model = Similarity(True, False, False)- elif model_type.lower() == "scale":- self.warper = HomographyWarper- self.model = Similarity(False, True, False)- else:- raise ValueError(f"{model_type} is not supported. Try {self.known_models}")+ raise ValueError(f"{model_type} is not supported. Try {self.known_models}")self.pyramid_levels = pyramid_levelsself.optimizer = optimizerself.lr = lrdiff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 075353bd0..152277b6a 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -535,7 +535,7 @@ def invert_affine_transform(matrix: Tensor) -> Tensor:r"""Invert an affine transformation.The function computes an inverse affine transformation represented by- 2×3 matrix:+ 2x3 matrix:.. math::\begin{bmatrix}@@ -543,7 +543,7 @@ def invert_affine_transform(matrix: Tensor) -> Tensor:a_{21} & a_{22} & b_{2} \\\end{bmatrix}- The result is also a 2×3 matrix of the same type as M.+ The result is also a 2x3 matrix of the same type as M.Args:matrix: original affine transform. The tensor must be@@ -875,7 +875,7 @@ def warp_affine3d(P_norm: Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4# compute meshgrid and apply to input- dsize_out: list[int] = [B, C] + list(size_out)+ dsize_out: list[int] = [B, C, *list(size_out)]grid = F.affine_grid(P_norm, dsize_out, align_corners=align_corners)return grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.pyindex 291af5381..2dc853481 100644--- a/kornia/geometry/transform/thin_plate_spline.py+++ b/kornia/geometry/transform/thin_plate_spline.py@@ -1,7 +1,7 @@from typing import Tupleimport torch-import torch.nn as nn+from torch import nnfrom kornia.utils import create_meshgridfrom kornia.utils.helpers import _torch_solve_castdiff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex 45b418da9..cceaa6a49 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -52,7 +52,7 @@ class Vector3(TensorWrapper):) -> "Vector3":if shape is None:shape = ()- return cls(rand(shape + (3,), device=device, dtype=dtype))+ return cls(rand((*shape, 3), device=device, dtype=dtype))# TODO: polish overload# @overload@@ -124,7 +124,7 @@ class Vector2(TensorWrapper):def random(cls, shape: Optional[Tuple[int, ...]] = None, device: Device = None, dtype: Dtype = None) -> "Vector2":if shape is None:shape = ()- return cls(rand(shape + (2,), device=device, dtype=dtype))+ return cls(rand((*shape, 2), device=device, dtype=dtype))@classmethoddef from_coords(diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.pyindex cebc3d2e8..f83642ccc 100644--- a/kornia/grad_estimator/ste.py+++ b/kornia/grad_estimator/ste.py@@ -1,7 +1,6 @@from typing import Any, Callable, Optional, Tuple-import torch.nn as nn-from torch import Tensor+from torch import Tensor, nnfrom torch.autograd import Function__all__ = ["STEFunction", "StraightThroughEstimator"]diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.pyindex b520e97a4..f8594f65a 100644--- a/kornia/losses/depth_smooth.py+++ b/kornia/losses/depth_smooth.py@@ -1,7 +1,7 @@from __future__ import annotationsimport torch-import torch.nn as nn+from torch import nn# Based on# https://github.com/tensorflow/models/blob/master/research/struct2depth/model.py#L625-L641diff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex c494c9ee3..b11237e17 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -1,7 +1,7 @@from __future__ import annotationsimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR@@ -37,7 +37,7 @@ def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: floatArgs:input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.labels: labels tensor with shape :math:`(N, H, W)` where each value- is :math:`0 ≤ targets[i] ≤ C−1`.+ is :math:`0 ≤ targets[i] ≤ C-1`.average:Reduction applied in multi-class scenario:- ``'micro'`` [default]: Calculate the loss across all classes.@@ -77,7 +77,7 @@ def dice_loss(input: Tensor, target: Tensor, average: str = "micro", eps: float# set dimensions for the appropriate averagingdims: tuple[int, ...] = (2, 3)if average == "micro":- dims = (1,) + dims+ dims = (1, *dims)# compute the actual dice scoreintersection = torch.sum(input_soft * target_one_hot, dims)@@ -124,7 +124,7 @@ class DiceLoss(nn.Module):Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.- Target: :math:`(N, H, W)` where each value is- :math:`0 ≤ targets[i] ≤ C−1`.+ :math:`0 ≤ targets[i] ≤ C-1`.Example:>>> N = 5 # num_classesdiff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex b0555ca5b..25ce14308 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport warningsimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Tensorfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE@@ -29,7 +29,7 @@ def focal_loss(Args:input: logits tensor with shape :math:`(N, C, *)` where C = number of classes.- target: labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C−1`.+ target: labels tensor with shape :math:`(N, *)` where each value is :math:`0 ≤ targets[i] ≤ C-1`.alpha: Weighting factor :math:`\alpha \in [0, 1]`.gamma: Focusing parameter :math:`\gamma >= 0`.reduction: Specifies the reduction to apply to the@@ -118,7 +118,7 @@ class FocalLoss(nn.Module):Shape:- Input: :math:`(N, C, *)` where C = number of classes.- Target: :math:`(N, *)` where each value is- :math:`0 ≤ targets[i] ≤ C−1`.+ :math:`0 ≤ targets[i] ≤ C-1`.Example:>>> N = 5 # num_classes@@ -171,7 +171,7 @@ def binary_focal_loss_with_logits(summed.eps: Deprecated: scalar for numerically stability when dividing. This is no longer used.pos_weight: a weight of positive examples.- It’s possible to trade off recall and precision by adding weights to positive examples.+ It`s possible to trade off recall and precision by adding weights to positive examples.Must be a vector with length equal to the number of classes.Returns:@@ -248,7 +248,7 @@ class BinaryFocalLossWithLogits(nn.Module):the number of elements in the output, ``'sum'``: the output will besummed.pos_weight: a weight of positive examples.- It’s possible to trade off recall and precision by adding weights to positive examples.+ It`s possible to trade off recall and precision by adding weights to positive examples.Must be a vector with length equal to the number of classes.Shape:diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.pyindex 9c96a74fa..53b00f16b 100644--- a/kornia/losses/hausdorff.py+++ b/kornia/losses/hausdorff.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom typing import Callableimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Module, Tensor, as_tensor, stack, tensor, where, zeros_likediff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.pyindex 464fc3166..da3a6abbf 100644--- a/kornia/losses/lovasz_hinge.py+++ b/kornia/losses/lovasz_hinge.py@@ -1,8 +1,7 @@from __future__ import annotationsimport torch-import torch.nn as nn-from torch import Tensor+from torch import Tensor, nnfrom kornia.core.check import KORNIA_CHECK_SHAPEdiff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pyindex 47bfe8fa0..a59689731 100644--- a/kornia/losses/lovasz_softmax.py+++ b/kornia/losses/lovasz_softmax.py@@ -1,8 +1,7 @@from __future__ import annotationsimport torch-import torch.nn as nn-from torch import Tensor+from torch import Tensor, nnfrom kornia.core.check import KORNIA_CHECK_SHAPE@@ -41,7 +40,7 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor:Args:pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.labels: labels tensor with shape :math:`(N, H, W)` where each value- is :math:`0 ≤ targets[i] ≤ C−1`.+ is :math:`0 ≤ targets[i] ≤ C-1`.Return:a scalar with the computed loss.@@ -129,7 +128,7 @@ class LovaszSoftmaxLoss(nn.Module):Args:pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes > 1.labels: labels tensor with shape :math:`(N, H, W)` where each value- is :math:`0 ≤ targets[i] ≤ C−1`.+ is :math:`0 ≤ targets[i] ≤ C-1`.Return:a scalar with the computed loss.diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.pyindex 0b8514835..31970a57d 100644--- a/kornia/losses/ms_ssim.py+++ b/kornia/losses/ms_ssim.py@@ -1,8 +1,8 @@from __future__ import annotationsimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nn# Based on:# https://github.com/psyrocloud/MS-SSIM_L1_LOSSdiff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.pyindex 5d9a75055..37688a304 100644--- a/kornia/losses/psnr.py+++ b/kornia/losses/psnr.py@@ -1,9 +1,9 @@from __future__ import annotationsimport torch-import torch.nn as nn+from torch import nn-import kornia.metrics as metrics+from kornia import metricsdef psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.pyindex 0e9846089..6bf36705a 100644--- a/kornia/losses/ssim.py+++ b/kornia/losses/ssim.py@@ -1,9 +1,9 @@from __future__ import annotationsimport torch-import torch.nn as nn+from torch import nn-import kornia.metrics as metrics+from kornia import metricsdef ssim_loss(diff --git a/kornia/losses/ssim3d.py b/kornia/losses/ssim3d.pyindex f581c458c..366be12da 100644--- a/kornia/losses/ssim3d.py+++ b/kornia/losses/ssim3d.py@@ -1,6 +1,6 @@from __future__ import annotations-import kornia.metrics as metrics+from kornia import metricsfrom kornia.core import Module, Tensordiff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.pyindex 026f778e8..6d43ab2d7 100644--- a/kornia/losses/tversky.py+++ b/kornia/losses/tversky.py@@ -1,8 +1,8 @@from __future__ import annotationsimport torch-import torch.nn as nnimport torch.nn.functional as F+from torch import nnfrom kornia.utils.one_hot import one_hot@@ -36,7 +36,7 @@ def tversky_loss(Args:input: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.target: labels tensor with shape :math:`(N, H, W)` where each value- is :math:`0 ≤ targets[i] ≤ C−1`.+ is :math:`0 ≤ targets[i] ≤ C-1`.alpha: the first coefficient in the denominator.beta: the second coefficient in the denominator.eps: scalar for numerical stability.@@ -111,7 +111,7 @@ class TverskyLoss(nn.Module):Shape:- Input: :math:`(N, C, H, W)` where C = number of classes.- Target: :math:`(N, H, W)` where each value is- :math:`0 ≤ targets[i] ≤ C−1`.+ :math:`0 ≤ targets[i] ≤ C-1`.Examples:>>> N = 5 # num_classesdiff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex e193bf070..9cf8f682e 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -1,7 +1,7 @@from typing import Listimport torch-import torch.nn as nn+from torch import nnfrom kornia.filters import filter2d_separable, get_gaussian_kernel1dfrom kornia.filters.filter import _compute_paddingdiff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.pyindex fdc87b669..17d24a529 100755--- a/kornia/nerf/nerf_solver.py+++ b/kornia/nerf/nerf_solver.py@@ -3,7 +3,7 @@ from typing import Optional, Unionimport torchimport torch.nn.functional as F-import torch.optim as optim+from torch import optimfrom kornia.core import Module, Tensor, tensor, zerosfrom kornia.geometry.camera import PinholeCameradiff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex cb70f3af7..93ea1d9f1 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -203,7 +203,20 @@ def generate_two_view_random_scene(x1 = scene['points2d'][0:1].to(device, dtype)x2 = scene['points2d'][1:2].to(device, dtype)- return dict(K1=K1, K2=K2, R1=R1, R2=R2, t1=t1, t2=t2, P1=P1, P2=P2, F=F_mat, X=X, x1=x1, x2=x2)+ return {+ "K1": K1,+ "K2": K2,+ "R1": R1,+ "R2": R2,+ "t1": t1,+ "t2": t2,+ "P1": P1,+ "P2": P2,+ "F": F_mat,+ "X": X,+ "x1": x1,+ "x2": x2,+ }def cartesian_product_of_parameters(**possible_parameters):diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.pyindex fcac28497..5e94f77a9 100644--- a/kornia/utils/_compat.py+++ b/kornia/utils/_compat.py@@ -33,25 +33,23 @@ if TYPE_CHECKING:def torch_meshgrid(tensors: List[Tensor], indexing: Optional[str] = None) -> Tuple[Tensor, ...]:...-else:- if torch_version_ge(1, 10, 0):+elif torch_version_ge(1, 10, 0):- def torch_meshgrid(tensors: List[Tensor], indexing: str):- return torch.meshgrid(tensors, indexing=indexing)+ def torch_meshgrid(tensors: List[Tensor], indexing: str):+ return torch.meshgrid(tensors, indexing=indexing)- else:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- def torch_meshgrid(tensors: List[Tensor], indexing: str):- return torch.meshgrid(tensors)+else:+ # TODO: remove this branch when kornia relies on torch >= 1.10.0+ def torch_meshgrid(tensors: List[Tensor], indexing: str):+ return torch.meshgrid(tensors)if TYPE_CHECKING:# TODO: remove this branch when kornia relies on torch >= 1.10.0_T = TypeVar('_T')torch_inference_mode: Callable[..., ContextManager[_T]]+elif torch_version_ge(1, 10, 0):+ torch_inference_mode = torch.inference_modeelse:- if torch_version_ge(1, 10, 0):- torch_inference_mode = torch.inference_mode- else:- # TODO: remove this branch when kornia relies on torch >= 1.10.0- torch_inference_mode = torch.no_grad+ # TODO: remove this branch when kornia relies on torch >= 1.10.0+ torch_inference_mode = torch.no_graddiff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 7d6f3db85..740ec8c6f 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -21,14 +21,10 @@ def get_cuda_device_if_available(index: int = 0) -> torch.device:Returns:torch.device"""- try:- if torch.cuda.is_available():- dev = torch.device(f'cuda:{index}')- else:- dev = torch.device('cpu')- except BaseException as e: # noqa: F841- dev = torch.device('cpu')- return dev+ if torch.cuda.is_available():+ return torch.device(f'cuda:{index}')++ return torch.device('cpu')def get_mps_device_if_available() -> torch.device:@@ -205,12 +201,11 @@ def _torch_linalg_svdvals(input: Tensor) -> Tensor:if TYPE_CHECKING:# TODO: remove this branch when kornia relies on torch >= 1.10out: Tensor+ elif torch_version_ge(1, 10):+ out = torch.linalg.svdvals(input.to(dtype))else:- if torch_version_ge(1, 10):- out = torch.linalg.svdvals(input.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.10- _, out, _ = torch.linalg.svd(input.to(dtype))+ # TODO: remove this branch when kornia relies on torch >= 1.10+ _, out, _ = torch.linalg.svd(input.to(dtype))return out.to(input.dtype)@@ -249,12 +244,11 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:A_LU: Tensorpivots: Tensorinfo: Tensor+ elif torch_version_ge(1, 13):+ A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))else:- if torch_version_ge(1, 13):- A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.13- A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)+ # TODO: remove this branch when kornia relies on torch >= 1.13+ A_LU, pivots, info = torch.lu(A.to(dtype), True, get_infos=True)valid_mask: Tensor = info == 0n_dim_B = len(B.shape)@@ -265,12 +259,11 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:if TYPE_CHECKING:# TODO: remove this branch when kornia relies on torch >= 1.13X: Tensor+ elif torch_version_ge(1, 13):+ X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))else:- if torch_version_ge(1, 13):- X = torch.linalg.lu_solve(A_LU, pivots, B.to(dtype))- else:- # TODO: remove this branch when kornia relies on torch >= 1.13- X = torch.lu_solve(B.to(dtype), A_LU, pivots)+ # TODO: remove this branch when kornia relies on torch >= 1.13+ X = torch.lu_solve(B.to(dtype), A_LU, pivots)return X.to(B.dtype), A_LU.to(A.dtype), valid_maskdiff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex cc6eefbdb..2362317a3 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -2,7 +2,7 @@ from functools import wrapsfrom typing import Any, Callable, Listimport torch-import torch.nn as nn+from torch import nnfrom kornia.core import Tensordiff --git a/kornia/x/trainers.py b/kornia/x/trainers.pyindex af753b208..72fcf4da2 100644--- a/kornia/x/trainers.py+++ b/kornia/x/trainers.py@@ -27,7 +27,7 @@ class ImageClassifierTrainer(Trainer):raise AssertionErrorout, target = argsacc1, acc5 = accuracy(out, target, topk=(1, 5))- return dict(top1=acc1.item(), top5=acc5.item())+ return {"top1": acc1.item(), "top5": acc5.item()}class SemanticSegmentationTrainer(Trainer):@@ -46,7 +46,7 @@ class SemanticSegmentationTrainer(Trainer):raise AssertionErrorout, target = argsiou = mean_iou(out.argmax(1), target, out.shape[1]).mean()- return dict(iou=iou.item())+ return {"iou": iou.item()}class ObjectDetectionTrainer(Trainer):diff --git a/pyproject.toml b/pyproject.tomlindex 7fcc5ca83..cb53089c7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -53,26 +53,22 @@ requires = [license-files = ["LICENSE"]include-package-data = false-[tool.setuptools.dynamic]- dependencies = {file = ["requirements/requirements.txt"]}- version = {attr = "kornia.__version__"}- readme = {file = ["README.md"], content-type = "text/markdown"}+ [tool.setuptools.dynamic]+ dependencies = {file = ["requirements/requirements.txt"]}+ version = {attr = "kornia.__version__"}+ readme = {file = ["README.md"], content-type = "text/markdown"}[tool.setuptools.dynamic.optional-dependencies]dev = {file = "requirements/requirements-dev.txt"}docs = {file = ["requirements/requirements-docs.txt"]}x = {file = ["requirements/requirements-x.txt"]}-[tool.setuptools.packages.find]-exclude = [- "docs*",- "test*",- "examples*",-]-namespaces = false+ [tool.setuptools.packages.find]+ exclude = ["docs*", "test*", "examples*"]+ namespaces = false-[tool.setuptools.package-data]- kornia = ["py.typed"]+ [tool.setuptools.package-data]+ kornia = ["py.typed"][tool.black]line-length = 120@@ -80,53 +76,31 @@ namespaces = falseskip-magic-trailing-comma = true[tool.ruff]-select = [- "C9",- "E",- "F",- "I",- "PL",- "S",- "UP",- "W",- "YTT",-]-ignore = [- "E402",- "F403",- "PLR0402",- "PLR1711",- "PLR5501",- "PLR2004",- "PLW2901"-]-line-length = 120-target-version = "py37"--[tool.ruff.isort]- known-first-party = ["examples", "kornia", "test"]--[tool.ruff.mccabe]-max-complexity = 39--[tool.ruff.pylint]-max-args = 16-max-branches = 45-max-returns = 13-max-statements = 258--[tool.ruff.per-file-ignores]-"*/__init__.py" = ["F401"]-"docs/*" = ["S101", "S113"]-"docs/generate_examples.py" = ["C901", "PLR0912", "PLR0915"]-"kornia/__init__.py" = ["I001"]-"kornia/augmentation/container/base.py" = ["PLC1901"]-"kornia/color/hls.py" = ["E741"]-"kornia/contrib/models/sam/architecture/image_encoder.py" = ["PLR0913"]-"kornia/enhance/equalization.py" = ["E741"]-"test/*" = ["PLR0402", "S101"]-"test/enhance/test_core.py" = ["S311"]-"test/nerf/test_camera_utils.py" = ["S310"]+ line-length = 120+ target-version = "py37"+ select = ["C9", "E", "F", "I", "PL", "S", "UP", "W", "YTT", "BLE", "C4", "RUF"]+ ignore = [+ "PLW2901", # Allow overwritten values on loops+ ]++ [tool.ruff.isort]+ known-first-party = ["examples", "kornia", "test"]++ [tool.ruff.mccabe]+ max-complexity = 40++ [tool.ruff.pylint]+ max-args = 20+ max-branches = 32+ max-returns = 16+ max-statements = 124+ allow-magic-value-types = ["str", "bytes", "int", "float"]++ [tool.ruff.per-file-ignores]+ "*/__init__.py" = ["F401", "F403"] # Allow unused imports and star imports+ "kornia/__init__.py" = ["I001"] # Allow unsorted imports+ "test/*" = ["S101", "S311", "BLE", "RUF012"] # allow assert, random, ignore BLE, mutable class attr+ "docs/*" = ["S101", "PLR0912", "PLR0915"] # allow assert, ignore max branches and statements[tool.pytest.ini_options]addopts = "--color=yes"@@ -163,12 +137,5 @@ exclude_lines = [universal = true[tool.pydocstyle]-match = '.*\.py'-ignore = """-D105-D107-D203-D204-D213-D406-D407"""+ match = '.*\.py'+ ignore = ['D105','D107','D203','D204','D213','D406','D407']diff --git a/test/augmentation/test_auto_operation.py b/test/augmentation/test_auto_operation.pyindex cfb8b0741..72d51bc1b 100644--- a/test/augmentation/test_auto_operation.py+++ b/test/augmentation/test_auto_operation.py@@ -4,9 +4,8 @@ from typing import Listimport pytestimport torch-import kornia.augmentation.auto.operations.ops as opsfrom kornia.augmentation.auto.autoaugment import AutoAugment-from kornia.augmentation.auto.operations import OperationBase+from kornia.augmentation.auto.operations import OperationBase, opsfrom kornia.augmentation.auto.rand_augment.rand_augment import RandAugmentfrom kornia.augmentation.auto.rand_augment.rand_augment import default_policy as randaug_configfrom kornia.augmentation.auto.trivial_augment import TrivialAugment@@ -18,7 +17,7 @@ from test.augmentation.test_container import reproducibility_testdef _find_all_ops() -> List[OperationBase]:_ops = [op for _, op in inspect.getmembers(ops, inspect.isclass)]- return list([op() for op in _ops if issubclass(op, OperationBase) and op != OperationBase])+ return [op() for op in _ops if issubclass(op, OperationBase) and op != OperationBase]def _test_sequential(augment_method, device, dtype):diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.pyindex 23b3192f9..fa74e5630 100644--- a/test/augmentation/test_backward.py+++ b/test/augmentation/test_backward.py@@ -1,6 +1,6 @@import pytestimport torch-import torch.nn as nn+from torch import nnfrom kornia.augmentation import (ColorJiggle,diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.pyindex 561e8e6af..163864d58 100644--- a/test/augmentation/test_backward_3d.py+++ b/test/augmentation/test_backward_3d.py@@ -1,6 +1,6 @@import pytestimport torch-import torch.nn as nn+from torch import nnfrom kornia.augmentation import RandomAffine3D, RandomMotionBlur3D, RandomPerspective3D, RandomRotation3Ddiff --git a/test/augmentation/test_dist_mapper.py b/test/augmentation/test_dist_mapper.pyindex b306d39e7..a7b13107b 100644--- a/test/augmentation/test_dist_mapper.py+++ b/test/augmentation/test_dist_mapper.py@@ -1,5 +1,5 @@import torch-import torch.nn as nn+from torch import nnfrom torch.distributions import Normalfrom kornia.augmentation.random_generator import DistributionWithMapperdiff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.pyindex 5dfa6e223..7a64b4986 100644--- a/test/augmentation/test_random_generator.py+++ b/test/augmentation/test_random_generator.py@@ -155,7 +155,7 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),}- assert set(list(jitter_params.keys())) == {+ assert set(jitter_params.keys()) == {'brightness_factor','contrast_factor','hue_factor',@@ -200,7 +200,7 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),}- assert set(list(jitter_params.keys())) == {+ assert set(jitter_params.keys()) == {'brightness_factor','contrast_factor','hue_factor',@@ -328,7 +328,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),}- assert set(list(jitter_params.keys())) == {+ assert set(jitter_params.keys()) == {'brightness_factor','contrast_factor','hue_factor',@@ -402,8 +402,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):batch_size = 2res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(torch.Size([batch_size, 1, 200, 200]))- expected = dict(- start_points=torch.tensor(+ expected = {+ 'start_points': torch.tensor([[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],@@ -411,7 +411,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- end_points=torch.tensor(+ 'end_points': torch.tensor([[[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]],[[47.0386, 6.6593], [152.2701, 29.6790], [155.5298, 170.6142], [37.0547, 177.5298]],@@ -419,7 +419,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['start_points'], expected['start_points'])assert_close(res['end_points'], expected['end_points'])@@ -430,16 +430,16 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(torch.Size([batch_size, 1, 200, 200]), same_on_batch=True)- expected = dict(- start_points=torch.tensor(+ expected = {+ 'start_points': torch.tensor([[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]]], device=device, dtype=dtype).repeat(2, 1, 1),- end_points=torch.tensor(+ 'end_points': torch.tensor([[[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]]],device=device,dtype=dtype,).repeat(2, 1, 1),- )+ }assert res.keys() == expected.keys()assert_close(res['start_points'], expected['start_points'])assert_close(res['end_points'], expected['end_points'])@@ -451,8 +451,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):torch.Size([batch_size, 1, 200, 200]))- expected = dict(- start_points=torch.tensor(+ expected = {+ 'start_points': torch.tensor([[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],@@ -460,7 +460,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- end_points=torch.tensor(+ 'end_points': torch.tensor([[[38.2269, 41.5004], [187.2864, 45.9306], [188.0448, 209.0895], [-24.3428, 228.3641]],[[44.0771, -36.6814], [242.4598, 9.3580], [235.9404, 205.7715], [24.1094, 191.9404]],@@ -468,7 +468,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['start_points'], expected['start_points'])assert_close(res['end_points'], expected['end_points'])@@ -537,14 +537,14 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):scale=scale.to(device=device, dtype=dtype) if scale is not None else None,shear=shear.to(device=device, dtype=dtype) if shear is not None else None,)(torch.Size([2, 1, 200, 200]))- expected = dict(- translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),- center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),- scale=torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),- angle=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),- shear_x=torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),- shear_y=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),- )+ expected = {+ 'translations': torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),+ 'center': torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),+ 'scale': torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),+ 'angle': torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),+ 'shear_x': torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),+ 'shear_y': torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)@@ -565,14 +565,14 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):scale=scale.to(device=device, dtype=dtype) if scale is not None else None,shear=shear.to(device=device, dtype=dtype) if shear is not None else None,)(torch.Size([2, 1, 200, 200]), True)- expected = dict(- translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),- center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),- scale=torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),- angle=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),- shear_x=torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),- shear_y=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),- )+ expected = {+ 'translations': torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),+ 'center': torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),+ 'scale': torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),+ 'angle': torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),+ 'shear_x': torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),+ 'shear_y': torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)@@ -609,20 +609,20 @@ class TestRandomCropGen(RandomGeneratorBaseTests):res = CropGenerator(torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200))(torch.Size([2, 1, 100, 100]))- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[36, 19], [95, 19], [95, 68], [36, 68]], [[19, 29], [98, 29], [98, 98], [19, 98]]],device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],device=device,dtype=dtype,),- input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),- output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),- )+ 'input_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),+ 'output_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'])assert_close(res['dst'], expected['dst'])@@ -632,20 +632,20 @@ class TestRandomCropGen(RandomGeneratorBaseTests):res = CropGenerator(torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200))(torch.Size([2, 1, 100, 100]), True)- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[36, 46], [95, 46], [95, 95], [36, 95]], [[36, 46], [115, 46], [115, 115], [36, 115]]],device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],device=device,dtype=dtype,),- input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),- output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),- )+ 'input_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),+ 'output_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'])assert_close(res['dst'], expected['dst'])@@ -689,8 +689,8 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):torch.tensor([0.7, 1.3], device=device, dtype=dtype),torch.tensor([0.9, 1.1], device=device, dtype=dtype),)(torch.Size([2, 1, 300, 300]))- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[3.0, 12.0], [298.0, 12.0], [298.0, 294.0], [3.0, 294.0]],[[8.0, 20.0], [284.0, 20.0], [284.0, 298.0], [8.0, 298.0]],@@ -698,7 +698,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],@@ -706,9 +706,9 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- input_size=torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),- output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),- )+ 'input_size': torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),+ 'output_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'])assert_close(res['dst'], expected['dst'])@@ -721,8 +721,8 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):torch.tensor([0.7, 1.3], device=device, dtype=dtype),torch.tensor([0.9, 1.1], device=device, dtype=dtype),)(torch.Size([2, 1, 300, 300]), same_on_batch=True)- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],[[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],@@ -730,7 +730,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],[[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],@@ -738,9 +738,9 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- input_size=torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),- output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),- )+ 'input_size': torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),+ 'output_size': torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'])assert_close(res['dst'], expected['dst'])@@ -792,13 +792,13 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):res = RectangleEraseGenerator(scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value)(torch.Size([2, 1, height, width]))- expected = dict(- widths=torch.tensor([100, 100], device=device, dtype=dtype),- heights=torch.tensor([0, 0], device=device, dtype=dtype),- xs=torch.tensor([0, 0], device=device, dtype=dtype),- ys=torch.tensor([6, 8], device=device, dtype=dtype),- values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),- )+ expected = {+ 'widths': torch.tensor([100, 100], device=device, dtype=dtype),+ 'heights': torch.tensor([0, 0], device=device, dtype=dtype),+ 'xs': torch.tensor([0, 0], device=device, dtype=dtype),+ 'ys': torch.tensor([6, 8], device=device, dtype=dtype),+ 'values': torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['widths'], expected['widths'])assert_close(res['widths'], expected['widths'])@@ -815,13 +815,13 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):res = RectangleEraseGenerator(scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value)(torch.Size([2, 1, height, width]), True)- expected = dict(- widths=torch.tensor([100, 100], device=device, dtype=dtype),- heights=torch.tensor([0, 0], device=device, dtype=dtype),- xs=torch.tensor([0, 0], device=device, dtype=dtype),- ys=torch.tensor([10, 10], device=device, dtype=dtype),- values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),- )+ expected = {+ 'widths': torch.tensor([100, 100], device=device, dtype=dtype),+ 'heights': torch.tensor([0, 0], device=device, dtype=dtype),+ 'xs': torch.tensor([0, 0], device=device, dtype=dtype),+ 'ys': torch.tensor([10, 10], device=device, dtype=dtype),+ 'values': torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['widths'], expected['widths'])assert_close(res['widths'], expected['widths'])@@ -856,20 +856,20 @@ class TestCenterCropGen(RandomGeneratorBaseTests):def test_random_gen(self, device, dtype):torch.manual_seed(42)res = center_crop_generator(batch_size=2, height=200, width=200, size=(120, 150))- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[25, 40], [174, 40], [174, 159], [25, 159]], [[25, 40], [174, 40], [174, 159], [25, 159]]],device=device,dtype=torch.long,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0], [149, 0], [149, 119], [0, 119]], [[0, 0], [149, 0], [149, 119], [0, 119]]],device=device,dtype=torch.long,),- input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),- output_size=torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long),- )+ 'input_size': torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),+ 'output_size': torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long),+ }assert res.keys() == expected.keys()assert_close(res['src'].to(device=device), expected['src'])assert_close(res['dst'].to(device=device), expected['dst'])@@ -918,11 +918,11 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):angle=angle.to(device=device, dtype=dtype),direction=direction.to(device=device, dtype=dtype),)(torch.Size([2]))- expected = dict(- ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),- angle_factor=torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),- direction_factor=torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype),- )+ expected = {+ 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),+ 'angle_factor': torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),+ 'direction_factor': torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)@@ -937,11 +937,11 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):angle=angle.to(device=device, dtype=dtype),direction=direction.to(device=device, dtype=dtype),)(torch.Size([2]), True)- expected = dict(- ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),- angle_factor=torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),- direction_factor=torch.tensor([0.8300, 0.8300], device=device, dtype=dtype),- )+ expected = {+ 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),+ 'angle_factor': torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),+ 'direction_factor': torch.tensor([0.8300, 0.8300], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)@@ -967,7 +967,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):torch.manual_seed(9)batch_size = 8res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]))- expected = dict(bits_factor=torch.tensor([5, 2, 4, 6, 7, 7, 2, 8], device=device, dtype=torch.int32))+ expected = {'bits_factor': torch.tensor([5, 2, 4, 6, 7, 7, 2, 8], device=device, dtype=torch.int32)}assert res.keys() == expected.keys()assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)@@ -977,7 +977,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]), same_on_batch=True)- expected = dict(bits_factor=torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32))+ expected = {'bits_factor': torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32)}assert res.keys() == expected.keys()assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)@@ -1006,11 +1006,11 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):res = PlainUniformGenerator((torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None))(torch.Size([batch_size, 1]))- expected = dict(- sharpness_factor=torch.tensor(+ expected = {+ 'sharpness_factor': torch.tensor([0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype)- )+ }assert res.keys() == expected.keys()assert_close(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)@@ -1020,11 +1020,11 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):res = PlainUniformGenerator((torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None))(torch.Size([batch_size, 1]), True)- expected = dict(- sharpness_factor=torch.tensor(+ expected = {+ 'sharpness_factor': torch.tensor([0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype)- )+ }assert res.keys() == expected.keys()assert_close(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)@@ -1055,12 +1055,12 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):res = MixupGenerator(p=0.5, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(torch.Size([batch_size, 3, 200, 200]), same_on_batch=False)- expected = dict(- mixup_pairs=torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),- mixup_lambdas=torch.tensor(+ expected = {+ 'mixup_pairs': torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),+ 'mixup_lambdas': torch.tensor([0.0000, 0.0000, 0.5739, 0.0000, 0.6274, 0.0000, 0.4414, 0.0000], device=device, dtype=dtype),- )+ }assert res.keys() == expected.keys()assert_close(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)assert_close(res['mixup_lambdas'], expected['mixup_lambdas'], rtol=1e-4, atol=1e-4)@@ -1071,12 +1071,12 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):res = MixupGenerator(p=0.999999, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(torch.Size([batch_size, 3, 200, 200]), same_on_batch=True)- expected = dict(- mixup_pairs=torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),- mixup_lambdas=torch.tensor(+ expected = {+ 'mixup_pairs': torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),+ 'mixup_lambdas': torch.tensor([0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804], device=device, dtype=dtype),- )+ }assert res.keys() == expected.keys()assert_close(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)assert_close(res['mixup_lambdas'], expected['mixup_lambdas'], rtol=1e-4, atol=1e-4)@@ -1132,9 +1132,9 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):cut_size=torch.tensor([0.0, 1.0], device=device, dtype=dtype),)(image_shape, same_on_batch=False)- expected = dict(- mix_pairs=torch.tensor([[1, 7, 5, 3, 6, 4, 2, 0]], device=device, dtype=torch.long),- crop_src=torch.tensor(+ expected = {+ 'mix_pairs': torch.tensor([[1, 7, 5, 3, 6, 4, 2, 0]], device=device, dtype=torch.long),+ 'crop_src': torch.tensor([[[[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],@@ -1150,8 +1150,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):device=device,dtype=dtype,),- image_shape=image_shape,- )+ 'image_shape': image_shape,+ }assert res.keys() == expected.keys(), res.keys()assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)@@ -1165,15 +1165,15 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):beta=torch.tensor(1.0, device=device, dtype=dtype),cut_size=torch.tensor([0.0, 1.0], device=device, dtype=dtype),)(image_shape, same_on_batch=True)- expected = dict(- mix_pairs=torch.tensor([[1, 0]], device=device, dtype=torch.long),- crop_src=torch.tensor(+ expected = {+ 'mix_pairs': torch.tensor([[1, 0]], device=device, dtype=torch.long),+ 'crop_src': torch.tensor([[[[114, 53], [113, 53], [113, 52], [114, 52]], [[114, 53], [113, 53], [113, 52], [114, 52]]]],device=device,dtype=dtype,),- image_shape=image_shape,- )+ 'image_shape': image_shape,+ }assert res.keys() == expected.keys(), res.keys()assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.pyindex 44f63129e..f033a5480 100644--- a/test/augmentation/test_random_generator_3d.py+++ b/test/augmentation/test_random_generator_3d.py@@ -58,8 +58,8 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):param_gen = PerspectiveGenerator3D(distortion_scale=torch.tensor(0.5, device=device, dtype=dtype))res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)))- expected = dict(- start_points=torch.tensor(+ expected = {+ 'start_points': torch.tensor([[[0.0, 0.0, 0.0],@@ -85,7 +85,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- end_points=torch.tensor(+ 'end_points': torch.tensor([[[44.1135, 45.7502, 19.1432],@@ -111,7 +111,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)assert_close(res['end_points'], expected['end_points'], atol=1e-4, rtol=1e-4)@@ -123,8 +123,8 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):param_gen = PerspectiveGenerator3D(distortion_scale=torch.tensor(0.5, device=device, dtype=dtype))res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)), same_on_batch=True)- expected = dict(- start_points=torch.tensor(+ expected = {+ 'start_points': torch.tensor([[[0.0, 0.0, 0.0],@@ -150,7 +150,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- end_points=torch.tensor(+ 'end_points': torch.tensor([[[44.1135, 45.7502, 19.1432],@@ -176,7 +176,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)assert_close(res['end_points'], expected['end_points'], atol=1e-4, rtol=1e-4)@@ -248,20 +248,24 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)))- expected = dict(- translations=torch.tensor(+ expected = {+ 'translations': torch.tensor([[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype),- center=torch.tensor([[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),- scale=torch.tensor([[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),- angles=torch.tensor([[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype),- sxy=torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),- sxz=torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),- syx=torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),- syz=torch.tensor([2.1063, 5.3899], device=device, dtype=dtype),- szx=torch.tensor([7.1763, 3.9873], device=device, dtype=dtype),- szy=torch.tensor([10.9438, 0.1232], device=device, dtype=dtype),- )+ 'center': torch.tensor(+ [[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype+ ),+ 'scale': torch.tensor([[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),+ 'angles': torch.tensor(+ [[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype+ ),+ 'sxy': torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),+ 'sxz': torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),+ 'syx': torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),+ 'syz': torch.tensor([2.1063, 5.3899], device=device, dtype=dtype),+ 'szx': torch.tensor([7.1763, 3.9873], device=device, dtype=dtype),+ 'szy': torch.tensor([10.9438, 0.1232], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)@@ -284,20 +288,24 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)), same_on_batch=True)- expected = dict(- translations=torch.tensor(+ expected = {+ 'translations': torch.tensor([[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype),- center=torch.tensor([[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),- scale=torch.tensor([[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),- angles=torch.tensor([[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype),- sxy=torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),- sxz=torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),- syx=torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),- syz=torch.tensor([17.3881, 17.3881], device=device, dtype=dtype),- szx=torch.tensor([11.3543, 11.3543], device=device, dtype=dtype),- szy=torch.tensor([14.8219, 14.8219], device=device, dtype=dtype),- )+ 'center': torch.tensor(+ [[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype+ ),+ 'scale': torch.tensor([[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),+ 'angles': torch.tensor(+ [[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype+ ),+ 'sxy': torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),+ 'sxz': torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),+ 'syx': torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),+ 'syz': torch.tensor([17.3881, 17.3881], device=device, dtype=dtype),+ 'szx': torch.tensor([11.3543, 11.3543], device=device, dtype=dtype),+ 'szy': torch.tensor([14.8219, 14.8219], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)@@ -334,11 +342,11 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):param_gen = RotationGenerator3D(degrees=degrees)res = param_gen(torch.Size((2,)), same_on_batch=False)- expected = dict(- yaw=torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),- pitch=torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),- roll=torch.tensor([11.7134, 18.0269], device=device, dtype=dtype),- )+ expected = {+ 'yaw': torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),+ 'pitch': torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),+ 'roll': torch.tensor([11.7134, 18.0269], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)assert_close(res['pitch'], expected['pitch'], atol=1e-4, rtol=1e-4)@@ -350,11 +358,11 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):param_gen = RotationGenerator3D(degrees=degrees)res = param_gen(torch.Size((2,)), same_on_batch=True)- expected = dict(- yaw=torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),- pitch=torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),- roll=torch.tensor([11.4859, 11.4859], device=device, dtype=dtype),- )+ expected = {+ 'yaw': torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),+ 'pitch': torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),+ 'roll': torch.tensor([11.4859, 11.4859], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)assert_close(res['pitch'], expected['pitch'], atol=1e-4, rtol=1e-4)@@ -398,8 +406,8 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):)res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)))- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[115, 53, 58],@@ -425,7 +433,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0, 0],@@ -451,7 +459,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'], atol=1e-4, rtol=1e-4)assert_close(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)@@ -464,8 +472,8 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):)res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)), same_on_batch=True)- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[115, 129, 57],@@ -491,7 +499,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0, 0],@@ -517,7 +525,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):device=device,dtype=dtype,),- )+ }assert res.keys() == expected.keys()assert_close(res['src'], expected['src'], atol=1e-4, rtol=1e-4)assert_close(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)@@ -547,8 +555,8 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):def test_random_gen(self, device, dtype):torch.manual_seed(42)res = center_crop_generator3d(batch_size=2, depth=200, height=200, width=200, size=(120, 150, 100))- expected = dict(- src=torch.tensor(+ expected = {+ 'src': torch.tensor([[[50, 25, 40],@@ -564,7 +572,7 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):device=device,dtype=torch.long,).repeat(2, 1, 1),- dst=torch.tensor(+ 'dst': torch.tensor([[[0, 0, 0],@@ -580,7 +588,7 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):device=device,dtype=torch.long,).repeat(2, 1, 1),- )+ }assert res.keys() == expected.keys()assert_close(res['src'].to(device=device), expected['src'], atol=1e-4, rtol=1e-4)assert_close(res['dst'].to(device=device), expected['dst'], atol=1e-4, rtol=1e-4)@@ -634,13 +642,13 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=False)- expected = dict(- ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),- angle_factor=torch.tensor(+ expected = {+ 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),+ 'angle_factor': torch.tensor([[27.6454, 41.4859, 71.7134], [28.3001, 58.7792, 78.0269]], device=device, dtype=dtype),- direction_factor=torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype),- )+ 'direction_factor': torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)@@ -654,13 +662,13 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=True)- expected = dict(- ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),- angle_factor=torch.tensor(+ expected = {+ 'ksize_factor': torch.tensor([3, 3], device=device, dtype=torch.int32),+ 'angle_factor': torch.tensor([[27.6454, 57.4501, 71.4859], [27.6454, 57.4501, 71.4859]], device=device, dtype=dtype),- direction_factor=torch.tensor([0.9186, 0.9186], device=device, dtype=dtype),- )+ 'direction_factor': torch.tensor([0.9186, 0.9186], device=device, dtype=dtype),+ }assert res.keys() == expected.keys()assert_close(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)assert_close(res['angle_factor'], expected['angle_factor'], rtol=1e-4, atol=1e-4)diff --git a/test/benchmark.py b/test/benchmark.pyindex 989e09a39..93ad7b36e 100644--- a/test/benchmark.py+++ b/test/benchmark.py@@ -1,7 +1,7 @@from itertools import productimport torch-import torch.utils.benchmark as benchmark+from torch.utils import benchmark# Compare takes a list of measurements which we'll save in results.results = []diff --git a/test/contrib/models/test_rt_detr.py b/test/contrib/models/test_rt_detr.pyindex 4357be503..975acb5de 100644--- a/test/contrib/models/test_rt_detr.py+++ b/test/contrib/models/test_rt_detr.py@@ -78,7 +78,7 @@ class TestRTDETR(BaseTester):out = model(images)assert isinstance(out, dict)- assert set(out.keys()) == set(["logits", "boxes"])+ assert set(out.keys()) == {"logits", "boxes"}@pytest.mark.parametrize("shape", ((1, 3, 96, 128), (2, 3, 224, 256)))def test_cardinality(self, shape, device, dtype):diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.pyindex cdf4a15c7..46920abc2 100644--- a/test/contrib/test_contrib.py+++ b/test/contrib/test_contrib.py@@ -397,7 +397,7 @@ class TestLambdaModule:img = torch.rand(B, C, H, W, device=device, dtype=dtype)func = self.add_2_layerif not callable(func):- raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")+ raise TypeError(f"Argument lambd should be callable, got {type(func).__name__!r}")assert isinstance(kornia.contrib.Lambda(func)(img), torch.Tensor)@pytest.mark.parametrize("x", [3, 2, 5])diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.pyindex 09b402936..e4dc5822d 100644--- a/test/feature/test_integrated.py+++ b/test/feature/test_integrated.py@@ -2,7 +2,7 @@ import sysimport pytestimport torch-import torch.nn as nn+from torch import nnfrom torch.autograd import gradcheckimport korniadiff --git a/test/geometry/epipolar/test_common.py b/test/geometry/epipolar/test_common.pyindex 399eb0785..558b63cb9 100644--- a/test/geometry/epipolar/test_common.py+++ b/test/geometry/epipolar/test_common.py@@ -41,4 +41,17 @@ def generate_two_view_random_scene(x1 = scene['points2d'][0:1].to(device, dtype)x2 = scene['points2d'][1:2].to(device, dtype)- return dict(K1=K1, K2=K2, R1=R1, R2=R2, t1=t1, t2=t2, P1=P1, P2=P2, F=F_mat, X=X, x1=x1, x2=x2)+ return {+ "K1": K1,+ "K2": K2,+ "R1": R1,+ "R2": R2,+ "t1": t1,+ "t2": t2,+ "P1": P1,+ "P2": P2,+ "F": F_mat,+ "X": X,+ "x1": x1,+ "x2": x2,+ }diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.pyindex 7d56e651a..7acb3978a 100644--- a/test/geometry/epipolar/test_numeric.py+++ b/test/geometry/epipolar/test_numeric.py@@ -22,15 +22,15 @@ class TestSkewSymmetric:@pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])def test_shapes(self, device, dtype, shapes):- input_shape = shapes + (3,)- output_shape = shapes + (3, 3)+ input_shape = (*shapes, 3)+ output_shape = (*shapes, 3, 3)t = torch.rand(*input_shape, device=device, dtype=dtype)cross_product_matrix = epi.cross_product_matrix(t)assert cross_product_matrix.shape == output_shape@pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])def test_funcional_shapes(self, device, dtype, shapes):- input_shape = shapes + (3,)+ input_shape = (*shapes, 3)t = torch.rand(*input_shape, device=device, dtype=dtype)# Feed batchesdiff --git a/test/geometry/liegroup/test_se2.py b/test/geometry/liegroup/test_se2.pyindex b443b3f12..a299a7ad3 100644--- a/test/geometry/liegroup/test_se2.py+++ b/test/geometry/liegroup/test_se2.py@@ -24,18 +24,18 @@ class TestSe2(BaseTester):@pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])def test_cardinality(self, device, dtype, input_shape):- t_input_shape = input_shape + (2,)- z = torch.randn(input_shape + (2,), dtype=dtype, device=device)+ t_input_shape = (*input_shape, 2)+ z = torch.randn((*input_shape, 2), dtype=dtype, device=device)t = torch.randn(t_input_shape, dtype=dtype, device=device)s = Se2(So2(torch.complex(z[..., 0], z[..., 1])), t)- theta = torch.rand(input_shape + (3,), dtype=dtype, device=device)+ theta = torch.rand((*input_shape, 3), dtype=dtype, device=device)assert s.so2.z.shape == input_shapeassert s.t.shape == t_input_shapeassert (s * s).so2.z.shape == input_shapeassert (s * s).t.shape == t_input_shapeassert s.exp(theta).so2.z.shape == input_shapeassert s.exp(theta).t.shape == t_input_shape- assert s.log().shape == input_shape + (3,)+ assert s.log().shape == (*input_shape, 3)if not any(input_shape):expected_hat_shape = (3, 3)else:diff --git a/test/geometry/liegroup/test_se3.py b/test/geometry/liegroup/test_se3.pyindex 095d9b846..8bba0f4f9 100644--- a/test/geometry/liegroup/test_se3.py+++ b/test/geometry/liegroup/test_se3.py@@ -25,7 +25,7 @@ class TestSe3(BaseTester):def _make_rand_data(self, device, dtype, batch_size, dims):shape = [] if batch_size is None else [batch_size]- return torch.rand(shape + [dims], device=device, dtype=dtype)+ return torch.rand([*shape, dims], device=device, dtype=dtype)def test_smoke(self, device, dtype):q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)diff --git a/test/geometry/liegroup/test_so3.py b/test/geometry/liegroup/test_so3.pyindex 0eef653e4..4bfd92f33 100644--- a/test/geometry/liegroup/test_so3.py+++ b/test/geometry/liegroup/test_so3.py@@ -11,7 +11,7 @@ from kornia.testing import BaseTesterclass TestSo3(BaseTester):def _make_rand_data(self, device, dtype, batch_size, dims):shape = [] if batch_size is None else [batch_size]- return torch.rand(shape + [dims], device=device, dtype=dtype)+ return torch.rand([*shape, dims], device=device, dtype=dtype)def test_smoke(self, device, dtype):q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)diff --git a/test/geometry/test_plane.py b/test/geometry/test_plane.pyindex 128810764..0822a7153 100644--- a/test/geometry/test_plane.py+++ b/test/geometry/test_plane.py@@ -46,8 +46,8 @@ class TestHyperplane(BaseTester):p0 = Vector3.random(shape, device, dtype)n0 = Vector3.random(shape, device, dtype).normalized()pl0 = Hyperplane.from_vector(n0, p0)- assert pl0.normal.shape == shape or () + (3,)- assert pl0.offset.shape == (shape + () if shape is not None else ())+ assert pl0.normal.shape == shape or (3,)+ assert pl0.offset.shape == ((*shape,) if shape is not None else ())def test_serialization(self, device, dtype, tmp_path):p = Vector3.random((), device, dtype)@@ -78,8 +78,8 @@ class TestHyperplane(BaseTester):v2 = Vector3.random(shape, device, dtype)# TODO: improve api so that we can accept Vector toop0 = Hyperplane.through(v0, v1, v2)- assert p0.normal.shape == shape or () + (3,)- assert p0.offset.shape == (shape + () if shape is not None else ())+ assert p0.normal.shape == shape or (3,)+ assert p0.offset.shape == ((*shape,) if shape is not None else ())@pytest.mark.parametrize("shape", (None, (1,), (2, 1)))def test_abs_signed_distance(self, device, dtype, shape):diff --git a/test/geometry/test_quaternion.py b/test/geometry/test_quaternion.pyindex 8f435e2ab..1ba9a654b 100644--- a/test/geometry/test_quaternion.py+++ b/test/geometry/test_quaternion.py@@ -8,7 +8,7 @@ from kornia.testing import assert_closeclass TestQuaternion:def _make_rand_data(self, device, dtype, batch_size):shape = [] if batch_size is None else [batch_size]- return torch.rand(shape + [4], device=device, dtype=dtype)+ return torch.rand([*shape, 4], device=device, dtype=dtype)def assert_close(self, actual, expected, rtol=None, atol=None):if isinstance(actual, Quaternion):diff --git a/test/geometry/test_vector.py b/test/geometry/test_vector.pyindex 49d0b2bab..3ca731406 100644--- a/test/geometry/test_vector.py+++ b/test/geometry/test_vector.py@@ -38,7 +38,7 @@ class TestVector3(BaseTester):@pytest.mark.parametrize("shape", ((), (1,), (2, 4)))def test_from_coords_tensor(self, device, dtype, shape):- xyz = torch.rand(shape + (3,), device=device, dtype=dtype)+ xyz = torch.rand((*shape, 3), device=device, dtype=dtype)vec = Vector3.from_coords(xyz[..., 0], xyz[..., 1], xyz[..., 2])assert vec.shape[:-1] == shapeassert vec.x.shape == shape@@ -107,7 +107,7 @@ class TestVector2(BaseTester):@pytest.mark.parametrize("shape", ((), (1,), (2, 4)))def test_from_coords_tensor(self, device, dtype, shape):- xy = torch.rand(shape + (2,), device=device, dtype=dtype)+ xy = torch.rand((*shape, 2), device=device, dtype=dtype)vec = Vector2.from_coords(xy[..., 0], xy[..., 1])assert vec.shape[:-1] == shapeassert vec.x.shape == shapediff --git a/test/geometry/transform/test_imgwarp3d.py b/test/geometry/transform/test_imgwarp3d.pyindex 77563668f..11913f3f8 100644--- a/test/geometry/transform/test_imgwarp3d.py+++ b/test/geometry/transform/test_imgwarp3d.py@@ -24,7 +24,7 @@ class TestWarpAffine3d:sample = torch.rand(B, C, 3, 4, 5, device=device, dtype=dtype)P = torch.rand(B, 3, 4, device=device, dtype=dtype)output = proj.warp_affine3d(sample, P, out_shape)- assert list(output.shape) == [B, C] + list(out_shape)+ assert list(output.shape) == [B, C, *list(out_shape)]def test_gradcheck(self, device):# generate input datadiff --git a/test/geometry/transform/test_thin_plate_spline.py b/test/geometry/transform/test_thin_plate_spline.pyindex 8c30532bc..d8f94bb0f 100644--- a/test/geometry/transform/test_thin_plate_spline.py+++ b/test/geometry/transform/test_thin_plate_spline.py@@ -54,7 +54,7 @@ class TestTransformParameters:@pytest.mark.parametrize('batch_size', [1, 3])@pytest.mark.parametrize('requires_grad', [True, False])def test_gradcheck(self, batch_size, device, dtype, requires_grad):- opts = dict(device=device, dtype=torch.float64)+ opts = {'device': device, 'dtype': torch.float64}src, dst = _sample_points(batch_size, **opts)src.requires_grad_(requires_grad)dst.requires_grad_(not requires_grad)@@ -125,7 +125,7 @@ class TestWarpPoints:@pytest.mark.parametrize('batch_size', [1, 3])@pytest.mark.parametrize('requires_grad', [True, False])def test_gradcheck(self, batch_size, device, dtype, requires_grad):- opts = dict(device=device, dtype=torch.float64)+ opts = {'device': device, 'dtype': torch.float64}src, dst = _sample_points(batch_size, **opts)kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)kernel.requires_grad_(requires_grad)@@ -213,7 +213,7 @@ class TestWarpImage:@pytest.mark.grad@pytest.mark.parametrize('batch_size', [1, 3])def test_gradcheck(self, batch_size, device, dtype):- opts = dict(device=device, dtype=torch.float64)+ opts = {'device': device, 'dtype': torch.float64}src, dst = _sample_points(batch_size, **opts)kernel, affine = kornia.geometry.transform.get_tps_transform(src, dst)image = torch.rand(batch_size, 3, 8, 8, requires_grad=True, **opts)diff --git a/test/integration/test_focal.py b/test/integration/test_focal.pyindex f52680109..06113376f 100644--- a/test/integration/test_focal.py+++ b/test/integration/test_focal.py@@ -2,9 +2,8 @@ import loggingimport pytestimport torch-import torch.nn as nnimport torch.nn.functional as F-import torch.optim as optim+from torch import nn, optimimport korniadiff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.pyindex 7c406d5fb..cdffb177b 100644--- a/test/integration/test_soft_argmax2d.py+++ b/test/integration/test_soft_argmax2d.py@@ -1,8 +1,7 @@import loggingimport torch-import torch.nn as nn-import torch.optim as optim+from torch import nn, optimimport korniafrom kornia.testing import assert_closediff --git a/test/integration/test_warp.py b/test/integration/test_warp.pyindex 6685242c2..c4eb3f1d5 100644--- a/test/integration/test_warp.py+++ b/test/integration/test_warp.py@@ -1,8 +1,7 @@import numpy as npimport torch-import torch.nn as nnimport torch.nn.functional as F-import torch.optim as optim+from torch import nn, optimimport korniadiff --git a/test/losses/test_hd.py b/test/losses/test_hd.pyindex e1b300389..63095cd67 100644--- a/test/losses/test_hd.py+++ b/test/losses/test_hd.py@@ -1,8 +1,8 @@import numpy as npimport pytestimport torch-import torch.nn as nnfrom scipy.ndimage import convolve+from torch import nnfrom torch.autograd import gradcheckimport korniadiff --git a/test/nerf/test_camera_utils.py b/test/nerf/test_camera_utils.pyindex 48d40ccae..dd1874122 100755--- a/test/nerf/test_camera_utils.py+++ b/test/nerf/test_camera_utils.py@@ -22,7 +22,7 @@ _ref = {def _get_data(url: str, sha256: str) -> str:req = urllib.request.Request(url)- with urllib.request.urlopen(req) as response: # nosec+ with urllib.request.urlopen(req) as response: # noqa: S310data = response.read()assert hashlib.sha256(data).hexdigest() == sha256diff --git a/test/x/test_detection.py b/test/x/test_detection.pyindex e59f858ee..3d085bab4 100644--- a/test/x/test_detection.py+++ b/test/x/test_detection.py@@ -1,6 +1,6 @@import pytestimport torch-import torch.nn as nn+from torch import nnfrom torch.utils.data import Datasetfrom kornia.x import Configuration, ObjectDetectionTrainerdiff --git a/test/x/test_image_classification.py b/test/x/test_image_classification.pyindex af0cb3319..a0761d699 100644--- a/test/x/test_image_classification.py+++ b/test/x/test_image_classification.py@@ -1,6 +1,6 @@import pytestimport torch-import torch.nn as nn+from torch import nnfrom torch.utils.data import Datasetfrom kornia.contrib import ClassificationHead, VisionTransformerdiff --git a/test/x/test_segmentation.py b/test/x/test_segmentation.pyindex ab57b14a0..8235d2542 100644--- a/test/x/test_segmentation.py+++ b/test/x/test_segmentation.py@@ -1,6 +1,6 @@import pytestimport torch-import torch.nn as nn+from torch import nnfrom torch.utils.data import Datasetfrom kornia.x import Configuration, SemanticSegmentationTrainerdiff --git a/test/x/test_x.py b/test/x/test_x.pyindex e11b31ebd..7a6bb936b 100644--- a/test/x/test_x.py+++ b/test/x/test_x.py@@ -1,5 +1,5 @@import pytest-import torch.nn as nn+from torch import nnfrom kornia.metrics import AverageMeterfrom kornia.x import EarlyStopping, ModelCheckpoint