Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

chore(lint): fix RUF036 unions and codespell typo for ruff 0.16.1 bump (#3925)

Dmytro Mishkin846c677bc0e2
diff --git a/.claude/skills/kornia-developer/SKILL.md b/.claude/skills/kornia-developer/SKILL.md
index f56b96de8..16e49b87d 100644
--- a/.claude/skills/kornia-developer/SKILL.md
+++ b/.claude/skills/kornia-developer/SKILL.md
@@ -50,10 +50,16 @@ The fix must run the **same code path** in eager and compile.
4. **Benchmark before/after β€” REQUIRED for every touched function.** A compile fix that doesn't speed anything up (or regresses eager) must be justified. Benchmarking is an experiment, not a vibe β€” hold it to experimental standards:
```python
import torch.utils.benchmark as bench
- def us(f,*a): return bench.Timer(stmt="f(*a)",globals={"f":f,"a":a}).blocked_autorange(min_run_time=1.0).median*1e6
+
+
+ def us(f, *a):
+ return bench.Timer(stmt="f(*a)", globals={"f": f, "a": a}).blocked_autorange(min_run_time=1.0).median * 1e6
+
+
eager = us(fn, *args)
- c = torch.compile(fn, fullgraph=True); c(*args) # warmup β€” compile + allocator + cudnn autotune all happen on the first call
- comp = us(c, *args)
+ c = torch.compile(fn, fullgraph=True)
+ c(*args) # warmup β€” compile + allocator + cudnn autotune all happen on the first call
+ comp = us(c, *args)
```
Methodology that makes the number trustworthy β€” deviate and the comparison is noise:
- **Warm up** before timing (first call pays compilation / autotune / lazy-init). **Never** time a single call β€” use `blocked_autorange` (statistical, median of many) so you report signal, not scheduler jitter.
diff --git a/CLAUDE.md b/CLAUDE.md
index 30b7d4c8e..1e7b87fbf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -82,12 +82,13 @@ All tests should inherit from `BaseTester` (from `testing.base`):
```python
from testing.base import BaseTester
+
class TestMyFunction(BaseTester):
- def test_smoke(self, device, dtype): ... # Basic run with all arg combinations
- def test_exception(self, device, dtype): ... # Exception cases
- def test_cardinality(self, device, dtype): ... # Output shapes
- def test_feature(self, device, dtype): ... # Correctness / numerical accuracy
- def test_gradcheck(self, device): ... # Gradient checking via self.gradcheck()
+ def test_smoke(self, device, dtype): ... # Basic run with all arg combinations
+ def test_exception(self, device, dtype): ... # Exception cases
+ def test_cardinality(self, device, dtype): ... # Output shapes
+ def test_feature(self, device, dtype): ... # Correctness / numerical accuracy
+ def test_gradcheck(self, device): ... # Gradient checking via self.gradcheck()
def test_dynamo(self, device, dtype, torch_optimizer): ... # torch.compile compat
```
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ee3a59196..63cffcdf4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -188,10 +188,10 @@ We're all volunteers. These policies help us focus on high-impact work.
```python
from testing.base import BaseTester
+
class TestMyFunction(BaseTester):
# To compare the actual and expected tensors use `self.assert_close(...)`
-
def test_smoke(self, device, dtype):
# test the function with different parameters arguments, to check if the function at least runs with all the
# arguments allowed.
@@ -241,6 +241,7 @@ We're all volunteers. These policies help us focus on high-impact work.
```python
import pytest
+
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_smoke(batch_size, device, dtype):
x = torch.rand(batch_size, 2, 3, device=device, dtype=dtype)
@@ -272,6 +273,7 @@ We're all volunteers. These policies help us focus on high-impact work.
from __future__ import annotations
import torch.nn as nn
+
class MyModule(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x
diff --git a/README.md b/README.md
index 616a0ce91..fdd07c3db 100644
--- a/README.md
+++ b/README.md
@@ -194,10 +194,7 @@ img = kr.resize(img, (256, 256), interpolation="bilinear")
img = np.stack([img] * 2) # batch images
# Define an augmentation pipeline
-augmentation_pipeline = AugmentationSequential(
- RandomAffine((-45., 45.), p=1.),
- RandomBrightness((0.,1.), p=1.)
-)
+augmentation_pipeline = AugmentationSequential(RandomAffine((-45.0, 45.0), p=1.0), RandomBrightness((0.0, 1.0), p=1.0))
# Leveraging StableDiffusion models
dslv_op = StableDiffusionDissolving()
@@ -216,6 +213,7 @@ dslv_op.save("Kornia-enhanced.jpg")
```python
import numpy as np
from kornia.onnx import ONNXSequential
+
# Chain ONNX models from HuggingFace repo and your own local model together
onnx_seq = ONNXSequential(
"hf://operators/kornia.geometry.transform.flips.Hflip",
@@ -239,6 +237,7 @@ You can now use Kornia with [TensorFlow](https://www.tensorflow.org/), [JAX](htt
```python
import kornia
+
tf_kornia = kornia.to_tensorflow()
```
diff --git a/TESTING.md b/TESTING.md
index bff0a5a4b..93740a6f5 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -44,12 +44,13 @@ All tests inherit from `testing.base.BaseTester` and implement a standard set of
```python
from testing.base import BaseTester
+
class TestMyFunction(BaseTester):
- def test_smoke(self, device, dtype): ... # basic run, all arg combinations
- def test_exception(self, device, dtype): ... # error paths
+ def test_smoke(self, device, dtype): ... # basic run, all arg combinations
+ def test_exception(self, device, dtype): ... # error paths
def test_cardinality(self, device, dtype): ... # output shapes
- def test_feature(self, device, dtype): ... # correctness / numerical accuracy
- def test_gradcheck(self, device): ... # gradient checking via self.gradcheck()
+ def test_feature(self, device, dtype): ... # correctness / numerical accuracy
+ def test_gradcheck(self, device): ... # gradient checking via self.gradcheck()
def test_dynamo(self, device, dtype, torch_optimizer): ... # torch.compile compat
```
@@ -134,8 +135,7 @@ will fail on CUDA/MPS even though the code is correct.
self.gradcheck(fn, inputs, rtol=1e-3, atol=1e-3, nondet_tol=1e-3)
# In a test calling torch.autograd.gradcheck() directly:
-torch.autograd.gradcheck(fn, inputs, eps=1e-4, atol=1e-3, rtol=1e-3,
- fast_mode=True, nondet_tol=1e-3)
+torch.autograd.gradcheck(fn, inputs, eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True, nondet_tol=1e-3)
```
A value of `1e-3` is usually sufficient; it should not exceed `atol`.
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index f01b30b99..9d0d7ced4 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -117,7 +117,6 @@ class RandomAffine3D(GeometricAugmentationBase3D):
]
] = None,
shears: Union[
- None,
torch.Tensor,
float,
Tuple[float, float],
@@ -130,6 +129,7 @@ class RandomAffine3D(GeometricAugmentationBase3D):
Tuple[float, float],
Tuple[float, float],
],
+ None,
] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 2928e7d56..c23ba5e15 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -296,7 +296,7 @@ def center_crop_generator(
height: int,
width: int,
size: Tuple[int, int],
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index b90c041ef..bd1aaca69 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -95,7 +95,6 @@ class AffineGenerator3D(RandomGeneratorBase):
]
] = None,
shears: Union[
- None,
torch.Tensor,
float,
Tuple[float, float],
@@ -108,6 +107,7 @@ class AffineGenerator3D(RandomGeneratorBase):
Tuple[float, float],
Tuple[float, float],
],
+ None,
] = None,
) -> None:
super().__init__()
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 0434982e9..e5d767eb4 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -161,7 +161,7 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index ad230c880..eb2e3147e 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -38,7 +38,7 @@ class _PostInitInjectionMetaClass(type):
class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
"""Base class for generating random augmentation parameters."""
- device: Union[None, str, torch.device] = None
+ device: Union[str, torch.device, None] = None
dtype: torch.dtype
def __init__(self) -> None:
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index d90882f08..3ca1717e9 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -187,7 +187,7 @@ class SIFTFeature(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
config: Optional[Detector_config] = None,
compile_model: bool = False,
score_threshold: float = 0.0,
@@ -225,7 +225,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
compile_modules: Union[bool, List[str]] = False,
) -> None:
if device is None:
@@ -255,7 +255,7 @@ class GFTTAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
compile_modules: Union[bool, List[str]] = False,
) -> None:
if device is None:
@@ -282,7 +282,7 @@ class HesAffNetHardNet(LocalFeature):
self,
num_features: int = 2048,
upright: bool = False,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
compile_modules: Union[bool, List[str]] = False,
) -> None:
if device is None:
@@ -309,7 +309,7 @@ class KeyNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
scale_laf: float = 1.0,
compile_model: bool = False,
score_threshold: float = 0.0,
@@ -338,7 +338,7 @@ class KeyNetAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
scale_laf: float = 1.0,
compile_model: bool = False,
score_threshold: float = 0.0,
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index bf0c1f4db..3c544bd1f 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -486,7 +486,7 @@ class Quaternion(nn.Module):
def identity(
cls,
batch_size: Optional[int] = None,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
dtype: Union[torch.dtype, None] = None,
) -> "Quaternion":
"""Create a quaternion representing an identity rotation.
@@ -531,7 +531,7 @@ class Quaternion(nn.Module):
def random(
cls,
batch_size: Optional[int] = None,
- device: Union[None, str, torch.device] = None,
+ device: Union[str, torch.device, None] = None,
dtype: Union[torch.dtype, None] = None,
) -> "Quaternion":
"""Create a random unit quaternion of shape :math:`(B, 4)`.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 3ca429887..6dbe50f3b 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -257,7 +257,7 @@ def affine3d(
def rotate(
tensor: torch.Tensor,
angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
+ center: Union[torch.Tensor, None] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
@@ -330,7 +330,7 @@ def rotate3d(
yaw: torch.Tensor,
pitch: torch.Tensor,
roll: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
+ center: Union[torch.Tensor, None] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
@@ -455,7 +455,7 @@ def translate(
def scale(
tensor: torch.Tensor,
scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
+ center: Union[torch.Tensor, None] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
@@ -1046,7 +1046,7 @@ class Rotate(nn.Module):
def __init__(
self,
angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
+ center: Union[torch.Tensor, None] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
@@ -1167,7 +1167,7 @@ class Scale(nn.Module):
def __init__(
self,
scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
+ center: Union[torch.Tensor, None] = None,
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
diff --git a/kornia/models/sam/architecture/mask_decoder.py b/kornia/models/sam/architecture/mask_decoder.py
index 07e2bbe41..f271933a0 100644
--- a/kornia/models/sam/architecture/mask_decoder.py
+++ b/kornia/models/sam/architecture/mask_decoder.py
@@ -105,7 +105,7 @@ class MaskDecoder(nn.Module):
dense_prompt_embeddings=dense_prompt_embeddings,
)
- # Select the correct mask or masks for outptu
+ # Select the correct mask or masks for output
if multimask_output:
mask_slice = slice(1, None)
else: