Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Housekeeping: more tests, warnings cleanup, tf32 issues fixed/explained (#3645)

Dmytro Mishkine14d0235ed42
diff --git a/TESTING.md b/TESTING.md
new file mode 100644
index 000000000..6b2109abe
--- /dev/null
+++ b/TESTING.md
@@ -0,0 +1,197 @@
+# Testing Guide
+
+This document explains how to run the Kornia test suite, what the common pytest flags are, and how to handle recurring classes of test failures.
+
+## Running Tests
+
+Kornia uses [pixi](https://pixi.sh) to manage the test environment.
+
+```bash
+# All tests, default device (cpu) and dtype (float32)
+pixi run test
+
+# Specific file
+pixi run test tests/geometry/test_boxes.py
+
+# Specific device and dtype
+pixi run test tests/ --device=cuda --dtype=float32
+
+# All devices and dtypes
+pixi run test tests/ --device=all --dtype=all
+
+# Skip slow tests (default); include them with --runslow
+pixi run test tests/ --runslow
+
+# Quick tests (excludes jit, grad, nn markers)
+pixi run test-quick
+```
+
+### CLI Options
+
+| Option | Env var | Default | Description |
+|---|---|---|---|
+| `--device` | `KORNIA_TEST_DEVICE` | `cpu` | `cpu`, `cuda`, `mps`, `tpu`, or `all` |
+| `--dtype` | `KORNIA_TEST_DTYPE` | `float32` | `float32`, `float64`, `float16`, `bfloat16`, or `all` |
+| `--runslow` | `KORNIA_TEST_RUNSLOW` | off | Include `@pytest.mark.slow` tests |
+| `--tf32` | `KORNIA_TEST_TF32` | off | Enable TF32 mode (see below) |
+| `--optimizer` | `KORNIA_TEST_OPTIMIZER` | `inductor` | `torch.compile` backend for dynamo tests |
+
+## Test Structure
+
+All tests inherit from `testing.base.BaseTester` and implement a standard set of methods:
+
+```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_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
+```
+
+The `device` and `dtype` fixtures are injected automatically from the CLI options. Use `self.assert_close()` for tensor comparisons β€” it automatically selects tolerances appropriate for the dtype.
+
+## Markers
+
+| Marker | Meaning |
+|---|---|
+| `@pytest.mark.slow` | Long-running test; skipped unless `--runslow` is passed |
+| `@pytest.mark.grad` | Gradient-check test |
+| `@pytest.mark.jit` | TorchScript test |
+| `@pytest.mark.nn` | Module-level test |
+| `@pytest.mark.tf32` | Known to fail under TF32 (see section below); xfail unless `--tf32` |
+
+---
+
+## Known Sources of Test Failures
+
+### 1. TF32 (TensorFloat-32) Precision
+
+**What it is.** `torch.set_float32_matmul_precision("high")` enables TF32 mode for CUDA matrix multiplications (`torch.bmm`, `torch.mm`, etc.). TF32 truncates float32 inputs to a 10-bit mantissa before the multiply-accumulate, giving roughly float16 mantissa precision for those ops. This is the default when `torch.compile` is in use and is enabled by many deep-learning frameworks for throughput.
+
+**Effect on tests.** Numerically sensitive tests that compare float32 outputs of matrix operations against hardcoded expected values (or against a CPU reference) can fail because the accumulated rounding error exceeds the test tolerance.
+
+**In Kornia's test suite.** TF32 is **off by default**. Pass `--tf32` (or set `KORNIA_TEST_TF32=true`) to enable it. Tests that are known to be sensitive to TF32 are marked `@pytest.mark.tf32`; without `--tf32` they are marked `xfail` so the suite stays green.
+
+**Fixing a TF32-sensitive test.** Prefer fixing the test data over relaxing tolerances:
+
+- Use integer-valued coordinates β€” all integers up to 2047 are exactly representable in TF32 (10-bit mantissa, so $n < 2^{10}$; integers up to 2047 via powers-of-two representation).
+- Restrict inputs to ranges that keep intermediate values well within the TF32-exact region (e.g. pixel coordinates within image bounds rather than Β±1500).
+- For camera/geometry tests, avoid near-zero depth values and use realistic intrinsic matrices (e.g. `fx=500, cx=256`) rather than fully random ones.
+- Only relax `atol`/`rtol` **as a last resort**, and only when the new tolerance is still below 0.01.
+
+**Example: 3D box transforms.** Float coordinates like `z=283.162` fall in the TF32 range [256, 512) where the representable step is 0.25. Rounding `283.162 β†’ 283.25` then computing `2Γ—283.25+1 = 567.5` instead of the expected `567.324` gives an error of 0.176 β€” which fails with `atol=1e-4` but is not meaningful. The fix is to use integer coordinates (`z=284`) which are TF32-exact.
+
+---
+
+### 2. Device-Dependent PRNG
+
+**What it is.** `torch.rand(..., device='cuda')` uses a different random number generator (Philox) than the CPU (Mersenne Twister). Even with the same seed set by `torch.manual_seed(n)`, the two devices produce **different sequences**.
+
+**Effect on tests.** Tests that:
+1. Generate random tensors directly on a non-CPU device, AND
+2. Compare against hardcoded expected values computed on CPU
+
+will fail on CUDA/MPS even though the code is correct.
+
+**In Kornia's test suite.** This affects augmentation tests with seeded expected values (`TestRandomRGBShift`, `TestRandomMixUpGen`), color roundtrip tests (`TestLuvToRgb`), and any test that runs `torch.rand(..., device=device)` without a device-independent strategy.
+
+**Fixes (in order of preference):**
+
+1. **Generate on CPU, move to device.** This is fully device-agnostic:
+ ```python
+ torch.manual_seed(42)
+ data = torch.rand(3, 4, 5).to(device=device, dtype=dtype)
+ ```
+
+2. **Skip for non-CPU when checking specific values.** Follow the existing pattern used in augmentation generator tests:
+ ```python
+ if device.type != "cpu":
+ pytest.skip("Random number sequences differ between CPU and non-CPU devices")
+ ```
+
+3. **Test properties instead of exact values** (e.g., check that output is in [0, 1] rather than matching a specific tensor).
+
+**Note.** `torch.manual_seed` seeds all devices in PyTorch β‰₯ 1.8, but the sequences still differ per device because the underlying algorithms differ.
+
+---
+
+### 3. CUDA Non-Determinism in Backward
+
+**What it is.** Some CUDA kernels use `atomicAdd` for scatter and reduction operations. The order of floating-point additions is non-deterministic across runs, producing slightly different gradient values each time backward is called.
+
+**Effect on tests.** `torch.autograd.gradcheck` calls backward twice with the same inputs and checks that the results are bit-identical (`nondet_tol=0.0` by default). If the op uses atomics, gradcheck raises `GradcheckError: Backward is not reentrant`.
+
+**Affected operations.** Histogram-based orientation estimators (`LAFOrienter`), ALIKED backbone (scatter/pool ops), and any custom op that uses `torch.scatter_add` or `atomicAdd` on CUDA.
+
+**Fix.** Pass `nondet_tol` to gradcheck:
+```python
+# In a test using self.gradcheck():
+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)
+```
+
+A value of `1e-3` is usually sufficient; it should not exceed `atol`.
+
+---
+
+### 4. Test-Order Dependencies (Full Suite vs. Isolation)
+
+**What it is.** A test can pass in isolation but fail when preceded by other tests, because some global state was mutated by an earlier test.
+
+**Common sources:**
+- **CUDA RNG state**: unseeded `torch.rand(..., device='cuda')` draws from the CUDA RNG, whose state depends on all prior CUDA random operations in the process.
+- **`torch.set_float32_matmul_precision`**: if any test (or the conftest warmup) sets this to `"high"`, all subsequent CUDA matmuls use TF32.
+- **`torch.use_deterministic_algorithms`**: a test enabling deterministic mode affects all later tests.
+- **Model caches / lazy initialisation**: some feature extractors load weights on first call and cache them globally.
+
+**Diagnosis.** If a test fails in the full suite but passes in isolation, run it with `--randomly-seed=last` (if `pytest-randomly` is installed) to reproduce the ordering, or prefix the failing test with the suspected culprit and check if the failure disappears.
+
+**Fix.** Always seed RNG state explicitly in tests that compare against reference values, and prefer generating random data on CPU:
+```python
+torch.manual_seed(0)
+data = torch.rand(B, C, H, W).to(device=device, dtype=dtype)
+```
+
+---
+
+### 5. Float32 Numerical Precision in Geometry/Camera Tests
+
+**What it is.** Operations like camera projection, LuV color conversion, and homography estimation involve divisions and non-linear functions. In float32, the roundtrip error can be significant for extreme inputs.
+
+**Common anti-patterns (and fixes):**
+
+| Anti-pattern | Problem | Fix |
+|---|---|---|
+| Depth in `[-500, 500]` | Near-zero depth β†’ `1/z` blow-up | Restrict depth to `[1, 500]` |
+| Pixel coords in `[-1500, 1500]` | Far outside image; large TF32 rounding | Use `[0, W) Γ— [0, H)` |
+| Fully random `K` matrix | Unrealistic intrinsics | Use `fx=500, cx=256` or similar |
+| Fully random rotation matrix | May not be a valid rotation | Use `axis_angle_to_rotation_matrix` |
+| `torch.rand(B, N, 2)` for homography points | Random degenerate configs | Use `create_random_homography` from `testing.geometry.create` |
+
+---
+
+### 6. SVD Numerical Stability (float32 on CUDA)
+
+**What it is.** `torch.linalg.svd` on float32 CUDA tensors can produce inaccurate singular values for ill-conditioned matrices. This affects anything that uses `_torch_svd_cast` internally: stereo camera reprojection, fundamental/essential matrix estimation, etc.
+
+**Fix (implemented in kornia).** `kornia.core.utils._torch_svd_cast` automatically promotes float32 inputs to float64 before SVD (except on MPS where float64 is unsupported), then casts the result back. This matches the existing behaviour of `_torch_solve_cast`.
+
+If you write a new function that calls SVD, use `_torch_svd_cast` rather than calling `torch.linalg.svd` directly.
+
+---
+
+## Writing Robust Tests
+
+- **Seed the RNG** when the test compares against reference values: `torch.manual_seed(seed)`.
+- **Generate random inputs on CPU** then move to device, to avoid device-specific RNG sequences.
+- **Use realistic inputs**: positive depths, in-bounds pixel coordinates, valid rotation matrices, and sensible intrinsic matrices.
+- **Avoid hardcoding CUDA expected values** computed from CPU runs β€” they will differ.
+- **Use `nondet_tol`** in `gradcheck` for ops that use CUDA atomics.
+- **Check the error magnitude** before relaxing tolerances: only relax `atol`/`rtol` if the maximum observed error is well below 0.01, and document why.
diff --git a/conftest.py b/conftest.py
index 37bc855db..266cd8d28 100644
--- a/conftest.py
+++ b/conftest.py
@@ -163,14 +163,29 @@ def pytest_collection_modifyitems(config, items):
# Filter out tests with "dynamo" or "compile" in their name
items[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]
- if config.getoption("--runslow"):
- # --runslow given in cli: do not skip slow tests
- return
-
- skip_slow = pytest.mark.skip(reason="need --runslow option to run")
- for item in items:
- if "slow" in item.keywords:
- item.add_marker(skip_slow)
+ tf32_enabled = config.getoption("--tf32")
+
+ if not config.getoption("--runslow"):
+ skip_slow = pytest.mark.skip(reason="need --runslow option to run")
+ for item in items:
+ if "slow" in item.keywords:
+ item.add_marker(skip_slow)
+
+ # Tests marked @pytest.mark.tf32 are known to produce incorrect results when
+ # TF32 is active (torch.set_float32_matmul_precision("high")). When running
+ # without --tf32 (the default), mark them xfail so the suite stays green.
+ # When --tf32 is explicitly passed, run them normally so the failures are visible.
+ if not tf32_enabled:
+ xfail_tf32 = pytest.mark.xfail(
+ reason=(
+ "This test is sensitive to TF32 (TensorFloat-32) precision reduction in CUDA matrix "
+ "multiplications. Run with --tf32 to reproduce the failure."
+ ),
+ strict=False,
+ )
+ for item in items:
+ if "tf32" in item.keywords:
+ item.add_marker(xfail_tf32)
def pytest_addoption(parser):
@@ -181,6 +196,7 @@ def pytest_addoption(parser):
KORNIA_TEST_DTYPE: Data type to test (default: float32)
KORNIA_TEST_OPTIMIZER: Optimizer backend (default: inductor)
KORNIA_TEST_RUNSLOW: Run slow tests (default: false)
+ KORNIA_TEST_TF32: Enable TF32 (TensorFloat-32) mode for CUDA matrix multiplications (default: false)
"""
parser.addoption(
"--device",
@@ -206,12 +222,22 @@ def pytest_addoption(parser):
default=os.environ.get("KORNIA_TEST_RUNSLOW", "false").lower() == "true",
help="Run slow tests (env: KORNIA_TEST_RUNSLOW)",
)
+ parser.addoption(
+ "--tf32",
+ action="store_true",
+ default=os.environ.get("KORNIA_TEST_TF32", "false").lower() == "true",
+ help=(
+ "Enable TF32 (TensorFloat-32) mode for CUDA matrix multiplications "
+ "(torch.set_float32_matmul_precision('high')). "
+ "Tests marked @pytest.mark.tf32 are expected to fail under TF32 and are skipped unless this flag is set. "
+ "(env: KORNIA_TEST_TF32)"
+ ),
+ )
def _setup_torch_compile() -> None:
"""Warm up torch.compile to reduce first-run latency in tests."""
print("Setting up torch compile...")
- torch.set_float32_matmul_precision("high")
def _dummy_fn(x, y):
return (x + y).sum()
@@ -226,6 +252,18 @@ def _setup_torch_compile() -> None:
def pytest_sessionstart(session):
"""Start pytest session."""
+ # Enable TF32 only when explicitly requested via --tf32 / KORNIA_TEST_TF32=true.
+ #
+ # TF32 (TensorFloat-32) truncates float32 inputs to a 10-bit mantissa before
+ # CUDA matrix multiplications (torch.bmm, torch.mm, etc.), giving ~float16
+ # mantissa precision for those ops. This can cause test failures for
+ # numerically sensitive operations even though the same test passes without TF32.
+ # By default we run with full float32 precision so that tests are deterministic
+ # and correct. Use --tf32 to reproduce the behaviour of torch.compile("high")
+ # and to run the @pytest.mark.tf32-marked tests.
+ if session.config.getoption("--tf32"):
+ torch.set_float32_matmul_precision("high")
+
try:
_setup_torch_compile()
except RuntimeError as ex:
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 8c780dd24..429c77280 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -161,8 +161,15 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
input data type to fp32, apply torch.svd, and cast back to the input dtype.
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
+
+ For numerical stability, fp32 inputs are promoted to fp64 (except on MPS where fp64 is unsupported).
"""
- dtype = _normalize_to_float32_or_float64(input.dtype)
+ if is_mps_tensor_safe(input):
+ dtype = torch.float32
+ elif input.dtype == torch.float32:
+ dtype = torch.float64
+ else:
+ dtype = _normalize_to_float32_or_float64(input.dtype)
out1, out2, out3H = torch.linalg.svd(input.to(dtype))
# Since kornia requires torch>=2.0.0, we can always use .mH
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index e1d3f7eae..e60374954 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -16,7 +16,6 @@
#
import math
-import warnings
from typing import Dict, Optional
import torch
@@ -121,14 +120,6 @@ class LAFAffineShapeEstimator(nn.Module):
self.patch_size = patch_size
self.affine_shape_detector = affine_shape_detector or PatchAffineShapeEstimator(self.patch_size)
self.preserve_orientation = preserve_orientation
- if preserve_orientation:
- warnings.warn(
- "`LAFAffineShapeEstimator` default behaviour is changed "
- "and now it does preserve original LAF orientation. "
- "Make sure your code accounts for this.",
- DeprecationWarning,
- stacklevel=2,
- )
def __repr__(self) -> str:
return (
@@ -214,14 +205,6 @@ class LAFAffNetShapeEstimator(nn.Module):
pretrained_dict = torch.hub.load_state_dict_from_url(urls["affnet"], map_location=torch.device("cpu"))
self.load_state_dict(pretrained_dict["state_dict"], strict=False)
self.preserve_orientation = preserve_orientation
- if preserve_orientation:
- warnings.warn(
- "`LAFAffNetShapeEstimator` default behaviour is changed "
- "and now it does preserve original LAF orientation. "
- "Make sure your code accounts for this.",
- DeprecationWarning,
- stacklevel=2,
- )
self.eval()
@staticmethod
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 057c7682a..4e928a247 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -15,7 +15,6 @@
# limitations under the License.
#
-import warnings
from typing import Any, Dict, Optional, Tuple, cast
import torch
@@ -63,13 +62,6 @@ class SOLD2(nn.Module):
def __init__(self, pretrained: bool = True, config: Optional[DetectorCfg] = None) -> None:
if isinstance(config, dict):
- warnings.warn(
- "Usage of config as a plain dictionary is deprecated in favor of"
- " `kornia.features.sold2.structures.DetectorCfg`. The support of plain dictionaries"
- "as config will be removed in kornia v0.8.0 (December 2024).",
- category=DeprecationWarning,
- stacklevel=2,
- )
config = dict_to_dataclass(cast(Dict[str, Any], config), DetectorCfg)
super().__init__()
# Initialize some parameters
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 4f449cb27..6e2deb976 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -646,8 +646,8 @@ class Boxes:
ys = torch.arange(height, device=device)
xs = torch.arange(width, device=device)
- y_mask = (ys[None, :] >= y1[:, None]) & (ys[None, :] < y2[:, None] + 1)
- x_mask = (xs[None, :] >= x1[:, None]) & (xs[None, :] < x2[:, None] + 1)
+ y_mask = (ys[None, :] >= y1[:, None]) & (ys[None, :] < y2[:, None])
+ x_mask = (xs[None, :] >= x1[:, None]) & (xs[None, :] < x2[:, None])
masks = (y_mask.unsqueeze(2) & x_mask.unsqueeze(1)).to(dtype)
return masks.view(*out_shape)
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 5c18454a3..fca915469 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -496,9 +496,6 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
[1.0000e-06, 1.0000e-06, 1.0000e-06, 1.0000e+00]]])
"""
- # warnings.warn("pinhole_matrix will be deprecated in version 0.2, "
- # "use PinholeCamera.camera_matrix instead",
- # PendingDeprecationWarning)
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
# unpack pinhole values
@@ -542,9 +539,6 @@ def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Te
[ 0.0000, 0.0000, 0.0000, 1.0000]]])
"""
- # warnings.warn("inverse_pinhole_matrix will be deprecated in version 0.2, "
- # "use PinholeCamera.intrinsics_inverse() instead",
- # PendingDeprecationWarning)
if not (len(pinhole.shape) == 2 and pinhole.shape[1] == 12):
raise AssertionError(pinhole.shape)
# unpack pinhole values
@@ -587,9 +581,6 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
0.6323, 0.3489, 0.4017]])
"""
- # warnings.warn("scale_pinhole will be deprecated in version 0.2, "
- # "use PinholeCamera.scale() instead",
- # PendingDeprecationWarning)
if not (len(pinholes.shape) == 2 and pinholes.shape[1] == 12):
raise AssertionError(pinholes.shape)
if len(scale.shape) != 1:
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 5dd153c78..a15e5c09d 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -205,7 +205,7 @@ class ScalePyramid(nn.Module):
ksize = kernel.shape[0]
pad = ksize // 2
_B, C, _H, _W = x.shape
- k = kernel.to(dtype=x.dtype)
+ k = kernel.to(device=x.device, dtype=x.dtype)
# Depthwise separable: same kernel applied independently to every channel.
k_h = k.view(1, 1, 1, ksize).expand(C, 1, 1, ksize).contiguous()
tmp = F.conv2d(F.pad(x, (pad, pad, 0, 0), mode="reflect"), k_h, groups=C)
diff --git a/pyproject.toml b/pyproject.toml
index 792a1488d..129720683 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -245,6 +245,7 @@ markers = [
"jit: mark a test as torchscript test",
"nn: mark a test as module test",
"slow: mark test as slow to run",
+ "tf32: mark a test as sensitive to TF32 (TensorFloat-32) CUDA matmul precision; xfail by default, run with --tf32 to activate",
]
filterwarnings = [
"ignore::DeprecationWarning:onnxscript.converter",
diff --git a/tests/augmentation/_3d/test_random_rotation_3d.py b/tests/augmentation/_3d/test_random_rotation_3d.py
index 87163e21a..56b661fc3 100644
--- a/tests/augmentation/_3d/test_random_rotation_3d.py
+++ b/tests/augmentation/_3d/test_random_rotation_3d.py
@@ -99,8 +99,10 @@ class TestRandomRotation3D(BaseTester):
)
out = f(input_tensor)
- self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
- self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
+ self.assert_close(out, expected, rtol=rtol, atol=atol)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
def test_batch_random_rotation(self, device, dtype):
torch.manual_seed(24) # for random reproductibility
@@ -192,8 +194,10 @@ class TestRandomRotation3D(BaseTester):
input_tensor = input_tensor.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
out = f(input_tensor)
- self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
- self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
+ self.assert_close(out, expected, rtol=rtol, atol=atol)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
def test_same_on_batch(self, device, dtype):
f = RandomRotation3D(degrees=40, same_on_batch=True)
@@ -258,8 +262,10 @@ class TestRandomRotation3D(BaseTester):
)
out = f(input_tensor)
- self.assert_close(out, expected, rtol=1e-6, atol=1e-4)
- self.assert_close(f.transform_matrix, expected_transform, rtol=1e-6, atol=1e-4)
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ rtol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-6
+ self.assert_close(out, expected, rtol=rtol, atol=atol)
+ self.assert_close(f.transform_matrix, expected_transform, rtol=rtol, atol=atol)
def test_gradcheck(self, device):
torch.manual_seed(0) # for random reproductibility
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 7ccf30de0..942e3fd40 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4896,6 +4896,8 @@ class TestRandomRGBShift(BaseTester):
assert out.shape == (2, 3, 4, 5)
def test_random_rgb_shift(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip("Random parameters are device-dependent; expected values were computed on CPU")
torch.manual_seed(0)
input = torch.tensor(
[
@@ -4918,6 +4920,8 @@ class TestRandomRGBShift(BaseTester):
self.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
def test_random_rgb_shift_same_batch(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip("Random parameters are device-dependent; expected values were computed on CPU")
torch.manual_seed(0)
input = torch.tensor(
[
@@ -5229,7 +5233,7 @@ class TestRandomJPEG(BaseTester):
img_jpeg = aug(img)
(img_jpeg - torch.zeros_like(img_jpeg)).abs().sum().backward()
# Numbers generated based on reference implementation
- img_jpeg_mean_grad_ref = torch.tensor([0.1919])
+ img_jpeg_mean_grad_ref = torch.tensor([0.1919], device=device)
# We use a slightly higher tolerance since our implementation varies from the reference implementation
self.assert_close(img.grad.mean().view(-1), img_jpeg_mean_grad_ref, rtol=0.01, atol=0.01)
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index d563a0cfd..3f77b7748 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -1400,6 +1400,10 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
)
def test_random_gen(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip(
+ "Random number sequences differ between CPU and non-CPU devices; expected values computed on CPU"
+ )
torch.manual_seed(42)
batch_size = 8
res = MixupGenerator(p=0.5, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(
@@ -1418,6 +1422,10 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
assert_close(res["mixup_lambdas"], expected["mixup_lambdas"], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip(
+ "Random number sequences differ between CPU and non-CPU devices; expected values computed on CPU"
+ )
torch.manual_seed(9)
batch_size = 8
res = MixupGenerator(p=0.999999, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(
diff --git a/tests/color/test_hls.py b/tests/color/test_hls.py
index 245893dec..25f6c1b13 100644
--- a/tests/color/test_hls.py
+++ b/tests/color/test_hls.py
@@ -16,11 +16,9 @@
#
import math
-import warnings
import pytest
import torch
-from packaging import version
from torch.autograd import gradcheck
import kornia
@@ -114,16 +112,6 @@ class TestRgbToHls(BaseTester):
def test_nan_rgb_to_hls(self, device, dtype):
if dtype == torch.float16:
pytest.skip("not work for half-precision")
-
- if device != torch.device("cpu") and version.parse(torch.__version__) < version.parse("1.7.0"):
- warnings.warn(
- "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
- "support pytorch 1.6.0. `torch.max()` have a problem in pytorch < 1.7.0 then we cannot get the correct "
- "result. https://github.com/pytorch/pytorch/issues/41781",
- DeprecationWarning,
- stacklevel=2,
- )
- return
data = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
# OpenCV
@@ -150,14 +138,6 @@ class TestRgbToHls(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse("1.7.0"):
- warnings.warn(
- "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
- "support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
- DeprecationWarning,
- stacklevel=2,
- )
- return
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.rgb_to_hls
@@ -276,14 +256,6 @@ class TestHlsToRgb(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse("1.7.0"):
- warnings.warn(
- "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
- "support pytorch 1.6.0. `hls_to_rgb()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
- DeprecationWarning,
- stacklevel=2,
- )
- return
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.hls_to_rgb
diff --git a/tests/color/test_luv.py b/tests/color/test_luv.py
index 011fd6117..3d5088e39 100644
--- a/tests/color/test_luv.py
+++ b/tests/color/test_luv.py
@@ -108,7 +108,9 @@ class TestRgbToLuv(BaseTester):
if dtype == torch.float16:
pytest.skip("not work for half-precision")
- data = torch.rand(3, 4, 5, device=device, dtype=dtype)
+ # Generate on CPU with a fixed seed so the test is order-independent.
+ torch.manual_seed(0)
+ data = torch.rand(3, 4, 5).to(device=device, dtype=dtype)
luv = kornia.color.rgb_to_luv
rgb = kornia.color.luv_to_rgb
@@ -225,7 +227,9 @@ class TestLuvToRgb(BaseTester):
if dtype == torch.float16:
pytest.skip("not work for half-precision")
- data = torch.rand(3, 4, 5, device=device, dtype=dtype)
+ # Generate on CPU with a fixed seed so the test is order-independent.
+ torch.manual_seed(0)
+ data = torch.rand(3, 4, 5).to(device=device, dtype=dtype)
luv = kornia.color.rgb_to_luv
rgb = kornia.color.luv_to_rgb
diff --git a/tests/color/test_raw.py b/tests/color/test_raw.py
index a6df10da9..b7172fc86 100644
--- a/tests/color/test_raw.py
+++ b/tests/color/test_raw.py
@@ -15,11 +15,9 @@
# limitations under the License.
#
-import warnings
import pytest
import torch
-from packaging import version
from torch.autograd import gradcheck
import kornia
@@ -146,14 +144,6 @@ class TestRawToRgb(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse("1.7.0"):
- warnings.warn(
- "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
- "support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
- DeprecationWarning,
- stacklevel=2,
- )
- return
B, C, H, W = 2, 1, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.raw_to_rgb
@@ -197,14 +187,6 @@ class TestRgbToRaw(BaseTester):
@pytest.mark.jit()
def test_jit(self, device, dtype):
- if version.parse(torch.__version__) < version.parse("1.7.0"):
- warnings.warn(
- "This test is not compatible with pytorch < 1.7.0. This message will be removed as soon as we do not "
- "support pytorch 1.6.0. `rgb_to_hls()` method for pytorch < 1.7.0 version cannot be compiled with JIT.",
- DeprecationWarning,
- stacklevel=2,
- )
- return
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.rgb_to_raw
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index 533504db9..60aa8e8f5 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -64,12 +64,6 @@ from testing.base import assert_close
],
)
def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_error):
- # TODO: include the warning in another way - possibly loggers.
- # Add GPU tests when GPU testing available
- # if torch.cuda.is_available():
- # import warnings
- # warnings.warn("Add GPU tests.")
-
if will_throw_error:
with pytest.raises(DeviceError):
_extract_device_dtype(tensor_list)
diff --git a/tests/enhance/test_rescale.py b/tests/enhance/test_rescale.py
new file mode 100644
index 000000000..78989a31e
--- /dev/null
+++ b/tests/enhance/test_rescale.py
@@ -0,0 +1,78 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.enhance.rescale import Rescale
+
+from testing.base import BaseTester
+
+
+class TestRescale(BaseTester):
+ def test_smoke(self, device, dtype):
+ r = Rescale(0.5).to(device, dtype)
+ x = torch.ones(1, 3, 4, 4, device=device, dtype=dtype)
+ assert isinstance(r(x), torch.Tensor)
+
+ def test_cardinality(self, device, dtype):
+ r = Rescale(2.0).to(device, dtype)
+ x = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
+ assert r(x).shape == x.shape
+
+ def test_float_factor(self, device, dtype):
+ r = Rescale(0.5).to(device, dtype)
+ x = torch.ones(1, 1, 2, 2, device=device, dtype=dtype) * 4.0
+ expected = torch.ones(1, 1, 2, 2, device=device, dtype=dtype) * 2.0
+ self.assert_close(r(x), expected)
+
+ def test_tensor_factor(self, device, dtype):
+ factor = torch.tensor(3.0, device=device, dtype=dtype)
+ r = Rescale(factor)
+ x = torch.ones(1, 1, 2, 2, device=device, dtype=dtype) * 2.0
+ expected = torch.ones(1, 1, 2, 2, device=device, dtype=dtype) * 6.0
+ self.assert_close(r(x), expected)
+
+ def test_zero_factor(self, device, dtype):
+ r = Rescale(0.0).to(device, dtype)
+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ expected = torch.zeros_like(x)
+ self.assert_close(r(x), expected)
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError):
+ Rescale(torch.ones(2)) # not a 0-d tensor
+
+ with pytest.raises(TypeError):
+ Rescale([0.5]) # list is not valid either
+
+ def test_gradcheck(self, device):
+ factor = torch.tensor(2.0)
+ r = Rescale(factor)
+ x = torch.rand(1, 3, 4, 4, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(r, (x,))
+
+ def test_module(self, device, dtype):
+ r1 = Rescale(2.0).to(device, dtype)
+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ self.assert_close(r1(x), x * 2.0)
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ r = Rescale(0.5).to(device, dtype)
+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ op = torch_optimizer(r)
+ self.assert_close(op(x), r(x))
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index 5ac6d4aa2..45e891e53 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -148,18 +148,20 @@ class TestLAFAffNetShapeEstimator(BaseTester):
laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
expected = torch.tensor([[[[33.2073, 0.0, 16.0], [-1.3766, 12.0456, 16.0]]]], device=device, dtype=dtype)
- self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+ atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ self.assert_close(new_laf, expected, atol=atol, rtol=1e-4)
@pytest.mark.slow
def test_gradcheck(self, device):
torch.manual_seed(0)
batch_size, channels, height, width = 1, 1, 35, 35
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device)
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device, dtype=torch.float64)
self.gradcheck(
LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype),
(laf, patches),
+ requires_grad=[False, True],
rtol=1e-3,
atol=1e-3,
- nondet_tol=1e-4,
+ nondet_tol=1e-3,
)
diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.py
index adfdc7dc7..f0c5b7a8a 100644
--- a/tests/feature/test_aliked.py
+++ b/tests/feature/test_aliked.py
@@ -228,7 +228,7 @@ class TestALIKED(BaseTester):
fm, sm = aliked.extract_dense_map(x)
return fm, sm
- assert torch.autograd.gradcheck(fn, [inp], eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True)
+ assert torch.autograd.gradcheck(fn, [inp], eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True, nondet_tol=1e-3)
# ---------------------------------------------------------------------------
diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.py
index b4ab2d227..06341ca0e 100644
--- a/tests/feature/test_disk.py
+++ b/tests/feature/test_disk.py
@@ -64,8 +64,10 @@ class TestDisk(BaseTester):
num_feat = 256
with torch.no_grad():
out = disk(data_dev["img1"], num_feat)
- self.assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(dtype))
- self.assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(dtype))
+ if device.type != "cpu":
+ pytest.skip("Reference keypoints were computed on CPU; NMS outcomes differ on non-CPU devices")
+ self.assert_close(out[0].keypoints, data_dev["disk1"][0].keypoints.to(device=device, dtype=dtype))
+ self.assert_close(out[0].descriptors, data_dev["disk1"][0].descriptors.to(device=device, dtype=dtype))
def test_heatmap_and_dense_descriptors(self, dtype, device):
disk = DISK().to(device, dtype)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 79e05ef45..6acbbb2ac 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -282,6 +282,23 @@ class TestNormalizeLAF(BaseTester):
img = torch.rand(5, 3, 10, 10)
assert inp.shape == kornia.feature.normalize_laf(inp, img).shape
+ def test_roundtrip_non_square_wide(self, device, dtype):
+ # Wide image (W >> H): x/y coords are normalized differently from scale components.
+ # The normalize→denormalize round-trip must be exact.
+ laf = torch.tensor([[10.0, 0.0, 160.0], [0.0, 10.0, 60.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ img = torch.zeros(1, 1, 120, 320, device=device, dtype=dtype)
+ laf_norm = kornia.feature.normalize_laf(laf, img)
+ laf_back = kornia.feature.denormalize_laf(laf_norm, img)
+ self.assert_close(laf_back, laf)
+
+ def test_roundtrip_non_square_tall(self, device, dtype):
+ # Tall image (H >> W): verify round-trip in the opposite aspect ratio.
+ laf = torch.tensor([[5.0, 0.0, 40.0], [0.0, 5.0, 100.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ img = torch.zeros(1, 1, 240, 80, device=device, dtype=dtype)
+ laf_norm = kornia.feature.normalize_laf(laf, img)
+ laf_back = kornia.feature.denormalize_laf(laf_norm, img)
+ self.assert_close(laf_back, laf)
+
def test_conversion(self, device):
w, h = 9, 5
laf = torch.tensor([[1, 0, 1], [0, 1, 1]]).float()
@@ -461,6 +478,28 @@ class TestExtractPatchesPyr(BaseTester):
patch = kornia.feature.extract_patches_from_pyramid(img, laf, 4, 1.0)
self.assert_close(img, patch[0])
+ def test_small_image_single_level(self, device, dtype):
+ # When min(H, W) < 2 * PS, the pyramid cannot descend beyond level 0.
+ # All patches must still have the correct shape and non-zero content.
+ PS = 16
+ img = torch.rand(1, 1, 24, 24, device=device, dtype=dtype) # 24 < 2*16=32 β†’ only level 0
+ laf = torch.tensor([[6.0, 0.0, 12.0], [0.0, 6.0, 12.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ assert patches.shape == (1, 1, 1, PS, PS)
+ assert patches.abs().sum().item() > 0
+
+ def test_multi_level_uses_correct_pyramid_level(self, device, dtype):
+ # Two LAFs with very different scales should be extracted from different pyramid levels.
+ # We verify the output shape and that the function runs without errors.
+ PS = 8
+ img = torch.rand(1, 1, 128, 128, device=device, dtype=dtype)
+ # Small-scale LAF (extracted at level 0) and large-scale LAF (extracted at higher level).
+ laf_small = torch.tensor([[2.0, 0.0, 64.0], [0.0, 2.0, 64.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ laf_large = torch.tensor([[32.0, 0.0, 64.0], [0.0, 32.0, 64.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ laf_both = torch.cat([laf_small, laf_large], dim=1)
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf_both, PS)
+ assert patches.shape == (1, 2, 1, PS, PS)
+
def test_gradcheck(self, device):
nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]], device=device, dtype=torch.float64)
nlaf = nlaf.view(1, 1, 2, 3)
diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.py
new file mode 100644
index 000000000..57454c2e3
--- /dev/null
+++ b/tests/feature/test_lightglue.py
@@ -0,0 +1,328 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.feature.lightglue import (
+ LearnableFourierPositionalEncoding,
+ LightGlue,
+ TokenConfidence,
+ apply_cached_rotary_emb,
+ normalize_keypoints,
+ pad_to_length,
+ rotate_half,
+)
+
+from testing.base import BaseTester
+
+# ---------------------------------------------------------------------------
+# Pure function tests
+# ---------------------------------------------------------------------------
+
+
+def test_normalize_keypoints_smoke():
+ kpts = torch.zeros(1, 5, 2)
+ size = torch.tensor([[100, 200]])
+ out = normalize_keypoints(kpts, size)
+ assert out.shape == kpts.shape
+
+
+def test_normalize_keypoints_center():
+ size = torch.tensor([[100, 100]])
+ kpts = size.float().unsqueeze(0) / 2 # center pixel
+ out = normalize_keypoints(kpts, size)
+ assert torch.allclose(out, torch.zeros_like(out), atol=1e-6)
+
+
+def test_normalize_keypoints_range():
+ size = torch.tensor([[128, 128]])
+ kpts = torch.rand(1, 20, 2) * 128
+ out = normalize_keypoints(kpts, size)
+ assert out.min() >= -1.0 - 1e-3
+ assert out.max() <= 1.0 + 1e-3
+
+
+def test_pad_to_length_no_pad():
+ x = torch.rand(1, 10, 64)
+ y, mask = pad_to_length(x, 5)
+ assert y is x
+ assert mask.shape[-2] == 10
+
+
+def test_pad_to_length_pads():
+ x = torch.rand(1, 5, 64)
+ y, mask = pad_to_length(x, 10)
+ assert y.shape[-2] == 10
+ assert mask.shape[-2] == 10
+ assert mask[..., :5, :].all()
+ assert not mask[..., 5:, :].any()
+
+
+def test_rotate_half_shape():
+ x = torch.rand(2, 8, 4)
+ out = rotate_half(x)
+ assert out.shape == x.shape
+
+
+def test_rotate_half_double_gives_negation():
+ x = torch.rand(1, 4, 8)
+ assert torch.allclose(rotate_half(rotate_half(x)), -x, atol=1e-6)
+
+
+def test_apply_cached_rotary_emb_shape():
+ B, N, D = 1, 10, 16
+ freqs = torch.rand(2, B, 1, N, D)
+ t = torch.rand(B, 1, N, D)
+ out = apply_cached_rotary_emb(freqs, t)
+ assert out.shape == t.shape
+
+
+# ---------------------------------------------------------------------------
+# Module tests
+# ---------------------------------------------------------------------------
+
+
+class TestLearnableFourierPositionalEncoding(BaseTester):
+ def test_smoke(self, device, dtype):
+ enc = LearnableFourierPositionalEncoding(2, 64).to(device, dtype)
+ x = torch.rand(1, 1, 10, 2, device=device, dtype=dtype)
+ out = enc(x)
+ assert out.shape[0] == 2 # cosines/sines stack
+
+ def test_cardinality(self, device, dtype):
+ M, dim = 2, 32
+ enc = LearnableFourierPositionalEncoding(M, dim).to(device, dtype)
+ B, N = 2, 15
+ x = torch.rand(B, 1, N, M, device=device, dtype=dtype)
+ out = enc(x)
+ assert out.shape[-1] == dim
+
+ def test_gradcheck(self, device):
+ enc = LearnableFourierPositionalEncoding(2, 32).to(device, torch.float64)
+ x = torch.rand(1, 1, 5, 2, device=device, dtype=torch.float64, requires_grad=True)
+ self.gradcheck(enc, (x,))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ enc = LearnableFourierPositionalEncoding(2, 32).to(device, dtype)
+ x = torch.rand(1, 1, 5, 2, device=device, dtype=dtype)
+ op = torch_optimizer(enc)
+ self.assert_close(op(x), enc(x))
+
+ def test_exception(self, device, dtype):
+ pass
+
+ def test_module(self, device, dtype):
+ enc = LearnableFourierPositionalEncoding(2, 32).to(device, dtype)
+ x = torch.rand(1, 1, 5, 2, device=device, dtype=dtype)
+ assert enc(x).shape[0] == 2
+
+
+class TestTokenConfidence(BaseTester):
+ def test_smoke(self, device, dtype):
+ tc = TokenConfidence(64).to(device, dtype)
+ d0 = torch.rand(1, 10, 64, device=device, dtype=dtype)
+ d1 = torch.rand(1, 8, 64, device=device, dtype=dtype)
+ s0, s1 = tc(d0, d1)
+ assert s0.shape == (1, 10)
+ assert s1.shape == (1, 8)
+
+ def test_cardinality(self, device, dtype):
+ tc = TokenConfidence(32).to(device, dtype)
+ B, M, N = 2, 12, 15
+ d0 = torch.rand(B, M, 32, device=device, dtype=dtype)
+ d1 = torch.rand(B, N, 32, device=device, dtype=dtype)
+ s0, s1 = tc(d0, d1)
+ assert s0.shape == (B, M)
+ assert s1.shape == (B, N)
+
+ def test_scores_in_range(self, device, dtype):
+ tc = TokenConfidence(32).to(device, dtype)
+ d0 = torch.rand(1, 20, 32, device=device, dtype=dtype)
+ d1 = torch.rand(1, 20, 32, device=device, dtype=dtype)
+ s0, s1 = tc(d0, d1)
+ assert (s0 >= 0).all() and (s0 <= 1).all()
+ assert (s1 >= 0).all() and (s1 <= 1).all()
+
+ def test_gradcheck(self, device):
+ pass # TokenConfidence uses detach() on inputs; not differentiable w.r.t. inputs
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ tc = TokenConfidence(32).to(device, dtype)
+ d0 = torch.rand(1, 10, 32, device=device, dtype=dtype)
+ d1 = torch.rand(1, 8, 32, device=device, dtype=dtype)
+ op = torch_optimizer(tc)
+ s0_jit, s1_jit = op(d0, d1)
+ s0, s1 = tc(d0, d1)
+ self.assert_close(s0_jit, s0)
+ self.assert_close(s1_jit, s1)
+
+ def test_exception(self, device, dtype):
+ pass
+
+ def test_module(self, device, dtype):
+ tc = TokenConfidence(32).to(device, dtype)
+ d0 = torch.rand(1, 5, 32, device=device, dtype=dtype)
+ d1 = torch.rand(1, 5, 32, device=device, dtype=dtype)
+ s0, _ = tc(d0, d1)
+ assert s0.shape == (1, 5)
+
+
+# ---------------------------------------------------------------------------
+# LightGlue (no pretrained weights) tests
+# ---------------------------------------------------------------------------
+
+
+def _make_lightglue(device, dtype, input_dim=64, n_layers=2):
+ """Instantiate a small LightGlue with random weights (features=None)."""
+ return (
+ LightGlue(
+ features=None,
+ input_dim=input_dim,
+ descriptor_dim=64,
+ n_layers=n_layers,
+ num_heads=4,
+ depth_confidence=-1,
+ width_confidence=-1,
+ flash=False,
+ )
+ .to(device, dtype)
+ .eval()
+ )
+
+
+def _make_data(device, dtype, B=1, M=20, N=15, H=64, W=64, D=64):
+ """Build a minimal data dict for LightGlue forward."""
+ return {
+ "image0": {
+ "keypoints": torch.rand(B, M, 2, device=device, dtype=dtype)
+ * torch.tensor([W, H], device=device, dtype=dtype),
+ "descriptors": torch.rand(B, M, D, device=device, dtype=dtype),
+ "image_size": torch.tensor([[W, H]], device=device, dtype=dtype).expand(B, -1),
+ },
+ "image1": {
+ "keypoints": torch.rand(B, N, 2, device=device, dtype=dtype)
+ * torch.tensor([W, H], device=device, dtype=dtype),
+ "descriptors": torch.rand(B, N, D, device=device, dtype=dtype),
+ "image_size": torch.tensor([[W, H]], device=device, dtype=dtype).expand(B, -1),
+ },
+ }
+
+
+class TestLightGlue(BaseTester):
+ def test_smoke(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ lg = _make_lightglue(device, dtype)
+ data = _make_data(device, dtype)
+ with torch.no_grad():
+ out = lg(data)
+ assert "matches0" in out
+ assert "matching_scores0" in out
+
+ def test_cardinality(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ B, M, N = 1, 20, 15
+ lg = _make_lightglue(device, dtype)
+ data = _make_data(device, dtype, B=B, M=M, N=N)
+ with torch.no_grad():
+ out = lg(data)
+ assert out["matches0"].shape == (B, M)
+ assert out["matches1"].shape == (B, N)
+ assert out["matching_scores0"].shape == (B, M)
+
+ def test_image_tensor_input(self, device, dtype):
+ """Accept image tensor instead of image_size."""
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ B, M, N, H, W, D = 1, 10, 8, 32, 32, 64
+ lg = _make_lightglue(device, dtype)
+ data = {
+ "image0": {
+ "keypoints": torch.rand(B, M, 2, device=device, dtype=dtype) * W,
+ "descriptors": torch.rand(B, M, D, device=device, dtype=dtype),
+ "image": torch.rand(B, 3, H, W, device=device, dtype=dtype),
+ },
+ "image1": {
+ "keypoints": torch.rand(B, N, 2, device=device, dtype=dtype) * W,
+ "descriptors": torch.rand(B, N, D, device=device, dtype=dtype),
+ "image": torch.rand(B, 3, H, W, device=device, dtype=dtype),
+ },
+ }
+ with torch.no_grad():
+ out = lg(data)
+ assert "matches0" in out
+
+ def test_matches_are_valid_indices(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ B, M, N = 1, 30, 25
+ lg = _make_lightglue(device, dtype)
+ data = _make_data(device, dtype, B=B, M=M, N=N)
+ with torch.no_grad():
+ out = lg(data)
+ m0 = out["matches0"] # (B, M), values in [-1, N-1]
+ assert (m0 >= -1).all()
+ assert (m0 < N).all()
+
+ def test_scores_in_range(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ lg = _make_lightglue(device, dtype)
+ data = _make_data(device, dtype)
+ with torch.no_grad():
+ out = lg(data)
+ scores = out["matching_scores0"]
+ assert (scores >= 0).all()
+ assert (scores <= 1).all()
+
+ def test_exception_missing_key(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ lg = _make_lightglue(device, dtype)
+ with pytest.raises(Exception):
+ lg({"image0": {}})
+
+ def test_exception_wrong_features(self, device, dtype):
+ with pytest.raises(Exception):
+ LightGlue(features="nonexistent_feature_type")
+
+ def test_gradcheck(self, device):
+ pass # LightGlue uses detach() on descriptors; not differentiable end-to-end
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ pass # LightGlue uses dynamic control flow; not torch.compile compatible
+
+ def test_module(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip("LightGlue requires float32 or float64")
+ lg = _make_lightglue(device, dtype)
+ data = _make_data(device, dtype)
+ with torch.no_grad():
+ out = lg(data)
+ assert isinstance(out, dict)
+
+ @pytest.mark.slow
+ def test_pretrained_smoke(self, device):
+ """Instantiating with real feature type downloads and loads weights."""
+ lg = LightGlue(features="disk", depth_confidence=-1, width_confidence=-1).to(device).eval()
+ B, M, N, D = 1, 50, 50, 128
+ data = _make_data(device, torch.float32, B=B, M=M, N=N, D=D)
+ with torch.no_grad():
+ out = lg(data)
+ assert "matches0" in out
diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.py
index 3af670b25..4bb2d64a2 100644
--- a/tests/feature/test_lightglue_onnx.py
+++ b/tests/feature/test_lightglue_onnx.py
@@ -47,6 +47,8 @@ class TestOnnxLightGlue:
@pytest.mark.slow
@pytest.mark.parametrize("dtype", [torch.float32])
def test_forward(self, dtype, device):
+ if device.type == "cuda" and "CUDAExecutionProvider" not in ort.get_available_providers():
+ pytest.skip("OnnxLightGlue on CUDA requires onnxruntime-gpu with CUDAExecutionProvider")
model = OnnxLightGlue(device=device)
kpts = torch.zeros(1, 5, 2, dtype=dtype, device=device)
diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.py
index 0b3d2424d..995636a10 100644
--- a/tests/feature/test_local_features_orientation.py
+++ b/tests/feature/test_local_features_orientation.py
@@ -179,4 +179,4 @@ class TestLAFOrienter(BaseTester):
laf = torch.ones(batch_size, 2, 2, 3, device=device, dtype=torch.float64)
laf[:, :, 0, 1] = 0
laf[:, :, 1, 0] = 0
- self.gradcheck(LAFOrienter(8).to(device), (laf, patches), rtol=1e-3, atol=1e-3)
+ self.gradcheck(LAFOrienter(8).to(device), (laf, patches), rtol=1e-3, atol=1e-3, nondet_tol=1e-3)
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index 7d286eaa4..4b67686e0 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -482,8 +482,9 @@ class TestLightGlueDISK(BaseTester):
assert idxs.shape[0] == dists.shape[0]
assert dists.shape[0] <= data_dev["descs1"].shape[0]
assert dists.shape[0] <= data_dev["descs2"].shape[0]
- expected_idxs = data_dev["lightglue_disk_idxs"].long()
- self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
+ if device.type == "cpu":
+ expected_idxs = data_dev["lightglue_disk_idxs"].long()
+ self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
@pytest.mark.slow
@pytest.mark.parametrize("data", ["lightglue_idxs"], indirect=True)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 19688ac7b..62a0232c8 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -18,7 +18,7 @@
import torch
import kornia
-from kornia.feature.scale_space_detector import ScaleSpaceDetector
+from kornia.feature.scale_space_detector import MultiResolutionDetector, ScaleSpaceDetector, get_default_detector_config
from kornia.geometry.subpix import ConvQuadInterp3d
from testing.base import BaseTester
@@ -67,6 +67,48 @@ class TestScaleSpaceDetector(BaseTester):
self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)
self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)
+ def test_minima_are_also_good(self, device, dtype):
+ # Image with a bright blob (local max) and dark blob (local min).
+ # With minima_are_also_good=True both should contribute to detections.
+ inp = torch.ones(1, 1, 33, 33, device=device, dtype=dtype) * 0.5
+ inp[:, :, 10:14, 10:14] = 1.0 # bright blob β†’ local maximum
+ inp[:, :, 10:14, 20:24] = 0.0 # dark blob β†’ local minimum
+ n_feats = 2
+ det_max_only = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(
+ device, dtype
+ )
+ det_minmax = ScaleSpaceDetector(
+ n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0, minima_are_also_good=True
+ ).to(device, dtype)
+ lafs_max, resps_max = det_max_only(inp)
+ lafs_minmax, resps_minmax = det_minmax(inp)
+ assert lafs_max.shape == torch.Size([1, n_feats, 2, 3])
+ assert lafs_minmax.shape == torch.Size([1, n_feats, 2, 3])
+ # minmax detector should find a higher total response magnitude (it sees both blobs).
+ assert resps_minmax.abs().sum() >= resps_max.abs().sum()
+
+ def test_scale_space_response_mode(self, device, dtype):
+ # Smoke test: scale_space_response=True uses a different internal code path.
+ # BlobDoG operates on the 5D scale-space tensor directly.
+ inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ n_feats = 5
+ det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobDoG(), scale_space_response=True).to(
+ device, dtype
+ )
+ lafs, resps = det(inp)
+ assert lafs.shape == torch.Size([1, n_feats, 2, 3])
+ assert resps.shape == torch.Size([1, n_feats])
+
+ def test_few_detections_padding(self, device, dtype):
+ # Constant image β†’ very few (possibly zero) NMS candidates; output must still
+ # have the requested shape because the detect() method pads with zeros.
+ inp = torch.ones(1, 1, 32, 32, device=device, dtype=dtype)
+ n_feats = 20
+ det = ScaleSpaceDetector(n_feats, subpix_module=ConvQuadInterp3d(10)).to(device, dtype)
+ lafs, resps = det(inp)
+ assert lafs.shape == torch.Size([1, n_feats, 2, 3])
+ assert resps.shape == torch.Size([1, n_feats])
+
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 7, 7
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
@@ -74,3 +116,78 @@ class TestScaleSpaceDetector(BaseTester):
# indexed in-place assignments that are incompatible with torch.autograd.gradcheck.
det = ScaleSpaceDetector(2, subpix_module=ConvQuadInterp3d(10)).to(device)
self.gradcheck(det, patches, nondet_tol=1e-4)
+
+
+class TestMultiResolutionDetector(BaseTester):
+ def _make_detector(self, num_features: int = 50, **config_overrides):
+ cfg = get_default_detector_config()
+ cfg.update(config_overrides)
+ return MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=num_features, config=cfg)
+
+ def test_shape(self, device, dtype):
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector().to(device, dtype)
+ lafs, resps = det(inp)
+ assert lafs.shape == torch.Size([1, 50, 2, 3])
+ assert resps.shape == torch.Size([1, 50])
+
+ def test_shape_non_square(self, device, dtype):
+ inp = torch.rand(1, 1, 48, 96, device=device, dtype=dtype)
+ det = self._make_detector().to(device, dtype)
+ lafs, _ = det(inp)
+ assert lafs.shape == torch.Size([1, 50, 2, 3])
+
+ def test_lafs_inside_image(self, device, dtype):
+ # All detected LAF centers should lie within the image boundaries.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det = self._make_detector(num_features=20).to(device, dtype)
+ lafs, _ = det(inp)
+ cx = lafs[0, :, 0, 2]
+ cy = lafs[0, :, 1, 2]
+ assert (cx >= 0).all() and (cx <= 64).all()
+ assert (cy >= 0).all() and (cy <= 64).all()
+
+ def test_no_upscale_levels(self, device, dtype):
+ # up_levels=0 disables the upsampling branch; should still produce valid output.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ cfg = get_default_detector_config()
+ cfg["up_levels"] = 0
+ cfg["pyramid_levels"] = 2
+ det = MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=20, config=cfg).to(device, dtype)
+ lafs, _ = det(inp)
+ assert lafs.shape == torch.Size([1, 20, 2, 3])
+
+ def test_with_upscale_levels(self, device, dtype):
+ # up_levels > 0 exercises the upsampling code path.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ cfg = get_default_detector_config()
+ cfg["up_levels"] = 2
+ cfg["pyramid_levels"] = 1
+ det = MultiResolutionDetector(kornia.feature.BlobHessian(), num_features=20, config=cfg).to(device, dtype)
+ lafs, _ = det(inp)
+ assert lafs.shape == torch.Size([1, 20, 2, 3])
+
+ def test_score_threshold_reduces_detections(self, device, dtype):
+ # A very high score_threshold should leave no real detections: all returned responses
+ # will be the sentinel fill value (very negative), while shape remains fixed.
+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ det_no_thresh = self._make_detector(num_features=50).to(device, dtype)
+ det_high_thresh = MultiResolutionDetector(
+ kornia.feature.BlobHessian(), num_features=50, score_threshold=1e6
+ ).to(device, dtype)
+ lafs_no_thresh, resps_no_thresh = det_no_thresh(inp)
+ lafs_high_thresh, resps_high_thresh = det_high_thresh(inp)
+ assert lafs_high_thresh.shape == lafs_no_thresh.shape
+ # With an impossibly high threshold all slots contain the fill sentinel (< 0),
+ # while real detections always have positive responses.
+ assert resps_no_thresh.max().item() > 0
+ assert (resps_high_thresh <= 0).all()
+
+ def test_smoke_with_blob_image(self, device, dtype):
+ # Synthetic image with a bright blob β€” detector should find it.
+ inp = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)
+ inp[:, :, 28:36, 28:36] = 1.0
+ det = self._make_detector(num_features=5).to(device, dtype)
+ lafs, resps = det(inp)
+ assert lafs.shape == torch.Size([1, 5, 2, 3])
+ assert resps.abs().max().item() > 0
diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.py
index 1e531c2a5..37d6d9f76 100644
--- a/tests/filters/test_in_range.py
+++ b/tests/filters/test_in_range.py
@@ -28,8 +28,8 @@ from testing.base import BaseTester, assert_close
def test_in_range(device, dtype):
torch.manual_seed(1)
- input_tensor = torch.rand(1, 3, 3, 3, device=device)
- input_tensor = input_tensor.to(dtype=dtype)
+ # Generate on CPU first so the expected mask is device-independent, then move to target device.
+ input_tensor = torch.rand(1, 3, 3, 3).to(dtype=dtype).to(device=device)
expected = torch.tensor([[[[1.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]], device=device, dtype=dtype)
lower = (0.2, 0.3, 0.4)
upper = (0.8, 0.9, 1.0)
@@ -48,8 +48,8 @@ class TestInRange(BaseTester):
def test_smoke(self, device, dtype):
torch.manual_seed(1)
- input_tensor = torch.rand(1, 3, 3, 3, device=device)
- input_tensor = input_tensor.to(dtype=dtype)
+ # Generate on CPU first so the expected mask is device-independent, then move to target device.
+ input_tensor = torch.rand(1, 3, 3, 3).to(dtype=dtype).to(device=device)
expected = self._get_expected(device=device, dtype=dtype)
res = InRange(lower=(0.2, 0.3, 0.4), upper=(0.8, 0.9, 1.0), return_mask=True)(input_tensor)
assert expected.shape == res.shape
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 36cc3b416..4ff2e5e07 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -74,7 +74,10 @@ class TestCam2Pixel(BaseTester):
cx, cy = W / 2, H / 2
eps = 1e-12
seed = 77
- low, high = -500, 500
+ # Use normalized image-plane coords so that projected pixel values stay in [0,W) x [0,H).
+ # cam_x/z in [-0.5, 0.5] gives pixel_x in [cx - fx/2, cx + fx/2] = [0, W).
+ low_norm, high_norm = -0.45, 0.45
+ low_z, high_z = 1.0, 500.0
intrinsics = self._create_intrinsics(batch_size, fx, fy, cx, cy, device=device, dtype=dtype)
intrinsics_inv = self._create_intrinsics_inv(batch_size, fx, fy, cx, cy, device=device, dtype=dtype)
@@ -84,7 +87,10 @@ class TestCam2Pixel(BaseTester):
proj_mat = intrinsics
torch.manual_seed(seed)
- cam_coords_input = self._get_samples((batch_size, H, W, 3), low, high, device, dtype)
+ # Generate z first, then x,y as z * normalized_coord so pixel coords stay in image bounds
+ cam_coords_z = self._get_samples((batch_size, H, W, 1), low_z, high_z, device, dtype)
+ cam_coords_xy = self._get_samples((batch_size, H, W, 2), low_norm, high_norm, device, dtype) * cam_coords_z
+ cam_coords_input = torch.cat([cam_coords_xy, cam_coords_z], dim=-1)
pixel_coords_output = kornia.geometry.camera.cam2pixel(
cam_coords_src=cam_coords_input, dst_proj_src=proj_mat, eps=eps
@@ -178,12 +184,18 @@ class TestPixel2Cam(BaseTester):
cx, cy = W / 2, H / 2
eps = 1e-12
seed = 77
- low_1, high_1 = -500, 500
- low_2, high_2 = -(max(W, H) * 3), (max(W, H) * 3)
+ # Depth must be positive and bounded away from zero to avoid 1/z blow-up.
+ # Pixel coords restricted to image bounds [0,W) x [0,H) to avoid TF32 precision issues
+ # from large coordinate values in matrix multiplication.
+ low_1, high_1 = 1.0, 500.0
+ low_2x, high_2x = 0.0, float(W)
+ low_2y, high_2y = 0.0, float(H)
torch.manual_seed(seed)
depth = self._get_samples((batch_size, 1, H, W), low_1, high_1, device, dtype)
- pixel_coords = self._get_samples((batch_size, H, W, 2), low_2, high_2, device, dtype)
+ pixel_coords_x = self._get_samples((batch_size, H, W, 1), low_2x, high_2x, device, dtype)
+ pixel_coords_y = self._get_samples((batch_size, H, W, 1), low_2y, high_2y, device, dtype)
+ pixel_coords = torch.cat([pixel_coords_x, pixel_coords_y], dim=-1)
last_ch = torch.ones((batch_size, H, W, 1), device=device, dtype=dtype)
pixel_coords_input = torch.cat([pixel_coords, last_ch], axis=-1)
diff --git a/tests/geometry/subpix/test_nms.py b/tests/geometry/subpix/test_nms.py
index 8dec998b9..a67869961 100644
--- a/tests/geometry/subpix/test_nms.py
+++ b/tests/geometry/subpix/test_nms.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import pytest
import torch
import kornia
@@ -33,6 +34,96 @@ class TestNMS2d(BaseTester):
nms = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)
assert nms(inp).shape == inp.shape
+ def test_shape_5x5(self, device):
+ inp = torch.ones(1, 2, 10, 10, device=device)
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((5, 5)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_shape_7x7(self, device):
+ inp = torch.ones(1, 2, 14, 14, device=device)
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((7, 7)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_nms_5x5_single_peak(self, device):
+ # A single isolated peak should be preserved; everything else zeroed.
+ inp = torch.zeros(1, 1, 15, 15, device=device)
+ inp[0, 0, 7, 7] = 1.0
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((5, 5)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 7, 7].item() == pytest.approx(1.0)
+ assert out.sum().item() == pytest.approx(1.0)
+
+ def test_nms_5x5_suppress_close_neighbor(self, device):
+ # 5x5 kernel has radius 2 (checks Β±2 pixels). Two peaks separated by exactly 2 pixels
+ # are inside each other's window; only the higher one survives.
+ inp = torch.zeros(1, 1, 20, 20, device=device)
+ inp[0, 0, 8, 8] = 2.0
+ inp[0, 0, 8, 10] = 1.0 # distance 2 β€” inside the 5x5 neighbourhood of (8,8)
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((5, 5)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 8, 8].item() == pytest.approx(2.0)
+ assert out[0, 0, 8, 10].item() == pytest.approx(0.0)
+
+ def test_nms_5x5_keep_far_peaks(self, device):
+ # Two peaks separated by 5 pixels (outside a 5x5 Β±2 window): both survive.
+ inp = torch.zeros(1, 1, 20, 20, device=device)
+ inp[0, 0, 4, 4] = 2.0
+ inp[0, 0, 4, 9] = 1.0 # distance 5 β€” outside the 5x5 neighbourhood
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((5, 5)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 4, 4].item() == pytest.approx(2.0)
+ assert out[0, 0, 4, 9].item() == pytest.approx(1.0)
+
+ def test_nms_5x5_matches_3x3_on_well_separated_peaks(self, device):
+ # When peaks are far apart, 3x3 and 5x5 NMS should agree.
+ inp = torch.zeros(1, 1, 30, 30, device=device)
+ inp[0, 0, 5, 5] = 3.0
+ inp[0, 0, 20, 20] = 2.0
+ nms3 = kornia.geometry.subpix.NonMaximaSuppression2d((3, 3)).to(device)
+ nms5 = kornia.geometry.subpix.NonMaximaSuppression2d((5, 5)).to(device)
+ out3 = nms3(inp)
+ out5 = nms5(inp)
+ # Both NMS variants should detect the same two peaks (peaks are far from each other).
+ assert (out3 > 0).equal(out5 > 0)
+
+ def test_nms_7x7_single_peak(self, device):
+ # A single isolated peak should be preserved.
+ inp = torch.zeros(1, 1, 20, 20, device=device)
+ inp[0, 0, 10, 10] = 1.0
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((7, 7)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 10, 10].item() == pytest.approx(1.0)
+ assert out.sum().item() == pytest.approx(1.0)
+
+ def test_nms_7x7_suppress_close_neighbor(self, device):
+ # 7x7 kernel has radius 3 (checks Β±3 pixels). Two peaks separated by exactly 3 pixels
+ # are inside each other's window; only the higher one survives.
+ inp = torch.zeros(1, 1, 25, 25, device=device)
+ inp[0, 0, 10, 10] = 2.0
+ inp[0, 0, 10, 13] = 1.0 # distance 3 β€” inside the 7x7 neighbourhood
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((7, 7)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 10, 10].item() == pytest.approx(2.0)
+ assert out[0, 0, 10, 13].item() == pytest.approx(0.0)
+
+ def test_nms_7x7_keep_far_peaks(self, device):
+ # Two peaks separated by 7 pixels (outside 7x7 Β±3 window): both survive.
+ inp = torch.zeros(1, 1, 30, 30, device=device)
+ inp[0, 0, 5, 5] = 2.0
+ inp[0, 0, 5, 12] = 1.0 # distance 7
+ nms = kornia.geometry.subpix.NonMaximaSuppression2d((7, 7)).to(device)
+ out = nms(inp)
+ assert out[0, 0, 5, 5].item() == pytest.approx(2.0)
+ assert out[0, 0, 5, 12].item() == pytest.approx(1.0)
+
+ def test_gradcheck_5x5(self, device):
+ img = torch.rand(1, 2, 7, 7, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms2d, (img, (5, 5)), nondet_tol=1e-4)
+
+ def test_gradcheck_7x7(self, device):
+ img = torch.rand(1, 2, 9, 9, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.geometry.subpix.nms2d, (img, (7, 7)), nondet_tol=1e-4)
+
def test_nms(self, device):
inp = torch.tensor(
[
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index dc0879a57..60652e190 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -821,13 +821,9 @@ class TestBbox3D(BaseTester):
class TestTransformBoxes3D(BaseTester):
def test_transform_boxes(self, device, dtype):
- # Define boxes in XYZXYZ format for simplicity.
- boxes_xyzxyz = torch.tensor(
- [[139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185]], device=device, dtype=dtype
- )
- expected_boxes_xyzxyz = torch.tensor(
- [[372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37]], device=device, dtype=dtype
- )
+ # Define boxes in XYZXYZ format with integer coordinates (TF32-safe on CUDA).
+ boxes_xyzxyz = torch.tensor([[140, 104, 284, 398, 412, 454]], device=device, dtype=dtype)
+ expected_boxes_xyzxyz = torch.tensor([[372, 104, 569, 116, 412, 908]], device=device, dtype=dtype)
boxes = Boxes3D.from_tensor(boxes_xyzxyz)
expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)
@@ -844,13 +840,9 @@ class TestTransformBoxes3D(BaseTester):
assert transformed_boxes is not boxes
def test_transform_boxes_(self, device, dtype):
- # Define boxes in XYZXYZ format for simplicity.
- boxes_xyzxyz = torch.tensor(
- [[139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185]], device=device, dtype=dtype
- )
- expected_boxes_xyzxyz = torch.tensor(
- [[372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37]], device=device, dtype=dtype
- )
+ # Define boxes in XYZXYZ format with integer coordinates (TF32-safe on CUDA).
+ boxes_xyzxyz = torch.tensor([[140, 104, 284, 398, 412, 454]], device=device, dtype=dtype)
+ expected_boxes_xyzxyz = torch.tensor([[372, 104, 569, 116, 412, 908]], device=device, dtype=dtype)
boxes = Boxes3D.from_tensor(boxes_xyzxyz)
expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)
@@ -867,13 +859,13 @@ class TestTransformBoxes3D(BaseTester):
assert transformed_boxes is boxes
def test_transform_multiple_boxes(self, device, dtype):
- # Define boxes in XYZXYZ format for simplicity.
+ # Define boxes in XYZXYZ format with integer coordinates (TF32-safe on CUDA).
boxes_xyzxyz = torch.tensor(
[
- [139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185],
- [1.0240, 80.5547, 469.50, 513.0000, 513.0000, 513.0],
- [165.2053, 262.1440, 42.98, 511.6347, 509.9280, 785.443],
- [119.8080, 144.2067, 234.21, 258.0240, 411.1292, 387.14],
+ [140, 104, 284, 398, 412, 454],
+ [2, 81, 470, 512, 513, 513],
+ [166, 263, 43, 512, 510, 786],
+ [120, 145, 235, 258, 412, 387],
],
device=device,
dtype=dtype,
@@ -882,16 +874,16 @@ class TestTransformBoxes3D(BaseTester):
expected_boxes_xyzxyz = torch.tensor(
[
[
- [372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37],
- [510.9760, 80.5547, 940.0, 1.0000, 513.0000, 1026.0],
- [346.7947, 262.1440, 86.96, 2.3653, 509.9280, 1570.886],
- [392.1920, 144.2067, 469.42, 255.9760, 411.1292, 774.28],
+ [372, 104, 569, 116, 412, 908],
+ [510, 81, 941, 2, 513, 1026],
+ [346, 263, 87, 2, 510, 1572],
+ [392, 145, 471, 256, 412, 774],
],
[
- [139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185],
- [1.0240, 80.5547, 469.50, 513.0000, 513.0000, 513.0],
- [165.2053, 262.1440, 42.98, 511.6347, 509.9280, 785.443],
- [119.8080, 144.2067, 234.21, 258.0240, 411.1292, 387.14],
+ [140, 104, 284, 398, 412, 454],
+ [2, 81, 470, 512, 513, 513],
+ [166, 263, 43, 512, 510, 786],
+ [120, 145, 235, 258, 412, 387],
],
],
device=device,
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index fa048004b..92ae7d81c 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -241,6 +241,42 @@ class TestRotationMatrixToQuaternion(BaseTester):
torch.set_printoptions(precision=10)
self.assert_close(quaternion_true, quaternion, atol=atol, rtol=rtol)
+ def test_cond1_180_rot_x(self, device, dtype, atol, rtol):
+ # 180Β° rotation around X: trace < 0, m00 > m11 and m00 > m22 β†’ activates cond_1 branch.
+ # R_x(Ο€) = diag(1, -1, -1); expected quaternion (w,x,y,z) = (0, 1, 0, 0).
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, eps=eps)
+ self.assert_close(quaternion.abs(), expected.abs(), atol=atol, rtol=rtol)
+ # Round-trip: convert back and verify the rotation matrix is recovered.
+ mat_back = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+ self.assert_close(mat_back, matrix, atol=atol, rtol=rtol)
+
+ def test_cond2_180_rot_y(self, device, dtype, atol, rtol):
+ # 180Β° rotation around Y: trace < 0, m11 > m22 and m00 not dominant β†’ activates cond_2 branch.
+ # R_y(Ο€) = diag(-1, 1, -1); expected quaternion (w,x,y,z) = (0, 0, 1, 0).
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor(((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ quaternion = kornia.geometry.conversions.rotation_matrix_to_quaternion(matrix, eps=eps)
+ self.assert_close(quaternion.abs(), expected.abs(), atol=atol, rtol=rtol)
+ mat_back = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternion)
+ self.assert_close(mat_back, matrix, atol=atol, rtol=rtol)
+
+ def test_all_four_branches_in_batch(self, device, dtype, atol, rtol):
+ # Batch of 4 rotation matrices that each activate a different internal branch.
+ # Verify consistency via round-trip: R β†’ q β†’ R must recover the original rotation.
+ eps = torch.finfo(dtype).eps
+ identity = torch.eye(3, device=device, dtype=dtype) # trace > 0 β†’ trace_positive_cond
+ rot_x_180 = torch.tensor(((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
+ rot_y_180 = torch.tensor(((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
+ rot_z_180 = torch.tensor(((-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
+ batch = torch.stack([identity, rot_x_180, rot_y_180, rot_z_180]) # (4, 3, 3)
+ quaternions = kornia.geometry.conversions.rotation_matrix_to_quaternion(batch, eps=eps)
+ mats_back = kornia.geometry.conversions.quaternion_to_rotation_matrix(quaternions)
+ self.assert_close(mats_back, batch, atol=atol, rtol=rtol)
+
def test_gradcheck(self, device):
dtype = torch.float64
eps = torch.finfo(dtype).eps
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index 90cf53626..2b7058f81 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -232,6 +232,8 @@ class TestFindHomographyDLT(BaseTester):
if dtype not in (torch.float32, torch.float64):
rtol = 3e-3
atol = 1e-3
+ elif device.type == "cuda" and dtype == torch.float32:
+ atol = 2e-3
self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=rtol, atol=atol)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@@ -252,6 +254,8 @@ class TestFindHomographyDLT(BaseTester):
if dtype not in (torch.float32, torch.float64):
rtol = 3e-3
atol = 1e-3
+ elif device.type == "cuda" and dtype == torch.float32:
+ atol = 2e-3
self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=rtol, atol=atol)
@pytest.mark.grad()
@@ -367,6 +371,8 @@ class TestFindHomographyFromLinesDLT(BaseTester):
if dtype not in (torch.float32, torch.float64):
rtol = 5e-3
atol = 1e-3
+ elif device.type == "cuda" and dtype == torch.float32:
+ atol = 5e-3
self.assert_close(
kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=rtol, atol=atol
)
@@ -392,6 +398,8 @@ class TestFindHomographyFromLinesDLT(BaseTester):
if dtype not in (torch.float32, torch.float64):
rtol = 5e-3
atol = 1e-3
+ elif device.type == "cuda" and dtype == torch.float32:
+ atol = 5e-3
self.assert_close(
kornia.geometry.transform_points(dst_homo_src, points_src_st), points_dst_st, rtol=rtol, atol=atol
)
@@ -444,7 +452,8 @@ class TestFindHomographyDLTIter(BaseTester):
# compute transform from source to target
dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)
- self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ atol = 2e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ self.assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=atol)
@pytest.mark.grad()
def test_gradcheck(self, device):
diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.py
new file mode 100644
index 000000000..3ccad02c2
--- /dev/null
+++ b/tests/geometry/test_keypoints.py
@@ -0,0 +1,365 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.geometry.keypoints import Keypoints, Keypoints3D, VideoKeypoints
+
+from testing.base import BaseTester
+
+
+class TestKeypoints(BaseTester):
+ def test_smoke(self, device, dtype):
+ data = torch.rand(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ assert isinstance(kp, Keypoints)
+
+ def test_cardinality(self, device, dtype):
+ data = torch.rand(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ assert kp.shape == (10, 2)
+
+ def test_batched(self, device, dtype):
+ data = torch.rand(3, 10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ assert kp.shape == (3, 10, 2)
+ assert kp._is_batched is True
+
+ def test_unbatched(self, device, dtype):
+ data = torch.rand(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ assert kp._is_batched is False
+
+ def test_device_dtype(self, device, dtype):
+ data = torch.rand(5, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ assert kp.device == device
+ assert kp.dtype == dtype
+
+ def test_from_tensor(self, device, dtype):
+ data = torch.rand(5, 2, device=device, dtype=dtype)
+ kp = Keypoints.from_tensor(data)
+ assert kp.shape == data.shape
+
+ def test_to_tensor(self, device, dtype):
+ data = torch.rand(5, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ out = kp.to_tensor()
+ assert out.shape == data.shape
+ self.assert_close(out, data)
+
+ def test_clone(self, device, dtype):
+ data = torch.rand(5, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ kp2 = kp.clone()
+ self.assert_close(kp.data, kp2.data)
+ kp2._data[0, 0] = 999.0
+ assert not torch.allclose(kp.data, kp2.data)
+
+ def test_getitem(self, device, dtype):
+ data = torch.rand(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ kp2 = kp[:5]
+ assert kp2.shape == (5, 2)
+
+ def test_setitem(self, device, dtype):
+ data = torch.rand(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ new_data = torch.zeros(5, 2, device=device, dtype=dtype)
+ new_kp = Keypoints(new_data)
+ kp[:5] = new_kp
+ self.assert_close(kp.data[:5], new_data)
+
+ def test_transform_keypoints(self, device, dtype):
+ # Use batched keypoints (B, N, 2) with batched M (B, 3, 3)
+ data = torch.tensor([[[1.0, 0.0], [0.0, 1.0]]], device=device, dtype=dtype) # (1, 2, 2)
+ kp = Keypoints(data)
+ M = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # (1, 3, 3)
+ M[0, 0, 2] = 2.0 # translate x by 2
+ M[0, 1, 2] = 3.0 # translate y by 3
+ kp_t = kp.transform_keypoints(M)
+ expected = torch.tensor([[[3.0, 3.0], [2.0, 4.0]]], device=device, dtype=dtype)
+ self.assert_close(kp_t.data, expected)
+
+ def test_transform_keypoints_inplace(self, device, dtype):
+ data = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype) # (1, 1, 2)
+ kp = Keypoints(data)
+ M = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # (1, 3, 3)
+ M[0, 0, 2] = 1.0
+ kp.transform_keypoints_(M)
+ expected = torch.tensor([[[2.0, 0.0]]], device=device, dtype=dtype)
+ self.assert_close(kp.data, expected)
+
+ def test_transform_keypoints_batched(self, device, dtype):
+ data = torch.ones(2, 4, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ M = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand(2, -1, -1).clone()
+ M[:, 0, 2] = 5.0
+ kp_t = kp.transform_keypoints(M)
+ assert kp_t.shape == (2, 4, 2)
+ self.assert_close(kp_t.data[..., 0], torch.full((2, 4), 6.0, device=device, dtype=dtype))
+
+ def test_pad(self, device, dtype):
+ data = torch.zeros(2, 4, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ padding = torch.tensor([[1.0, 0.0, 2.0, 0.0], [0.0, 0.0, 3.0, 0.0]], device=device, dtype=dtype)
+ kp.pad(padding)
+ # x += left_pad, y += top_pad
+ self.assert_close(kp.data[0, :, 0], torch.full((4,), 1.0, device=device, dtype=dtype))
+ self.assert_close(kp.data[1, :, 0], torch.zeros(4, device=device, dtype=dtype))
+ self.assert_close(kp.data[0, :, 1], torch.full((4,), 2.0, device=device, dtype=dtype))
+
+ def test_unpad(self, device, dtype):
+ data = torch.ones(2, 4, 2, device=device, dtype=dtype) * 5.0
+ kp = Keypoints(data)
+ padding = torch.tensor([[1.0, 0.0, 2.0, 0.0], [0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ kp.unpad(padding)
+ self.assert_close(kp.data[0, :, 0], torch.full((4,), 4.0, device=device, dtype=dtype))
+ self.assert_close(kp.data[0, :, 1], torch.full((4,), 3.0, device=device, dtype=dtype))
+
+ def test_index_put(self, device, dtype):
+ data = torch.zeros(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ new_vals = torch.ones(3, 2, device=device, dtype=dtype)
+ idx = (torch.tensor([0, 1, 2], device=device),)
+ kp2 = kp.index_put(idx, new_vals)
+ self.assert_close(kp2.data[:3], new_vals)
+
+ def test_index_put_inplace(self, device, dtype):
+ data = torch.zeros(10, 2, device=device, dtype=dtype)
+ kp = Keypoints(data)
+ new_vals = torch.ones(3, 2, device=device, dtype=dtype)
+ idx = (torch.tensor([0, 1, 2], device=device),)
+ kp.index_put(idx, new_vals, inplace=True)
+ self.assert_close(kp.data[:3], new_vals)
+
+ def test_type(self, device, dtype):
+ data = torch.rand(5, 2, device=device, dtype=torch.float32)
+ kp = Keypoints(data)
+ kp.type(torch.float64)
+ assert kp.dtype == torch.float64
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError):
+ Keypoints("not a tensor")
+
+ with pytest.raises(ValueError):
+ Keypoints(torch.tensor([1, 2, 3], dtype=torch.int32))
+
+ with pytest.raises(ValueError):
+ Keypoints(torch.rand(3, 3, device=device, dtype=dtype))
+
+ with pytest.raises(ValueError):
+ Keypoints(torch.rand(3, 4, 2, 2, device=device, dtype=dtype))
+
+ def test_transform_exception(self, device, dtype):
+ kp = Keypoints(torch.rand(5, 2, device=device, dtype=dtype))
+ with pytest.raises(ValueError):
+ kp.transform_keypoints(torch.eye(4, device=device, dtype=dtype))
+
+ def test_pad_exception(self, device, dtype):
+ kp = Keypoints(torch.rand(2, 4, 2, device=device, dtype=dtype))
+ with pytest.raises(RuntimeError):
+ kp.pad(torch.zeros(2, 3, device=device, dtype=dtype))
+
+ def test_int_input_raises_by_default(self, device, dtype):
+ with pytest.raises(ValueError):
+ Keypoints(torch.ones(5, 2, device=device, dtype=torch.int32))
+
+ def test_int_input_converted_when_not_raising(self, device, dtype):
+ data = torch.ones(5, 2, device=device, dtype=torch.int32)
+ kp = Keypoints(data, raise_if_not_floating_point=False)
+ assert kp.dtype == torch.float32
+
+ def test_gradcheck(self, device):
+ data = torch.rand(1, 5, 2, device=device, dtype=torch.float64, requires_grad=True)
+ M = torch.eye(3, device=device, dtype=torch.float64).unsqueeze(0)
+ M[0, 0, 2] = 1.0
+
+ def fn(x):
+ return Keypoints(x).transform_keypoints(M).data
+
+ self.gradcheck(fn, (data,))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ data = torch.rand(1, 5, 2, device=device, dtype=dtype)
+ M = torch.eye(3, device=device, dtype=dtype).unsqueeze(0)
+
+ def fn(x):
+ return Keypoints(x).transform_keypoints(M).data
+
+ op = torch_optimizer(fn)
+ self.assert_close(op(data), fn(data))
+
+ def test_smoke_jit(self, device, dtype):
+ pass # Keypoints is not a nn.Module, jit test not applicable
+
+ def test_module(self, device, dtype):
+ pass # Keypoints is not a nn.Module
+
+
+class TestVideoKeypoints(BaseTester):
+ def test_smoke(self, device, dtype):
+ data = torch.rand(2, 5, 10, 2, device=device, dtype=dtype)
+ vkp = VideoKeypoints.from_tensor(data)
+ assert isinstance(vkp, VideoKeypoints)
+
+ def test_cardinality(self, device, dtype):
+ B, T, N = 2, 5, 10
+ data = torch.rand(B, T, N, 2, device=device, dtype=dtype)
+ vkp = VideoKeypoints.from_tensor(data)
+ assert vkp.temporal_channel_size == T
+ out = vkp.to_tensor()
+ assert out.shape == (B, T, N, 2)
+
+ def test_to_tensor_roundtrip(self, device, dtype):
+ data = torch.rand(2, 4, 8, 2, device=device, dtype=dtype)
+ vkp = VideoKeypoints.from_tensor(data)
+ out = vkp.to_tensor()
+ self.assert_close(out, data)
+
+ def test_clone(self, device, dtype):
+ data = torch.rand(2, 4, 8, 2, device=device, dtype=dtype)
+ vkp = VideoKeypoints.from_tensor(data)
+ vkp2 = vkp.clone()
+ self.assert_close(vkp.to_tensor(), vkp2.to_tensor())
+ assert vkp2.temporal_channel_size == vkp.temporal_channel_size
+
+ def test_transform_keypoints(self, device, dtype):
+ B, T, N = 1, 3, 5
+ data = torch.ones(B, T, N, 2, device=device, dtype=dtype)
+ vkp = VideoKeypoints.from_tensor(data)
+ # After from_tensor, internal shape is (B*T, N, 2); need M with batch size B*T or 1
+ M = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # (1, 3, 3) broadcasts
+ out = vkp.transform_keypoints(M)
+ assert isinstance(out, VideoKeypoints)
+ assert out.temporal_channel_size == T
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(ValueError):
+ VideoKeypoints.from_tensor(torch.rand(5, 2, device=device, dtype=dtype))
+
+ with pytest.raises(ValueError):
+ VideoKeypoints.from_tensor(torch.rand(2, 5, 10, 3, device=device, dtype=dtype))
+
+ def test_gradcheck(self, device):
+ pass # VideoKeypoints ops not differentiable through from_tensor reshape
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ pass # VideoKeypoints uses reshape; not straightforward to dynamo
+
+ def test_smoke_jit(self, device, dtype):
+ pass
+
+ def test_module(self, device, dtype):
+ pass
+
+ def test_exception_in_base(self, device, dtype):
+ pass
+
+
+class TestKeypoints3D(BaseTester):
+ def test_smoke(self, device, dtype):
+ data = torch.rand(10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ assert isinstance(kp, Keypoints3D)
+
+ def test_cardinality(self, device, dtype):
+ data = torch.rand(10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ assert kp.shape == (10, 3)
+
+ def test_batched(self, device, dtype):
+ data = torch.rand(3, 10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ assert kp.shape == (3, 10, 3)
+ assert kp._is_batched is True
+
+ def test_unbatched(self, device, dtype):
+ data = torch.rand(10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ assert kp._is_batched is False
+
+ def test_from_tensor(self, device, dtype):
+ data = torch.rand(5, 3, device=device, dtype=dtype)
+ kp = Keypoints3D.from_tensor(data)
+ assert kp.shape == data.shape
+
+ def test_to_tensor(self, device, dtype):
+ data = torch.rand(5, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ out = kp.to_tensor()
+ self.assert_close(out, data)
+
+ def test_clone(self, device, dtype):
+ data = torch.rand(5, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ kp2 = kp.clone()
+ self.assert_close(kp.data, kp2.data)
+ kp2._data[0, 0] = 999.0
+ assert not torch.allclose(kp.data, kp2.data)
+
+ def test_getitem(self, device, dtype):
+ data = torch.rand(10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ kp2 = kp[:5]
+ assert kp2.shape == (5, 3)
+
+ def test_setitem(self, device, dtype):
+ data = torch.rand(10, 3, device=device, dtype=dtype)
+ kp = Keypoints3D(data)
+ new_data = torch.zeros(5, 3, device=device, dtype=dtype)
+ new_kp = Keypoints3D(new_data)
+ kp[:5] = new_kp
+ self.assert_close(kp.data[:5], new_data)
+
+ def test_not_implemented(self, device, dtype):
+ kp = Keypoints3D(torch.rand(5, 3, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError):
+ kp.pad(torch.zeros(1, 6, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError):
+ kp.unpad(torch.zeros(1, 6, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError):
+ kp.transform_keypoints(torch.eye(4, device=device, dtype=dtype))
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError):
+ Keypoints3D("not a tensor")
+
+ with pytest.raises(ValueError):
+ Keypoints3D(torch.tensor([1, 2, 3], dtype=torch.int32))
+
+ with pytest.raises(ValueError):
+ Keypoints3D(torch.rand(3, 2, device=device, dtype=dtype))
+
+ def test_int_input_converted_when_not_raising(self, device, dtype):
+ data = torch.ones(5, 3, device=device, dtype=torch.int32)
+ kp = Keypoints3D(data, raise_if_not_floating_point=False)
+ assert kp.data.dtype == torch.float32
+
+ def test_gradcheck(self, device):
+ pass # Keypoints3D transform ops are NotImplemented
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ pass
+
+ def test_smoke_jit(self, device, dtype):
+ pass
+
+ def test_module(self, device, dtype):
+ pass
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index 096039ada..0f535356b 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -46,7 +46,8 @@ class TestTransformPoints(BaseTester):
points_dst_to_src = kgl.transform_points(src_homo_dst, points_dst)
# projected should be equal as initial
- self.assert_close(points_src, points_dst_to_src, atol=1e-4, rtol=1e-4)
+ atol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ self.assert_close(points_src, points_dst_to_src, atol=atol, rtol=1e-4)
def test_gradcheck(self, device):
# generate input data
diff --git a/tests/geometry/test_ray.py b/tests/geometry/test_ray.py
new file mode 100644
index 000000000..a7762173e
--- /dev/null
+++ b/tests/geometry/test_ray.py
@@ -0,0 +1,41 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import torch
+
+from kornia.geometry.line import ParametrizedLine
+from kornia.geometry.ray import Ray
+
+
+def test_ray_is_parametrized_line():
+ assert Ray is ParametrizedLine
+
+
+def test_ray_smoke():
+ origin = torch.zeros(3)
+ direction = torch.tensor([0.0, 0.0, 1.0])
+ ray = Ray(origin, direction)
+ assert isinstance(ray, ParametrizedLine)
+
+
+def test_ray_point_at():
+ origin = torch.zeros(3)
+ direction = torch.tensor([1.0, 0.0, 0.0])
+ ray = Ray(origin, direction)
+ pt = ray.point_at(2.0)
+ expected = torch.tensor([2.0, 0.0, 0.0])
+ assert torch.allclose(pt, expected)
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index fbd7e7ced..79fc26679 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -397,17 +397,18 @@ class TestHomographyWarper3D(BaseTester):
dst_homo_src = eye_like(4, norm.expand(batch_size, -1, -1, -1))
- self.assert_close(norm, res, rtol=1e-4, atol=1e-4)
+ _atol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ self.assert_close(norm, res, rtol=1e-4, atol=_atol)
norm_homo = kornia.geometry.conversions.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(
device=device, dtype=dtype
)
- self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+ self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=_atol)
norm_homo = kornia.geometry.conversions.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(
device=device, dtype=dtype
)
- self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+ self.assert_close(norm_homo, dst_homo_src, rtol=1e-4, atol=_atol)
# change output scale
norm_homo = kornia.geometry.conversions.normalize_homography3d(
@@ -419,7 +420,8 @@ class TestHomographyWarper3D(BaseTester):
dtype=dtype,
).repeat(batch_size, 1, 1)
- self.assert_close(norm_homo, res, rtol=1e-4, atol=1e-4)
+ atol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
+ self.assert_close(norm_homo, res, rtol=1e-4, atol=atol)
@pytest.mark.parametrize("batch_size", [1, 3])
def test_normalize_homography_general(self, batch_size, device, dtype):
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index 93cb01d18..9fc8d7f89 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -48,37 +48,42 @@ class TestMutualInformationLoss(BaseTester):
for radius in [1 / 2, 1, 2, 3]:
# relative MI, expect 1
- assert torch.allclose(self.relative_mi(img_1, img_2, window_radius=radius), torch.ones(1).to(dtype)), (
- "Wrong MI behaviour, correlated case."
- )
+ assert torch.allclose(
+ self.relative_mi(img_1, img_2, window_radius=radius),
+ torch.ones(1, device=device, dtype=dtype),
+ ), "Wrong MI behaviour, correlated case."
# relative MI, expect 0
# NOTE: mutual_information_loss is a finite-sample, histogram-based estimator applied to random data.
# For independent variables the theoretical value is 0, but sampling noise and binning effects across
# radii introduce noticeable variance, so we use a slightly looser atol here for test robustness.
assert torch.allclose(
- self.relative_mi(img_1, img_3, window_radius=radius), torch.zeros(1).to(dtype), atol=0.2
+ self.relative_mi(img_1, img_3, window_radius=radius),
+ torch.zeros(1, device=device, dtype=dtype),
+ atol=0.2,
), "Wrong MI behaviour, uncorrelated case."
assert torch.allclose(
- self.relative_mi(img_2, img_3, window_radius=radius), torch.zeros(1).to(dtype), atol=0.2
+ self.relative_mi(img_2, img_3, window_radius=radius),
+ torch.zeros(1, device=device, dtype=dtype),
+ atol=0.2,
), "Wrong MI behaviour, uncorrelated case."
# NMI, expect -2
assert torch.allclose(
normalized_mutual_information_loss(img_1, img_2, window_radius=radius, num_bins=num_bins),
- -2 * torch.ones(1).to(dtype),
+ -2 * torch.ones(1, device=device, dtype=dtype),
atol=0.2 * radius + 0.15,
), "Wrong NMI behaviour, correlated case."
# NMI, expect -1
assert torch.allclose(
normalized_mutual_information_loss(img_1, img_3, window_radius=radius, num_bins=num_bins),
- -torch.ones(1).to(dtype),
+ -torch.ones(1, device=device, dtype=dtype),
atol=0.1,
), "Wrong NMI behaviour, uncorrelated case."
assert torch.allclose(
normalized_mutual_information_loss(img_2, img_3, window_radius=radius, num_bins=num_bins),
- -torch.ones(1).to(dtype),
+ -torch.ones(1, device=device, dtype=dtype),
atol=0.1,
), "Wrong NMI behaviour, uncorrelated case."
diff --git a/tests/models/test_naflex.py b/tests/models/test_naflex.py
index 687ef0702..8ccd78d30 100644
--- a/tests/models/test_naflex.py
+++ b/tests/models/test_naflex.py
@@ -50,6 +50,7 @@ class TestNaFlex(BaseTester):
def test_smoke(self, model: NaFlex, device: torch.device, dtype: torch.dtype) -> None:
"""Test basic forward pass with standard input."""
+ model = model.to(device)
input_data = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)
out = model(input_data)
assert isinstance(out, Tensor)
@@ -60,6 +61,7 @@ class TestNaFlex(BaseTester):
For 224x320 input with 16x16 patches, expect 14x20=280 patches.
"""
+ model = model.to(device)
input_data = torch.randn(1, 3, 224, 320, device=device, dtype=dtype)
out = model(input_data)
assert out.shape[0] == 1
@@ -90,7 +92,7 @@ class TestNaFlex(BaseTester):
return torch.randn(B, 768, h_out, w_out, dtype=x.dtype, device=x.device)
position_embedding = torch.randn(196, 768)
- model = NaFlex(mock_patch_embedding_dynamic, position_embedding)
+ model = NaFlex(mock_patch_embedding_dynamic, position_embedding).to(device)
input_448 = torch.randn(1, 3, 448, 448, device=device, dtype=dtype)
out = model(input_448)
assert out.shape == (1, 784, 768)