Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Speed up CI test execution without reducing coverage (#4169)

Dmytro Mishkin056ccd64d3ce
diff --git a/.github/actions/coverage/action.yml b/.github/actions/coverage/action.yml
index 026974e41..010ff259c 100644
--- a/.github/actions/coverage/action.yml
+++ b/.github/actions/coverage/action.yml
@@ -51,7 +51,7 @@ runs:
shell: bash
run: |
pixi run -e ${{ steps.pixi-env.outputs.name }} uv run coverage erase
- pixi run -e ${{ steps.pixi-env.outputs.name }} uv run coverage run --data-file=${{ inputs.coverage-artifact }} -m pytest -v ./tests/ --device=${{ inputs.pytorch-device }} --dtype=${{ inputs.pytorch-dtype }} ${{ inputs.pytest-extra }}
+ pixi run -e ${{ steps.pixi-env.outputs.name }} uv run coverage run --data-file=${{ inputs.coverage-artifact }} -m pytest ./tests/ --device=${{ inputs.pytorch-device }} --dtype=${{ inputs.pytorch-dtype }} ${{ inputs.pytest-extra }}
- name: Upload coverage results
uses: actions/upload-artifact@v4
diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml
index c1cb2754b..45260e137 100644
--- a/.github/workflows/coverage.yml
+++ b/.github/workflows/coverage.yml
@@ -116,6 +116,9 @@ jobs:
restore-keys: ${{ inputs.cache-restore-keys }}
- uses: ./.github/actions/coverage
+ env:
+ MKL_NUM_THREADS: "1"
+ OMP_NUM_THREADS: "1"
with:
python-version: ${{ inputs.python-version }}
pytorch-dtype: ${{ matrix.pytorch-dtype }}
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index bc2f3b3f9..4636908d3 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -118,10 +118,14 @@ jobs:
echo "DNNL_MAX_CPU_ISA=AVX2" >> $GITHUB_ENV
- name: Run tests
+ shell: bash
env:
KORNIA_TEST_DEVICE: cpu
KORNIA_TEST_DTYPE: ${{ inputs.pytorch-dtype }}
KORNIA_TEST_RUNSLOW: ${{ inputs.runslow }}
KORNIA_TEST_OPTIMIZER: ${{ inputs.optimizer }}
+ KORNIA_CI_PYTEST_VERBOSITY: ${{ runner.os == 'Windows' && '-v' || '' }}
+ MKL_NUM_THREADS: "1"
+ OMP_NUM_THREADS: "1"
UV_NO_SYNC: "1"
- run: pixi run -e ${{ steps.pixi-env.outputs.name }} test ${{ inputs.pytest-extra }}
+ run: pixi run -e ${{ steps.pixi-env.outputs.name }} test $KORNIA_CI_PYTEST_VERBOSITY ${{ inputs.pytest-extra }}
diff --git a/TESTING.md b/TESTING.md
index f31d10cc1..88d8fc7ee 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -36,6 +36,7 @@ pixi run test-quick
| `--tf32` | `KORNIA_TEST_TF32` | off | Enable TF32 mode (see below) |
| `--optimizer` | `KORNIA_TEST_OPTIMIZER` | CLI: `inductor`; env: unset | Select the backend. Only setting the environment variable enables dynamo/compile collection; the CLI option alone does not. |
| `--isolate-half-precision` | `KORNIA_TEST_ISOLATE_HALF` | off | Run float16/bfloat16 CUDA tests each in a fresh `subprocess.run` process (no shared CUDA state) |
+| `--run-device-agnostic` | `KORNIA_TEST_RUN_DEVICE_AGNOSTIC` | off | Run `@pytest.mark.device_agnostic` tests even when CPU is not in the device matrix |
## Test Structure
@@ -60,6 +61,7 @@ The `device` and `dtype` fixtures are injected automatically from the CLI option
| Marker | Meaning |
|---|---|
+| `@pytest.mark.device_agnostic` | Test runs once in a CPU-containing matrix because its logic does not use the selected accelerator. An accelerator-only run deselects it and says so on a line of its own at the start of the run, because the deselected set includes the ONNX and `torch.export` suites; `--run-device-agnostic` forces it back on |
| `@pytest.mark.slow` | Long-running test; skipped unless `--runslow` is passed |
| `@pytest.mark.tf32` | Known to fail under TF32 (see section below); xfail unless `--tf32` |
diff --git a/conftest.py b/conftest.py
index 977ce5989..08bd8f400 100644
--- a/conftest.py
+++ b/conftest.py
@@ -166,6 +166,29 @@ def pytest_generate_tests(metafunc) -> None:
def pytest_collection_modifyitems(config, items):
"""Collect test options."""
+ # Device-agnostic tests exercise CPU-only code regardless of the selected test device. Run
+ # them once whenever CPU is part of the matrix instead of repeating the same work in every
+ # accelerator job. --run-device-agnostic forces them back on, so an accelerator-only run can
+ # still cover the whole suite when that is what the caller wants.
+ selected_devices = _parse_test_option(config, "--device", TEST_DEVICES)
+ if "cpu" not in selected_devices and not config.getoption("--run-device-agnostic"):
+ device_agnostic_items = [item for item in items if item.get_closest_marker("device_agnostic") is not None]
+ if device_agnostic_items:
+ config.hook.pytest_deselected(items=device_agnostic_items)
+ device_agnostic_ids = {id(item) for item in device_agnostic_items}
+ items[:] = [item for item in items if id(item) not in device_agnostic_ids]
+ # Say so out loud. The deselected set is not incidental -- it holds the ONNX and
+ # torch.export suites -- and a bare "N deselected" in the status line is easy to read
+ # as noise, so an accelerator-only run should not look like a full-suite run.
+ reporter = config.pluginmanager.get_plugin("terminalreporter")
+ if reporter is not None:
+ reporter.write_line(
+ f"deselected {len(device_agnostic_items)} device_agnostic test(s): they exercise "
+ "CPU-only code and CPU is not in --device. Pass --run-device-agnostic "
+ "(or KORNIA_TEST_RUN_DEVICE_AGNOSTIC=true) to run them here too.",
+ yellow=True,
+ )
+
# Deselect dynamo/compile tests when no optimizer is specified
# Check environment variable directly (not config option which has default "inductor")
optimizer_env = os.environ.get("KORNIA_TEST_OPTIMIZER", "").strip()
@@ -287,6 +310,17 @@ def pytest_addoption(parser):
"(env: KORNIA_TEST_ISOLATE_HALF)"
),
)
+ parser.addoption(
+ "--run-device-agnostic",
+ action="store_true",
+ default=os.environ.get("KORNIA_TEST_RUN_DEVICE_AGNOSTIC", "false").lower() == "true",
+ help=(
+ "Run tests marked device_agnostic even when CPU is not part of the device matrix. "
+ "They exercise CPU-only code, so an accelerator-only run deselects them by default "
+ "to avoid repeating work the CPU job already did; pass this to run the whole suite "
+ "on one device anyway. (env: KORNIA_TEST_RUN_DEVICE_AGNOSTIC)"
+ ),
+ )
def _setup_torch_compile() -> None:
@@ -499,6 +533,8 @@ def pytest_runtest_protocol(item, nextitem):
"-m",
"pytest",
item.nodeid,
+ "-o",
+ "addopts=",
"--no-header",
"--tb=short",
"-q",
@@ -506,6 +542,11 @@ def pytest_runtest_protocol(item, nextitem):
f"--device={device_name}",
f"--dtype={dtype_name}",
]
+ # The parent already decided this node runs, so the child must not re-apply a selection rule
+ # and collect nothing: it is handed a single --device=cuda, under which the device_agnostic
+ # deselection would fire. Exit code 5 is reported back as an ordinary skip, which would hide
+ # a test that never executed.
+ cmd.append("--run-device-agnostic")
if item.config.getoption("--runslow"):
cmd.append("--runslow")
if item.config.getoption("--tf32"):
@@ -515,6 +556,9 @@ def pytest_runtest_protocol(item, nextitem):
cmd.append(f"--optimizer={optimizer_backend}")
env = {**os.environ, "KORNIA_TEST_IN_SUBPROCESS": "1"}
+ # `-o addopts=` above only clears the ini value; the environment form is inherited and would
+ # push the child to -qq, where the summary line the parser relies on is no longer printed.
+ env.pop("PYTEST_ADDOPTS", None)
t0 = time.monotonic()
proc = subprocess.run( # noqa: S603
cmd, capture_output=True, text=True, cwd=str(item.config.rootdir), env=env, check=False
diff --git a/pixi.toml b/pixi.toml
index c818216e0..342b57fa1 100644
--- a/pixi.toml
+++ b/pixi.toml
@@ -38,20 +38,20 @@ py313 = { features = ["py313"], solve-group = "py313" }
install = { cmd = "uv sync --extra dev", description = "Install dev dependencies" }
install-docs = { cmd = "uv sync --extra dev --extra docs", description = "Install dev + docs dependencies" }
# Tests - use env vars (KORNIA_TEST_DEVICE, KORNIA_TEST_DTYPE, KORNIA_TEST_RUNSLOW)
-test = { cmd = "uv run pytest -v tests/", description = "Run tests (configure via KORNIA_TEST_* env vars)" }
-test-f32 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "float32" } }
-test-f64 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "float64" } }
-test-slow = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_RUNSLOW = "true" } }
-test-quick = { cmd = "uv run pytest -v tests/" }
-test-half = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "float16,bfloat16" }, description = "Run CPU half-precision tests" }
-test-module = { cmd = "uv run pytest -v", description = "Run tests for a specific module (usage: pixi run test-module tests/<module_path>, e.g., pixi run test-module tests/contrib/)" }
+test = { cmd = "uv run pytest tests/", description = "Run tests (configure via KORNIA_TEST_* env vars)" }
+test-f32 = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DTYPE = "float32" } }
+test-f64 = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DTYPE = "float64" } }
+test-slow = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_RUNSLOW = "true" } }
+test-quick = { cmd = "uv run pytest tests/" }
+test-half = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DTYPE = "float16,bfloat16" }, description = "Run CPU half-precision tests" }
+test-module = { cmd = "uv run pytest", description = "Run tests for a specific module (usage: pixi run test-module tests/<module_path>, e.g., pixi run test-module tests/contrib/)" }
# Quality
lint = { cmd = "uv run pre-commit run ruff-check --all-files && uv run pre-commit run ruff-format --all-files" }
pre-commit-all = { cmd = "uv run pre-commit run --all-files", description = "Run all repository pre-commit checks" }
pre-commit-install = { cmd = "uv run pre-commit install", description = "Install the pre-commit Git hook" }
typecheck = { cmd = "ty check kornia" }
-doctest = { cmd = "uv run pytest -v --doctest-modules kornia/", description = "Run docstring examples; examples needing an uncached model checkpoint are skipped" }
-doctest-weights = { cmd = "uv run pytest -v --doctest-modules kornia/", env = { KORNIA_DOCTEST_DOWNLOAD = "1" }, description = "Run docstring examples, downloading pretrained weights when the cache misses (~838 MB cold)" }
+doctest = { cmd = "uv run pytest --doctest-modules kornia/", description = "Run docstring examples; examples needing an uncached model checkpoint are skipped" }
+doctest-weights = { cmd = "uv run pytest --doctest-modules kornia/", env = { KORNIA_DOCTEST_DOWNLOAD = "1" }, description = "Run docstring examples, downloading pretrained weights when the cache misses (~838 MB cold)" }
toml-fmt = { cmd = "tombi format", description = "Format TOML files" }
toml-fmt-check = { cmd = "tombi format --check", description = "Check TOML formatting" }
# Docs
@@ -76,10 +76,10 @@ platforms = ["linux-64", "linux-aarch64", "win-64"]
install = { cmd = "uv sync --extra dev && uv pip install --reinstall torch torchvision --index pytorch-cu121", description = "Install dev dependencies (CUDA PyTorch)" }
install-docs = { cmd = "uv sync --extra dev --extra docs --extra x && uv pip install --reinstall torch torchvision --index pytorch-cu121", description = "Install dev + docs (CUDA PyTorch)" }
# CUDA test tasks
-test-cuda = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DEVICE = "cuda" }, description = "Run tests on CUDA" }
-test-cuda-f32 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float32" } }
-test-cuda-f64 = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float64" } }
-test-cuda-half = { cmd = "uv run pytest -v tests/ --isolate-half-precision", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float16,bfloat16" }, description = "Run half-precision CUDA tests with per-test subprocess isolation" }
+test-cuda = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DEVICE = "cuda" }, description = "Run tests on CUDA" }
+test-cuda-f32 = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float32" } }
+test-cuda-f64 = { cmd = "uv run pytest tests/", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float64" } }
+test-cuda-half = { cmd = "uv run pytest tests/ --isolate-half-precision", env = { KORNIA_TEST_DEVICE = "cuda", KORNIA_TEST_DTYPE = "float16,bfloat16" }, description = "Run half-precision CUDA tests with per-test subprocess isolation" }
# ------------------------------------------------------------------------------
# Python version features (for CI matrix)
diff --git a/pyproject.toml b/pyproject.toml
index 6776466e7..d0e8f90b3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -177,11 +177,12 @@ include = ["kornia/", "LICENSE", "README.md"]
match = '.*\.py'
[tool.pytest.ini_options]
-addopts = "--color=yes -v"
+addopts = "--color=yes"
filterwarnings = [
"ignore::DeprecationWarning:onnxscript.converter",
]
markers = [
+ "device_agnostic: run CPU-only test logic once in a CPU-containing device matrix",
"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",
]
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 6e02eb4f9..957c47396 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -131,14 +131,14 @@ class TestAugmentationSequential:
assert out_bb.shape == bb.shape
def test_random_flips(self, device, dtype):
- inp = torch.randn(1, 3, 510, 1020, device=device, dtype=dtype)
- bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
+ inp = torch.randn(1, 3, 255, 510, device=device, dtype=dtype)
+ bbox = torch.tensor([[[177, 5], [330, 5], [330, 125], [177, 125]]], device=device, dtype=dtype)
expected_bbox_vertical_flip = torch.tensor(
- [[[355, 259], [660, 259], [660, 499], [355, 499]]], device=device, dtype=dtype
+ [[[177, 129], [330, 129], [330, 249], [177, 249]]], device=device, dtype=dtype
)
expected_bbox_horizontal_flip = torch.tensor(
- [[[359, 10], [664, 10], [664, 250], [359, 250]]], device=device, dtype=dtype
+ [[[179, 5], [332, 5], [332, 125], [179, 125]]], device=device, dtype=dtype
)
aug_ver = K.AugmentationSequential(
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 8997ebdac..5d446fa10 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4561,7 +4561,7 @@ class TestNormalize(BaseTester):
)
def test_random_normalize_different_parameter_types(self, mean, std):
f = Normalize(mean=mean, std=std, p=1)
- data = torch.ones(2, 3, 256, 313)
+ data = torch.ones(2, 3, 16, 17)
if isinstance(mean, float):
expected = (data - torch.as_tensor(mean)) / torch.as_tensor(std)
else:
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 5a5859dfb..d509d8139 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -451,7 +451,7 @@ class TestRandomJigsaw(BaseTester):
torch.manual_seed(76)
f = RandomJigsaw(p=p, data_keys=["input"], same_on_batch=same_on_batch)
- input = torch.randn((12, 3, 256, 256), device=device, dtype=dtype)
+ input = torch.randn((4, 3, 32, 32), device=device, dtype=dtype)
f(input)
diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.py
index bc4436883..72f36f63d 100644
--- a/tests/augmentation/test_auto_operation.py
+++ b/tests/augmentation/test_auto_operation.py
@@ -40,11 +40,12 @@ def _find_all_ops() -> List[OperationBase]:
def _test_sequential(augment_method, device, dtype):
- inp = torch.rand(1, 3, 1000, 500, device=device, dtype=dtype)
- bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
- keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
+ height, width = 50, 100
+ inp = torch.rand(1, 3, height, width, device=device, dtype=dtype)
+ bbox = torch.tensor([[[35.5, 1], [66, 1], [66, 25], [35.5, 25]]], device=device, dtype=dtype)
+ keypoints = torch.tensor([[[46.5, 11.5], [54.5, 11.6]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
+ torch.tensor([[[15.5, 0], [90, 0], [90, 40], [15.5, 40]]], device=device, dtype=dtype), width, height
)[:, None]
aug = AugmentationSequential(augment_method, data_keys=["input", "mask", "bbox", "keypoints"])
out = aug(inp, mask, bbox, keypoints)
diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.py
index 94c95c8b1..707d1b1eb 100644
--- a/tests/augmentation/test_onnx_export.py
+++ b/tests/augmentation/test_onnx_export.py
@@ -186,6 +186,7 @@ def _try_export(module: torch.nn.Module, x: torch.Tensor) -> int:
@pytest.mark.parametrize("name,factory", EXPORTABLE_OPS, ids=[n for n, _ in EXPORTABLE_OPS])
def test_onnx_export_exportable(name: str, factory: Callable[[], torch.nn.Module]) -> None:
"""Augmentation exports cleanly via ``torch.onnx.export`` (legacy tracer, opset 20)."""
torch.manual_seed(0)
@@ -195,6 +196,7 @@ def test_onnx_export_exportable(name: str, factory: Callable[[], torch.nn.Module
@pytest.mark.parametrize("name,factory,reason", XFAIL_OPS, ids=[n for n, _, _ in XFAIL_OPS])
def test_onnx_export_known_blocked(name: str, factory: Callable[[], torch.nn.Module], reason: str) -> None:
"""Augmentation cannot export today; pinned so we notice if it starts working."""
torch.manual_seed(0)
@@ -308,6 +310,7 @@ def _run_onnx(module: torch.nn.Module, x: torch.Tensor) -> Any:
@pytest.mark.parametrize("name,factory", ONNX_NUMERICAL_EQUIVALENT, ids=[n for n, _ in ONNX_NUMERICAL_EQUIVALENT])
def test_onnx_export_numerically_matches_eager(name: str, factory: Callable[[], torch.nn.Module]) -> None:
"""Exported graph produces the same numbers as eager for the deterministic configuration."""
torch.manual_seed(0)
diff --git a/tests/augmentation/test_param_validation.py b/tests/augmentation/test_param_validation.py
index 0d42839fd..594b8c521 100644
--- a/tests/augmentation/test_param_validation.py
+++ b/tests/augmentation/test_param_validation.py
@@ -84,22 +84,24 @@ class TestParamValidation:
"tensor-2d",
],
)
- @pytest.mark.parametrize(
- "device",
- [
- torch.device("cpu"),
- pytest.param(
- torch.device("cuda"),
- marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available"),
- ),
- ],
- )
def test_tuple_range_reader_valid(self, input_param, target_size, expected, device):
"""Supported input formats should expand correctly across devices."""
res = _tuple_range_reader(input_param, target_size, device=device)
assert res.shape == (target_size, 2)
torch.testing.assert_close(res, expected.to(device))
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
+ def test_tuple_range_reader_honours_cuda_device(self):
+ """`_tuple_range_reader` allocates its own tensors, so the CUDA branch needs its own test.
+
+ The `device` fixture above follows `--device`, which is `cpu` in CI and in a default local
+ run, so the cross-product alone would never place the reader on an accelerator.
+ """
+ cuda = torch.device("cuda")
+ res = _tuple_range_reader([(5.0, 10.0), (3.0, 8.0)], 2, device=cuda)
+ assert res.device.type == "cuda"
+ torch.testing.assert_close(res, torch.tensor([[5.0, 10.0], [3.0, 8.0]], device=cuda))
+
@pytest.mark.parametrize(
"args, kwargs, expected_exception, match_msg",
[
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index 5b202f520..e1fcdf0a3 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -80,6 +80,7 @@ TORCH_EXPORT_DETERMINISTIC: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
@pytest.mark.skipif(not _HAS_TORCH_EXPORT_TRACKING, reason=_TORCH_EXPORT_TRACKING_REASON)
@pytest.mark.parametrize("name,factory", TORCH_EXPORT_DETERMINISTIC, ids=[n for n, _ in TORCH_EXPORT_DETERMINISTIC])
def test_torch_export_deterministic(name: str, factory: Callable[[], torch.nn.Module]) -> None:
"""Deterministic inference transform captures via ``torch.export`` and matches eager."""
torch.manual_seed(0)
@@ -124,6 +125,7 @@ TORCH_EXPORT_CONTAINERS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
@pytest.mark.skipif(not _HAS_TORCH_EXPORT_TRACKING, reason=_TORCH_EXPORT_TRACKING_REASON)
@pytest.mark.parametrize("name,factory", TORCH_EXPORT_CONTAINERS, ids=[n for n, _ in TORCH_EXPORT_CONTAINERS])
def test_torch_export_container(name: str, factory: Callable[[], torch.nn.Module]) -> None:
"""A deterministic ``AugmentationSequential`` pipeline captures via ``torch.export`` and matches eager."""
torch.manual_seed(0)
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index 3649310b7..d11f4a05f 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -45,7 +45,7 @@ class TestEqualization(BaseTester):
(1, 3, (2, 2)),
(4, 1, (2, 2)),
(4, 3, (2, 2)),
- (4, 3, (8, 8)),
+ (2, 2, (8, 8)),
],
)
def test_cardinality(self, B, C, grid_size, device, dtype):
diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.py
index e321bcfe3..eedfeaa2a 100644
--- a/tests/enhance/test_histogram.py
+++ b/tests/enhance/test_histogram.py
@@ -29,30 +29,30 @@ class TestImageHistogram2d(BaseTester):
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
def test_shape(self, device, dtype, kernel):
- sample = torch.ones(32, 32, device=device, dtype=dtype)
- hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 256, kernel=kernel)
- assert hist.shape == (256,)
- assert pdf.shape == (256,)
+ sample = torch.ones(16, 16, device=device, dtype=dtype)
+ hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 32, kernel=kernel)
+ assert hist.shape == (32,)
+ assert pdf.shape == (32,)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
def test_shape_channels(self, device, dtype, kernel):
- sample = torch.ones(3, 32, 32, device=device, dtype=dtype)
- hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 256, kernel=kernel)
- assert hist.shape == (3, 256)
- assert pdf.shape == (3, 256)
+ sample = torch.ones(3, 16, 16, device=device, dtype=dtype)
+ hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 32, kernel=kernel)
+ assert hist.shape == (3, 32)
+ assert pdf.shape == (3, 32)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
def test_shape_batch(self, device, dtype, kernel):
- sample = torch.ones(8, 3, 32, 32, device=device, dtype=dtype)
- hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 256, kernel=kernel)
- assert hist.shape == (8, 3, 256)
- assert pdf.shape == (8, 3, 256)
+ sample = torch.ones(4, 3, 16, 16, device=device, dtype=dtype)
+ hist, pdf = TestImageHistogram2d.fcn(sample, 0.0, 1.0, 32, kernel=kernel)
+ assert hist.shape == (4, 3, 32)
+ assert pdf.shape == (4, 3, 32)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
def test_gradcheck(self, device, kernel):
- sample = torch.ones(32, 32, device=device, dtype=torch.float64)
+ sample = torch.ones(8, 8, device=device, dtype=torch.float64)
centers = torch.linspace(0, 255, 8, device=device, dtype=torch.float64)
- self.gradcheck(TestImageHistogram2d.fcn, (sample, 0.0, 255.0, 256, None, centers, True, kernel))
+ self.gradcheck(TestImageHistogram2d.fcn, (sample, 0.0, 255.0, 8, None, centers, True, kernel))
@pytest.mark.skipif(
version.parse(torch.__version__) < version.parse("1.9"), reason="Tuple cannot be jitted with PyTorch < v1.9"
@@ -71,7 +71,7 @@ class TestImageHistogram2d(BaseTester):
self.assert_close(out[1], out_script[1])
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
- @pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
+ @pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (4, 3, 1, 1)])
def test_uniform_hist(self, device, dtype, kernel, size):
sample = torch.linspace(0, 255, 10, device=device, dtype=dtype)
sample_x, _ = torch.meshgrid(sample, sample, indexing="ij")
@@ -85,7 +85,7 @@ class TestImageHistogram2d(BaseTester):
self.assert_close(ans, hist)
@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])
- @pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (8, 3, 1, 1)])
+ @pytest.mark.parametrize("size", [(1, 1), (3, 1, 1), (4, 3, 1, 1)])
def test_uniform_dist(self, device, dtype, kernel, size):
sample = torch.linspace(0, 255, 10, device=device, dtype=dtype)
sample_x, _ = torch.meshgrid(sample, sample, indexing="ij")
@@ -105,20 +105,20 @@ class TestHistogram2d(BaseTester):
fcn = kornia.enhance.histogram2d
def test_shape(self, device, dtype):
- inp1 = torch.ones(1, 32, device=device, dtype=dtype)
- inp2 = torch.ones(1, 32, device=device, dtype=dtype)
- bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ inp1 = torch.ones(1, 16, device=device, dtype=dtype)
+ inp2 = torch.ones(1, 16, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 32, device=device, dtype=dtype)
bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)
- assert pdf.shape == (1, 128, 128)
+ assert pdf.shape == (1, 32, 32)
def test_shape_batch(self, device, dtype):
- inp1 = torch.ones(8, 32, device=device, dtype=dtype)
- inp2 = torch.ones(8, 32, device=device, dtype=dtype)
- bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ inp1 = torch.ones(4, 16, device=device, dtype=dtype)
+ inp2 = torch.ones(4, 16, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 32, device=device, dtype=dtype)
bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)
- assert pdf.shape == (8, 128, 128)
+ assert pdf.shape == (4, 32, 32)
def test_gradcheck(self, device):
inp1 = torch.ones(1, 8, device=device, dtype=torch.float64)
@@ -154,18 +154,18 @@ class TestHistogram(BaseTester):
fcn = kornia.enhance.histogram
def test_shape(self, device, dtype):
- inp = torch.ones(1, 32, device=device, dtype=dtype)
- bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ inp = torch.ones(1, 16, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 32, device=device, dtype=dtype)
bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
pdf = TestHistogram.fcn(inp, bins, bandwidth)
- assert pdf.shape == (1, 128)
+ assert pdf.shape == (1, 32)
def test_shape_batch(self, device, dtype):
- inp = torch.ones(8, 32, device=device, dtype=dtype)
- bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ inp = torch.ones(4, 16, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 32, device=device, dtype=dtype)
bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
pdf = TestHistogram.fcn(inp, bins, bandwidth)
- assert pdf.shape == (8, 128)
+ assert pdf.shape == (4, 32)
def test_gradcheck(self, device):
inp = torch.ones(1, 8, device=device, dtype=torch.float64)
diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.py
index fa70ba496..5af2a745c 100644
--- a/tests/enhance/test_normalize.py
+++ b/tests/enhance/test_normalize.py
@@ -120,7 +120,7 @@ class TestNormalize(BaseTester):
# prepare input data
mean = torch.tensor(2, device=device, dtype=dtype)
std = torch.tensor(3, device=device, dtype=dtype)
- data = torch.ones(2, 3, 256, 313, device=device, dtype=dtype)
+ data = torch.ones(2, 3, 16, 17, device=device, dtype=dtype)
# expected output
expected = (data - mean) / std
@@ -143,7 +143,7 @@ class TestNormalize(BaseTester):
)
def test_random_normalize_different_parameter_types(self, mean, std):
f = kornia.enhance.Normalize(mean=mean, std=std)
- data = torch.ones(2, 3, 256, 313)
+ data = torch.ones(2, 3, 16, 17)
if isinstance(mean, float):
expected = (data - torch.as_tensor(mean)) / torch.as_tensor(std)
else:
diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.py
index 1b12302b3..8c6dfbf20 100644
--- a/tests/feature/test_hardnet.py
+++ b/tests/feature/test_hardnet.py
@@ -34,10 +34,10 @@ class TestHardNet(BaseTester):
@pytest.mark.slow
def test_shape_batch(self, device):
- inp = torch.ones(16, 1, 32, 32, device=device)
+ inp = torch.ones(4, 1, 32, 32, device=device)
hardnet = HardNet().to(device)
out = hardnet(inp)
- assert out.shape == (16, 128)
+ assert out.shape == (4, 128)
def test_gradcheck(self, device):
patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
@@ -61,10 +61,10 @@ class TestHardNet8(BaseTester):
assert out.shape == (1, 128)
def test_shape_batch(self, device):
- inp = torch.ones(16, 1, 32, 32, device=device)
+ inp = torch.ones(4, 1, 32, 32, device=device)
hardnet = HardNet8().to(device)
out = hardnet(inp)
- assert out.shape == (16, 128)
+ assert out.shape == (4, 128)
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.py
index 83aaaa884..8df03f90d 100644
--- a/tests/feature/test_hynet.py
+++ b/tests/feature/test_hynet.py
@@ -36,10 +36,10 @@ class TestHyNet(BaseTester):
assert out.shape == (1, 128)
def test_shape_batch(self, device):
- inp = torch.ones(16, 1, 32, 32, device=device)
+ inp = torch.ones(4, 1, 32, 32, device=device)
hynet = HyNet().to(device)
out = hynet(inp)
- assert out.shape == (16, 128)
+ assert out.shape == (4, 128)
def test_gradcheck(self, device):
patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)
diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.py
index 4da71c17d..06adf4c21 100644
--- a/tests/feature/test_lightglue_onnx.py
+++ b/tests/feature/test_lightglue_onnx.py
@@ -41,6 +41,7 @@ class TestOnnxLightGlue:
assert model is not None
@pytest.mark.slow
+ @pytest.mark.device_agnostic
@pytest.mark.parametrize("weights", ["disk", "superpoint"])
def test_pretrained_weights_cpu(self, weights):
model = OnnxLightGlue(weights, "cpu")
@@ -79,6 +80,7 @@ class TestOnnxLightGlue:
assert outputs["scores"].ndim == 1
assert outputs["matches"].shape[0] == outputs["scores"].shape[0]
+ @pytest.mark.device_agnostic
def test_normalize_keypoints(self):
kpts = torch.randint(0, 100, (1, 5, 2))
size = torch.tensor([[100, 100]])
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index b9bf864b4..01a2a1144 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -619,14 +619,14 @@ class TestMultiResolutionDetector(BaseTester):
# interpolated mask reads 1.0 there and the stripe is gone; the conservative resample keeps
# every level pixel it touches at zero.
torch.manual_seed(0)
- inp = torch.rand(1, 1, 256, 256, device=device, dtype=dtype)
- mask = torch.ones(1, 1, 256, 256, device=device, dtype=dtype)
- mask[:, :, :, 120:122] = 0.0
- det = self._make_detector(num_features=2000).to(device, dtype)
+ inp = torch.rand(1, 1, 128, 128, device=device, dtype=dtype)
+ mask = torch.ones(1, 1, 128, 128, device=device, dtype=dtype)
+ mask[:, :, :, 60:62] = 0.0
+ det = self._make_detector(num_features=500).to(device, dtype)
lafs, resps = det(inp, mask)
xs = lafs[0][resps[0] != 0][:, 0, 2]
assert xs.numel() > 100
- assert not bool(((xs >= 120) & (xs < 122)).any()), sorted(xs[(xs >= 119) & (xs < 123)].tolist())
+ assert not bool(((xs >= 60) & (xs < 62)).any()), sorted(xs[(xs >= 59) & (xs < 63)].tolist())
@pytest.mark.parametrize("src, dst", [((100, 100), (45, 45)), ((38, 38), (90, 90)), ((7, 9), (3, 4))])
def test_mask_resample_is_the_cpu_adaptive_min_pool_on_every_device(self, device, dtype, src, dst):
diff --git a/tests/feature/test_steerer.py b/tests/feature/test_steerer.py
index ee14318f7..d39ab1379 100644
--- a/tests/feature/test_steerer.py
+++ b/tests/feature/test_steerer.py
@@ -24,7 +24,7 @@ from testing.base import BaseTester
class TestDiscreteSteerer(BaseTester):
- @pytest.mark.parametrize("num_desc, desc_dim, steerer_power", [(1, 4, 1), (2, 128, 7), (32, 128, 11)])
+ @pytest.mark.parametrize("num_desc, desc_dim, steerer_power", [(1, 4, 1), (2, 128, 7), (4, 128, 11)])
def test_shape(self, num_desc, desc_dim, steerer_power, device, dtype):
desc = torch.rand(num_desc, desc_dim, device=device, dtype=dtype)
generator = torch.rand(desc_dim, desc_dim, device=device, dtype=dtype)
@@ -35,7 +35,7 @@ class TestDiscreteSteerer(BaseTester):
@pytest.mark.parametrize("normalize", [True, False])
def test_steering(self, device, normalize):
generator = torch.tensor([[0.0, 1], [-1, 0]], device=device)
- desc = torch.rand(16, 2, device=device)
+ desc = torch.rand(4, 2, device=device)
steerer = DiscreteSteerer(generator)
desc_out = steerer.steer_descriptions(desc, steerer_power=3, normalize=normalize)
if normalize:
@@ -52,7 +52,7 @@ class TestDiscreteSteerer(BaseTester):
steerer_order=steerer_order,
).to(device)
assert isinstance(steerer, DiscreteSteerer)
- shape = (96, 256)
+ shape = (4, 256)
desc = torch.randn(*shape, device=device)
desc = steerer(desc)
assert desc.shape == shape
@@ -60,14 +60,14 @@ class TestDiscreteSteerer(BaseTester):
@pytest.mark.parametrize("steerer_power", [0, 1, 5, -1])
def test_steerer_power_extremes(self, device, steerer_power):
generator = torch.tensor([[0.0, 1], [-1, 0]], device=device)
- desc = torch.rand(8, 2, device=device)
+ desc = torch.rand(4, 2, device=device)
steerer = DiscreteSteerer(generator)
out = steerer.steer_descriptions(desc, steerer_power=steerer_power)
assert out.shape == desc.shape
def test_normalization_preserves_norm(self, device):
generator = torch.tensor([[0.0, 1], [-1, 0]], device=device)
- desc = torch.rand(8, 2, device=device)
+ desc = torch.rand(4, 2, device=device)
steerer = DiscreteSteerer(generator)
out = steerer.steer_descriptions(desc, steerer_power=1, normalize=True)
orig_norm = torch.norm(out, dim=-1)
diff --git a/tests/feature/test_tfeat.py b/tests/feature/test_tfeat.py
index edecff9e8..f22017b19 100644
--- a/tests/feature/test_tfeat.py
+++ b/tests/feature/test_tfeat.py
@@ -40,10 +40,10 @@ class TestTFeat(BaseTester):
assert out.shape == (1, 128)
def test_shape_batch(self, device):
- inp = torch.ones(16, 1, 32, 32, device=device)
+ inp = torch.ones(4, 1, 32, 32, device=device)
tfeat = TFeat().to(device)
out = tfeat(inp)
- assert out.shape == (16, 128)
+ assert out.shape == (4, 128)
@pytest.mark.skip("jacobian not well computed")
def test_gradcheck(self, device):
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 93013fd17..119ca157a 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -15,11 +15,16 @@
# limitations under the License.
#
+import io
+import os
+import tempfile
import warnings
+from typing import Any
import pytest
import torch
+from kornia.core._compat import torch_version_ge, torch_version_lt
from kornia.filters import (
GaussianBlur2d,
gaussian,
@@ -320,38 +325,56 @@ class TestGaussianBlur2d(BaseTester):
self.assert_close(op(data), op_optimized(data))
- def test_onnx_export(self, device, dtype):
- """Test that GaussianBlur2d can be exported via torch.onnx.export."""
+ @pytest.mark.device_agnostic
+ def test_onnx_export_legacy(self, dtype):
+ """Test that GaussianBlur2d can be exported through the legacy ONNX exporter."""
+ pytest.importorskip("onnx")
kernel_size = (3, 3)
sigma = (1.5, 1.5)
-
- # Create model and sample input
model = GaussianBlur2d(kernel_size, sigma)
- sample_input = torch.ones(1, 3, 8, 8, device=device, dtype=dtype)
-
- # Test ONNX export - just ensure it doesn't error
- # TODO: think of an absctraction
- try:
- import os
- import tempfile
-
- # Suppress onnxscript deprecation warnings (Python 3.15 compatibility)
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=DeprecationWarning, module="onnxscript.converter")
- with tempfile.TemporaryDirectory() as tmpdir:
- onnx_path = os.path.join(tmpdir, "gaussian_blur2d.onnx")
- torch.onnx.export(
- model,
- sample_input,
- onnx_path,
- input_names=["input"],
- output_names=["output"],
- opset_version=17,
- )
- # Verify the file was created
- assert os.path.exists(onnx_path)
- except Exception as e:
- pytest.skip(f"ONNX export not supported: {e}")
+ sample_input = torch.ones(1, 3, 8, 8, dtype=dtype)
+ buf = io.BytesIO()
+ export_kwargs: dict[str, Any] = {
+ "input_names": ["input"],
+ "output_names": ["output"],
+ "opset_version": 17,
+ }
+ if torch_version_ge(2, 5, 0):
+ export_kwargs["dynamo"] = False
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, sample_input, buf, **export_kwargs)
+ assert buf.getbuffer().nbytes > 0
+
+ @pytest.mark.device_agnostic
+ # 2.5 is where `dynamo=` first exists, but there it still routes through the experimental
+ # `_compat.export_compat` shim. This test passes `fallback=False` implicitly, so on the 2.5.1
+ # CI legs any exporter/onnxscript mismatch would be a hard failure rather than a skip; require
+ # the settled 2.6 exporter instead.
+ @pytest.mark.skipif(
+ torch_version_lt(2, 6, 0), reason="the dynamo ONNX exporter is only non-experimental from PyTorch 2.6"
+ )
+ def test_onnx_export_modern(self, dtype):
+ """Test that GaussianBlur2d can be exported through the dynamo ONNX exporter."""
+ pytest.importorskip("onnx")
+ pytest.importorskip("onnxscript")
+ model = GaussianBlur2d((3, 3), (1.5, 1.5))
+ sample_input = torch.ones(1, 3, 8, 8, dtype=dtype)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ with tempfile.TemporaryDirectory() as tmpdir:
+ onnx_path = os.path.join(tmpdir, "gaussian_blur2d.onnx")
+ torch.onnx.export(
+ model,
+ sample_input,
+ onnx_path,
+ input_names=["input"],
+ output_names=["output"],
+ opset_version=18,
+ dynamo=True,
+ )
+ assert os.path.getsize(onnx_path) > 0
def test_sigma_negative_raises_exception(self, device, dtype):
"""Test that negative sigma raises an exception."""
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index de448c3bf..d49e3e593 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -33,7 +33,7 @@ class TestFindEssential(BaseTester):
E_mat = epi.essential.find_essential(points1, points2, weights)
assert E_mat.shape == (1, 10, 3, 3)
- @pytest.mark.parametrize("batch_size, num_points", [(1, 5), (2, 6), (3, 7), (1000, 5)])
+ @pytest.mark.parametrize("batch_size, num_points", [(1, 5), (2, 6), (3, 7), (16, 5)])
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index bc570f3d7..9e7bf8cf9 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -3236,30 +3236,44 @@ class TestNormalizePixelCoordinates(BaseTester):
with pytest.raises(ValueError, match="must be positive"):
op(coords, *bad_sizes)
- def test_trace_crosses_singleton_boundary(self, device, dtype):
- class Normalize(torch.nn.Module):
+ def test_normalize_and_denormalize_trace_cross_singleton_boundary(self, device, dtype):
+ class Convert(torch.nn.Module):
def forward(self, image, coords):
- return kornia.geometry.conversions.normalize_pixel_coordinates(coords, image.shape[-2], image.shape[-1])
+ height, width = image.shape[-2], image.shape[-1]
+ return (
+ kornia.geometry.conversions.normalize_pixel_coordinates(coords, height, width),
+ kornia.geometry.conversions.denormalize_pixel_coordinates(coords, height, width),
+ )
coords = torch.tensor([[0.0, 0.0], [0.5, 0.5]], device=device, dtype=dtype)
for trace_height, runtime_height in ((2, 1), (1, 2)):
example = torch.zeros(1, 1, trace_height, 4, device=device, dtype=dtype)
runtime = torch.zeros(1, 1, runtime_height, 4, device=device, dtype=dtype)
- traced = torch.jit.trace(Normalize(), (example, coords))
- self.assert_close(traced(runtime, coords), Normalize()(runtime, coords), atol=0.0, rtol=0.0)
-
- class Normalize3d(torch.nn.Module):
+ convert = Convert()
+ traced = torch.jit.trace(convert, (example, coords))
+ actual = traced(runtime, coords)
+ expected = convert(runtime, coords)
+ self.assert_close(actual[0], expected[0], atol=0.0, rtol=0.0)
+ self.assert_close(actual[1], expected[1], atol=0.0, rtol=0.0)
+
+ class Convert3d(torch.nn.Module):
def forward(self, volume, coords):
- return kornia.geometry.conversions.normalize_pixel_coordinates3d(
- coords, volume.shape[-3], volume.shape[-2], volume.shape[-1]
+ depth, height, width = volume.shape[-3], volume.shape[-2], volume.shape[-1]
+ return (
+ kornia.geometry.conversions.normalize_pixel_coordinates3d(coords, depth, height, width),
+ kornia.geometry.conversions.denormalize_pixel_coordinates3d(coords, depth, height, width),
)
coords3d = torch.tensor([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]], device=device, dtype=dtype)
for trace_depth, runtime_depth in ((2, 1), (1, 2)):
example = torch.zeros(1, 1, trace_depth, 3, 4, device=device, dtype=dtype)
runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
- traced = torch.jit.trace(Normalize3d(), (example, coords3d))
- self.assert_close(traced(runtime, coords3d), Normalize3d()(runtime, coords3d), atol=0.0, rtol=0.0)
+ convert = Convert3d()
+ traced = torch.jit.trace(convert, (example, coords3d))
+ actual = traced(runtime, coords3d)
+ expected = convert(runtime, coords3d)
+ self.assert_close(actual[0], expected[0], atol=0.0, rtol=0.0)
+ self.assert_close(actual[1], expected[1], atol=0.0, rtol=0.0)
def test_wart_default_eps_1e_8_backs_the_remaining_quoted_warning_numbers():
@@ -3433,33 +3447,6 @@ class TestDenormalizePixelCoordinates(BaseTester):
actual = op(coords, *sizes, eps=1.0)
self.assert_close(actual, expected, atol=0.0, rtol=0.0)
- def test_trace_crosses_singleton_boundary(self, device, dtype):
- class Denormalize(torch.nn.Module):
- def forward(self, image, coords):
- return kornia.geometry.conversions.denormalize_pixel_coordinates(
- coords, image.shape[-2], image.shape[-1]
- )
-
- coords = torch.tensor([[0.0, 0.0], [0.5, 0.5]], device=device, dtype=dtype)
- for trace_height, runtime_height in ((2, 1), (1, 2)):
- example = torch.zeros(1, 1, trace_height, 4, device=device, dtype=dtype)
- runtime = torch.zeros(1, 1, runtime_height, 4, device=device, dtype=dtype)
- traced = torch.jit.trace(Denormalize(), (example, coords))
- self.assert_close(traced(runtime, coords), Denormalize()(runtime, coords), atol=0.0, rtol=0.0)
-
- class Denormalize3d(torch.nn.Module):
- def forward(self, volume, coords):
- return kornia.geometry.conversions.denormalize_pixel_coordinates3d(
- coords, volume.shape[-3], volume.shape[-2], volume.shape[-1]
- )
-
- coords3d = torch.tensor([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]], device=device, dtype=dtype)
- for trace_depth, runtime_depth in ((2, 1), (1, 2)):
- example = torch.zeros(1, 1, trace_depth, 3, 4, device=device, dtype=dtype)
- runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
- traced = torch.jit.trace(Denormalize3d(), (example, coords3d))
- self.assert_close(traced(runtime, coords3d), Denormalize3d()(runtime, coords3d), atol=0.0, rtol=0.0)
-
@pytest.mark.parametrize(
("op_name", "args"),
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 11a25d5fb..d344f1554 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -405,11 +405,14 @@ class TestRANSACEssential(BaseTester):
forward() must return an essential matrix even when local optimization does not win and
the best model is the minimal-solver estimate (find_essential), which is not guaranteed
to be on the essential manifold. The returned model is projected onto the manifold
- before being returned, so the constraint holds regardless of which path selects the
- best model.
+ before being returned, so the constraint holds for the model forward() selects.
+
+ ``batch_size``/``max_iter`` are trimmed for speed, but ``max_lo_iters`` keeps its default
+ so the local-optimization loop still runs: on this input it is entered once per draw and
+ never beats the minimal-solver model, exactly as with the default sampler settings.
"""
torch.random.manual_seed(0)
- ransac = RANSAC("essential").to(device=device, dtype=dtype)
+ ransac = RANSAC("essential", batch_size=32, max_iter=1).to(device=device, dtype=dtype)
for _ in range(5):
kp1 = torch.rand(20, 2, device=device, dtype=dtype)
kp2 = torch.rand(20, 2, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index 3fe5bf377..b4a226e3f 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -127,7 +127,9 @@ class TestImageRegistrator(BaseTester):
img1 = torch.rand(1, 1, 64, 64, device=device)
img2 = torch.rand(1, 1, 32, 32, device=device)
- registrator = ImageRegistrator("similarity", allow_shape_mismatch=True)
+ registrator = ImageRegistrator("similarity", allow_shape_mismatch=True, pyramid_levels=1, num_iterations=1).to(
+ device
+ )
out = registrator.register(img1, img2)
diff --git a/tests/losses/test_mutual_information.py b/tests/losses/test_mutual_information.py
index c5994a882..b2ab4fa59 100644
--- a/tests/losses/test_mutual_information.py
+++ b/tests/losses/test_mutual_information.py
@@ -123,23 +123,23 @@ class TestMutualInformationLoss(BaseTester):
self.gradcheck(normalized_mutual_information_loss, (img1, img2))
def test_differentiability(self, device, dtype):
- for _ in range(10):
- img_1 = self.sampling_function(10000, device, dtype)
- img_2 = self.sampling_function(10000, device, dtype)
- param = torch.tensor(1 / 2.0, requires_grad=True)
- mi = mutual_information_loss(img_1 + param * img_2, img_2)
- mi.backward()
- # negative gradient, order of magnitude 1/2
- assert -1 < param.grad < -1 / 10, f"Differentiability issue for mi, {param.grad=}."
- param = torch.tensor(1 / 2.0, requires_grad=True)
- nmi = normalized_mutual_information_loss(img_1 + param * img_2, img_2)
- nmi.backward()
- # negative gradient, order of magnitude 1/20
- assert -1 / 10 < param.grad < -1 / 100, f"Differentiability issue for nmi, {param.grad=}."
+ torch.manual_seed(0)
+ img_1 = self.sampling_function(10000, device, dtype)
+ img_2 = self.sampling_function(10000, device, dtype)
+ param = torch.tensor(1 / 2.0, requires_grad=True)
+ mi = mutual_information_loss(img_1 + param * img_2, img_2)
+ mi.backward()
+ # negative gradient, order of magnitude 1/2
+ assert -1 < param.grad < -1 / 10, f"Differentiability issue for mi, {param.grad=}."
+ param = torch.tensor(1 / 2.0, requires_grad=True)
+ nmi = normalized_mutual_information_loss(img_1 + param * img_2, img_2)
+ nmi.backward()
+ # negative gradient, order of magnitude 1/20
+ assert -1 / 10 < param.grad < -1 / 100, f"Differentiability issue for nmi, {param.grad=}."
def test_value_ranges(self, device, dtype):
- for _ in range(10):
- self.value_ranges_check(device, dtype)
+ torch.manual_seed(0)
+ self.value_ranges_check(device, dtype)
def test_trivial_signal_normalizes_to_zero(self, device, dtype):
signal = torch.tensor([[0.25, 0.25, 0.25], [0.75, 0.75, 0.75]], device=device, dtype=dtype)
@@ -207,19 +207,19 @@ class TestMutualInformationLoss(BaseTester):
def test_masking(self, device, dtype):
"""test masking works on a 2d signal."""
- pred = torch.rand(2, 3, 200, 200, device=device, dtype=dtype)
- target = torch.rand(2, 3, 200, 200, device=device, dtype=dtype)
+ pred = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
+ target = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
target_mask = torch.zeros(pred.shape[-2:], dtype=torch.bool, device=device)
pred_mask = target_mask.clone()
- target_mask[:100] = True
- pred_mask[:, :100] = True
+ target_mask[:32] = True
+ pred_mask[:, :32] = True
# we tweak the values of target and pred for the normalization to be the same with or without the mask
target[..., 0, 0] = 0
target[..., 0, 1] = 1
pred[..., 0, 0] = 0
pred[..., 0, 1] = 1
- restricted_pred = pred[..., :100, :100]
- restricted_target = target[..., :100, :100]
+ restricted_pred = pred[..., :32, :32]
+ restricted_target = target[..., :32, :32]
masked_kwargs = {"input": pred, "target": target, "input_mask": pred_mask, "target_mask": target_mask}
restricted_kwargs = {
diff --git a/tests/models/qwen25/test_qwen2_vl.py b/tests/models/qwen25/test_qwen2_vl.py
index 6f0ba56a8..07389dc35 100644
--- a/tests/models/qwen25/test_qwen2_vl.py
+++ b/tests/models/qwen25/test_qwen2_vl.py
@@ -30,16 +30,16 @@ class TestQwen2VL:
# smaller model β†’ stable
model = Qwen2VLVisionTransformer(embed_dim=64, depth=2, num_heads=4).to(device=device, dtype=dtype)
- x = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)
+ x = torch.randn(batch_size, 3, 112, 112, device=device, dtype=dtype)
output = model(x)
- assert output.shape == (batch_size, 256, 64)
+ assert output.shape == (batch_size, 64, 64)
def test_gradients(self, device):
model = Qwen2VLVisionTransformer(embed_dim=64, depth=1, num_heads=4).to(device)
- x = torch.randn(1, 3, 224, 224, device=device, requires_grad=True)
+ x = torch.randn(1, 3, 112, 112, device=device, requires_grad=True)
output = model(x)
loss = output.mean()
@@ -50,16 +50,16 @@ class TestQwen2VL:
def test_patch_merger(self, device):
merger = Qwen2VLPatchMerger(dim=64).to(device)
- x = torch.randn(1, 3, 224, 224, device=device)
+ x = torch.randn(1, 3, 112, 112, device=device)
output = merger(x)
- assert output.shape == (1, 256, 64)
+ assert output.shape == (1, 64, 64)
def test_batch_consistency(self, device):
"""Ensure outputs are consistent between batch and single input."""
model = Qwen2VLVisionTransformer(embed_dim=64, depth=2, num_heads=4).to(device)
- x = torch.randn(2, 3, 224, 224, device=device)
+ x = torch.randn(2, 3, 112, 112, device=device)
out_batch = model(x)
out_single = model(x[:1])
diff --git a/tests/models/sam3/test_sam3_architecture.py b/tests/models/sam3/test_sam3_architecture.py
index b26954952..5f96170eb 100644
--- a/tests/models/sam3/test_sam3_architecture.py
+++ b/tests/models/sam3/test_sam3_architecture.py
@@ -67,7 +67,7 @@ class TestSam3Common(BaseTester):
class TestImageEncoderHiera(BaseTester):
"""Test ImageEncoderHiera architecture."""
- @pytest.mark.parametrize("img_size,embed_dim", [(256, 128), (512, 256)])
+ @pytest.mark.parametrize("img_size,embed_dim", [(64, 128), (128, 256)])
def test_image_encoder_hiera_smoke(self, device: str, img_size: int, embed_dim: int) -> None:
"""Test ImageEncoderHiera basic functionality with different configs."""
patch_size = 16
@@ -87,20 +87,20 @@ class TestImageEncoderHiera(BaseTester):
num_patches = (img_size // patch_size) ** 2
assert features.shape == (B, num_patches, embed_dim)
- @pytest.mark.parametrize("batch_size", [1, 2, 4])
+ @pytest.mark.parametrize("batch_size", [1, 2])
def test_image_encoder_hiera_cardinality(self, device: str, batch_size: int) -> None:
"""Test ImageEncoderHiera output cardinality with different batch sizes."""
encoder = ImageEncoderHiera(
- img_size=256,
+ img_size=64,
patch_size=16,
embed_dim=128,
depth=2,
num_heads=4,
).to(device)
- x = torch.randn(batch_size, 3, 256, 256, device=device)
+ x = torch.randn(batch_size, 3, 64, 64, device=device)
features = encoder(x)
- assert features.shape == (batch_size, (256 // 16) ** 2, 128)
+ assert features.shape == (batch_size, (64 // 16) ** 2, 128)
def test_image_encoder_hiera_output_shape(self) -> None:
"""Test output shape computation method."""
diff --git a/tests/models/test_dexined_onnx.py b/tests/models/test_dexined_onnx.py
index bab05d1e9..140d7bcf4 100644
--- a/tests/models/test_dexined_onnx.py
+++ b/tests/models/test_dexined_onnx.py
@@ -19,6 +19,9 @@ import pytest
from kornia.models.dexined import DexiNed
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
@pytest.mark.timeout(120)
def test_dexined_to_onnx(tmp_path):
diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.py
index a357a4301..c5d6dd402 100644
--- a/tests/models/test_efficient_vit.py
+++ b/tests/models/test_efficient_vit.py
@@ -46,7 +46,7 @@ class TestEfficientViT:
self._test_smoke(device, dtype, img_size, expected_resolution, model_name)
@pytest.mark.parametrize("model_name", ["b0", "b1", "b2"])
- @pytest.mark.parametrize("img_size,expected_resolution", [(224, 7), (256, 8), (288, 9)])
+ @pytest.mark.parametrize("img_size,expected_resolution", [(64, 2), (96, 3), (128, 4)])
def test_smoke(self, device, dtype, img_size: int, expected_resolution: int, model_name: str):
self._test_smoke(device, dtype, img_size, expected_resolution, model_name)
diff --git a/tests/models/test_mobile_vit.py b/tests/models/test_mobile_vit.py
index 16f91c8f8..b0918410c 100644
--- a/tests/models/test_mobile_vit.py
+++ b/tests/models/test_mobile_vit.py
@@ -25,7 +25,7 @@ from testing.base import BaseTester
class TestMobileViT(BaseTester):
@pytest.mark.parametrize("B", [1, 2])
- @pytest.mark.parametrize("image_size", [(256, 256)])
+ @pytest.mark.parametrize("image_size", [(128, 128)])
@pytest.mark.parametrize("mode", ["xxs", "xs", "s"])
@pytest.mark.parametrize("patch_size", [(2, 2)])
def test_smoke(self, device, dtype, B, image_size, mode, patch_size):
@@ -37,4 +37,4 @@ class TestMobileViT(BaseTester):
out = mvit(img)
assert isinstance(out, torch.Tensor)
- assert out.shape == (B, channel[mode], 8, 8)
+ assert out.shape == (B, channel[mode], 4, 4)
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index 0d7f0dbcf..23ebb0566 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -30,9 +30,9 @@ from testing.base import BaseTester
class TestObjectDetector(BaseTester):
def test_smoke(self, device, dtype):
- batch_size = 3
+ batch_size = 2
confidence = 0.3
- config = RTDETRConfig("resnet50d", 10, head_num_queries=10)
+ config = RTDETRConfig("resnet18d", 10, head_num_queries=10)
model = RTDETR.from_config(config).to(device, dtype).eval()
pre_processor = kornia.models.processors.ResizePreProcessor(32, 32)
post_processor = DETRPostProcessor(confidence, num_top_queries=3).to(device, dtype).eval()
diff --git a/tests/models/test_rt_detr.py b/tests/models/test_rt_detr.py
index 3c5191935..e0c9e5efe 100644
--- a/tests/models/test_rt_detr.py
+++ b/tests/models/test_rt_detr.py
@@ -99,7 +99,7 @@ class TestRTDETR(BaseTester):
assert isinstance(out, tuple)
assert len(out) == 2
- @pytest.mark.parametrize("shape", ((1, 3, 96, 128), (2, 3, 224, 256)))
+ @pytest.mark.parametrize("shape", ((1, 3, 96, 128), (2, 3, 64, 96)))
def test_cardinality(self, shape, device, dtype):
num_classes = 10
num_queries = 10
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index fe1ada9b1..deb7de789 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -21,6 +21,9 @@ import pytest
from kornia.models.rt_detr.model import RTDETR, RTDETRConfig
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
@pytest.mark.timeout(120)
def test_rtdetr_to_onnx(tmp_path):
diff --git a/tests/models/test_sam_onnx.py b/tests/models/test_sam_onnx.py
index dc33b4133..ffc3b9df5 100644
--- a/tests/models/test_sam_onnx.py
+++ b/tests/models/test_sam_onnx.py
@@ -21,6 +21,9 @@ import pytest
from kornia.models.sam.model import Sam, SamConfig
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
def test_sam_has_to_onnx():
"""Sam exposes a to_onnx() method via ONNXExportMixin."""
diff --git a/tests/models/test_small_sr.py b/tests/models/test_small_sr.py
index 1640918dc..1c3c5f0fb 100644
--- a/tests/models/test_small_sr.py
+++ b/tests/models/test_small_sr.py
@@ -37,7 +37,7 @@ class TestSmallSRNet(BaseTester):
assert model is not None
# Input is single channel (Y channel from YCbCr)
- x = torch.randn(batch_size, 1, 224, 224, device=device, dtype=dtype)
+ x = torch.randn(batch_size, 1, 32, 48, device=device, dtype=dtype)
output = model(x)
assert output is not None
@@ -47,7 +47,7 @@ class TestSmallSRNet(BaseTester):
# SmallSRNet expects 1 channel input (Y channel), not 3
with pytest.raises(RuntimeError):
- x = torch.randn(1, 3, 224, 224, device=device, dtype=dtype)
+ x = torch.randn(1, 3, 16, 16, device=device, dtype=dtype)
model(x)
def test_smoke_upscale_factor_one(self, device, dtype):
@@ -58,7 +58,7 @@ class TestSmallSRNet(BaseTester):
assert model is not None
# Test forward pass - should work without crashing
- x = torch.randn(1, 1, 64, 64, device=device, dtype=dtype)
+ x = torch.randn(1, 1, 32, 32, device=device, dtype=dtype)
output = model(x)
# With upscale_factor=1, output dimensions should match input dimensions
@@ -67,7 +67,7 @@ class TestSmallSRNet(BaseTester):
@pytest.mark.parametrize("upscale_factor", [2, 3, 4])
@pytest.mark.parametrize("batch_size", [1, 2, 4])
- @pytest.mark.parametrize("height,width", [(64, 64), (128, 128), (224, 224)])
+ @pytest.mark.parametrize("height,width", [(32, 32), (32, 48), (48, 32)])
def test_cardinality(self, device, dtype, upscale_factor, batch_size, height, width):
"""Test that output shape matches expected upscaled dimensions."""
model = SmallSRNet(upscale_factor=upscale_factor, pretrained=False).to(device, dtype)
@@ -83,7 +83,7 @@ class TestSmallSRNet(BaseTester):
"""Test the forward pass produces valid outputs with expected value ranges."""
model = SmallSRNet(upscale_factor=upscale_factor, pretrained=False).to(device, dtype)
- x = torch.randn(1, 1, 64, 64, device=device, dtype=dtype)
+ x = torch.randn(1, 1, 32, 32, device=device, dtype=dtype)
output = model(x)
# Check output is not all zeros
@@ -155,7 +155,7 @@ class TestSmallSRNetWrapper(BaseTester):
assert model is not None
# Input is RGB image
- x = torch.randn(batch_size, 3, 224, 224, device=device, dtype=dtype)
+ x = torch.randn(batch_size, 3, 32, 48, device=device, dtype=dtype)
output = model(x)
assert output is not None
@@ -165,13 +165,13 @@ class TestSmallSRNetWrapper(BaseTester):
# SmallSRNetWrapper expects 3 channel RGB input, rgb_to_ycbcr will raise ValueError
with pytest.raises(ValueError, match="Input size must have a shape of"):
- x = torch.randn(1, 1, 224, 224, device=device, dtype=dtype)
+ x = torch.randn(1, 1, 16, 16, device=device, dtype=dtype)
model(x)
def test_exception_negative_values(self, device, dtype):
"""Test handling of invalid pixel value ranges (should still process but may produce unexpected results)."""
model = SmallSRNetWrapper(upscale_factor=3, pretrained=False).to(device, dtype)
- x = torch.randn(1, 3, 64, 64, device=device, dtype=dtype) - 1.0 # Negative values
+ x = torch.randn(1, 3, 32, 32, device=device, dtype=dtype) - 1.0 # Negative values
output = model(x)
# Should not crash, output should be finite
@@ -179,7 +179,7 @@ class TestSmallSRNetWrapper(BaseTester):
@pytest.mark.parametrize("upscale_factor", [2, 3, 4])
@pytest.mark.parametrize("batch_size", [1, 2, 4])
- @pytest.mark.parametrize("height,width", [(64, 64), (128, 128), (224, 224)])
+ @pytest.mark.parametrize("height,width", [(32, 32), (32, 48), (48, 32)])
def test_cardinality(self, device, dtype, upscale_factor, batch_size, height, width):
"""Test that output shape matches expected upscaled dimensions for RGB images."""
model = SmallSRNetWrapper(upscale_factor=upscale_factor, pretrained=False).to(device, dtype)
@@ -194,7 +194,7 @@ class TestSmallSRNetWrapper(BaseTester):
def test_feature_rgb_processing(self, device, dtype, upscale_factor):
"""Test that RGB images are processed correctly through color space conversions."""
model = SmallSRNetWrapper(upscale_factor=upscale_factor, pretrained=False).to(device, dtype)
- x = torch.rand(1, 3, 64, 64, device=device, dtype=dtype) # RGB in [0, 1]
+ x = torch.rand(1, 3, 32, 32, device=device, dtype=dtype) # RGB in [0, 1]
output = model(x)
# Check output is not all zeros
diff --git a/tests/models/test_tiny_vit.py b/tests/models/test_tiny_vit.py
index 479461400..529293bef 100644
--- a/tests/models/test_tiny_vit.py
+++ b/tests/models/test_tiny_vit.py
@@ -26,7 +26,10 @@ from testing.base import BaseTester
class TestTinyViT(BaseTester):
- @pytest.mark.parametrize("img_size", [224, 256])
+ # 128 is not a multiple of the 7-pixel attention window at any stage, so it takes the padded
+ # window-attention path; 224 divides evenly and takes the unpadded one. Both belong here: the
+ # only other coverage of the exact-multiple path is marked slow, which PR CI skips.
+ @pytest.mark.parametrize("img_size", [128, 224])
def test_smoke(self, device, dtype, img_size):
model = TinyViT(img_size=img_size).to(device=device, dtype=dtype)
data = torch.randn(1, 3, img_size, img_size, device=device, dtype=dtype)
diff --git a/tests/onnx/test_resize_onnx.py b/tests/onnx/test_resize_onnx.py
index 903b03cca..f9067982b 100644
--- a/tests/onnx/test_resize_onnx.py
+++ b/tests/onnx/test_resize_onnx.py
@@ -24,6 +24,9 @@ import torch
from kornia.geometry.transform import Resize
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
onnx = pytest.importorskip("onnx")
ort = pytest.importorskip("onnxruntime")
diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.py
index 1ca9345fb..1b1aa1942 100644
--- a/tests/onnx/test_sequential.py
+++ b/tests/onnx/test_sequential.py
@@ -17,6 +17,9 @@
import pytest
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
onnx = pytest.importorskip("onnx")
from kornia.onnx.sequential import ONNXSequential # noqa: E402
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index b7302bd1c..c191b7fca 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -20,6 +20,9 @@ import urllib
import pytest
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
onnx = pytest.importorskip("onnx")
from kornia.onnx.utils import ONNXLoader # noqa: E402
diff --git a/tests/test_conftest.py b/tests/test_conftest.py
index 23567b02d..ca4c95310 100644
--- a/tests/test_conftest.py
+++ b/tests/test_conftest.py
@@ -18,6 +18,7 @@
from __future__ import annotations
import types
+from pathlib import Path
import pytest
import torch
@@ -25,10 +26,47 @@ import torch
from conftest import _is_subprocess_isolated_test, skip_half_precision_on_cuda
pytest_plugins = ["pytester"]
+# Deliberately *not* marked device_agnostic. These are the runner's own regression tests, and
+# several of them guard accelerator-only entry points -- `test_isolated_skip_is_reported_with_
+# quiet_addopts` exists to protect `pixi run -e cuda test-cuda-half`. Marking the module would
+# deselect exactly the tests that command needs. They take no device fixture, so they run once
+# per session on any device matrix. `test_half_precision_isolation_probe` below is the one
+# exception, and is marked deliberately -- see its docstring.
_skip_fixture_fn = getattr(skip_half_precision_on_cuda, "__wrapped__", skip_half_precision_on_cuda)
[email protected](autouse=True)
+def _neutral_runner_env(monkeypatch):
+ """Keep the ambient run's runner flags out of the pytester subprocesses.
+
+ ``runpytest_subprocess`` inherits the environment, and both options below are
+ ``action="store_true"`` with their default read from an environment variable -- so once the
+ variable is exported there is no command line that turns the option back off. A developer
+ following TESTING.md and exporting ``KORNIA_TEST_RUN_DEVICE_AGNOSTIC=true`` for an
+ accelerator-only run would otherwise fail the very tests that document the escape hatch.
+ Each test below passes the flags it needs explicitly.
+ """
+ for var in ("KORNIA_TEST_ISOLATE_HALF", "KORNIA_TEST_RUN_DEVICE_AGNOSTIC"):
+ monkeypatch.delenv(var, raising=False)
+
+
+def test_half_precision_isolation_probe(device, dtype):
+ """Skip under half precision so the isolation runner has a child-side skip to report.
+
+ Support test for ``test_isolated_skip_is_reported_with_quiet_addopts`` below, which needs a
+ node that the parent collects and the subprocess skips. It lives here, next to its only
+ caller, rather than borrowing an unrelated suite's internal skip: under that coupling a dtype
+ fix somewhere else would break this file. The ``device_agnostic`` mark is load-bearing for the
+ same runner test -- it is what makes the parent and the child disagree about selection -- and
+ honest on its own terms, since the body never touches the device. Outside that runner test
+ this is a no-op that passes.
+ """
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("probe: skipped by design under half precision")
+
+
def _make_mock_item(params: dict | None, isolate: bool = True):
config = types.SimpleNamespace(
getoption=lambda opt, default=False: isolate if opt == "--isolate-half-precision" else default
@@ -169,7 +207,7 @@ class TestIntegrationLocalHalfPrecision:
)
# 1. CUDA + --dtype=float32 without --isolate-half-precision -> Must be SKIPPED
- result_cuda = pytester.runpytest_inprocess(
+ result_cuda = pytester.runpytest_subprocess(
"-p",
"conftest",
str(test_file),
@@ -181,7 +219,7 @@ class TestIntegrationLocalHalfPrecision:
result_cuda.assert_outcomes(skipped=1)
# 2. CPU + --dtype=float32 -> Must PASS
- result_cpu = pytester.runpytest_inprocess(
+ result_cpu = pytester.runpytest_subprocess(
"-p",
"conftest",
str(test_file),
@@ -191,3 +229,97 @@ class TestIntegrationLocalHalfPrecision:
"--dtype=float32",
)
result_cpu.assert_outcomes(passed=1)
+
+ def test_isolated_skip_is_reported_with_quiet_addopts(self, pytester, monkeypatch):
+ """The isolation parent must not turn a child's skip into a pass when addopts is quiet.
+
+ ``-o addopts=-q`` on the parent command line is not inherited by the child, so it cannot
+ reproduce the failure; ``PYTEST_ADDOPTS`` is. pytester clears that variable at fixture
+ setup, so it has to be set here, in the test body.
+
+ ``--device=cpu,cuda`` also pins the second way the child can come back empty. The probe is
+ marked ``device_agnostic``; with CPU in the matrix the parent keeps it, but the child is
+ handed a bare ``--device=cuda``, under which the deselection rule fires unless the parent
+ forwards ``--run-device-agnostic``. Both legs skip here, hence ``skipped=2``.
+ """
+ monkeypatch.setenv("PYTEST_ADDOPTS", "-q")
+ node_id = f"{Path(__file__)}::test_half_precision_isolation_probe"
+ result = pytester.runpytest_subprocess(
+ node_id,
+ "--device=cpu,cuda",
+ "--dtype=float16",
+ "--isolate-half-precision",
+ "-rs",
+ )
+ result.assert_outcomes(skipped=2)
+ # The count on its own does not prove the child ran: `pytest_runtest_protocol` also maps
+ # the child's exit code 5 ("no tests collected") onto a skip, so a node the parent collects
+ # but the child parametrises away would satisfy the count while proving nothing. Deleting
+ # or renaming the node is caught by the count already (the parent reports 0 outcomes), but
+ # a divergence between parent and child collection is not. `-rs` puts the synthetic
+ # report's reason in the summary, so require the skip to be the child's own.
+ result.stdout.no_fnmatch_line("*no tests collected*")
+
+
+class TestDeviceAgnosticSelection:
+ def test_device_agnostic_tests_run_once_in_cpu_containing_matrix(self, pytester):
+ test_file = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.device_agnostic
+ def test_device_agnostic():
+ assert True
+
+ def test_unmarked():
+ assert True
+ """
+ )
+
+ result_cpu = pytester.runpytest_subprocess(
+ "-p",
+ "conftest",
+ str(test_file),
+ "-o",
+ "testpaths=.",
+ "--device=cpu",
+ "--dtype=float32",
+ )
+ result_cpu.assert_outcomes(passed=2)
+
+ result_cuda = pytester.runpytest_subprocess(
+ "-p",
+ "conftest",
+ str(test_file),
+ "-o",
+ "testpaths=.",
+ "--device=cuda",
+ "--dtype=float32",
+ )
+ result_cuda.assert_outcomes(passed=1, deselected=1)
+
+ def test_run_device_agnostic_overrides_the_deselection(self, pytester):
+ test_file = pytester.makepyfile(
+ """
+ import pytest
+
+ @pytest.mark.device_agnostic
+ def test_device_agnostic():
+ assert True
+
+ def test_unmarked():
+ assert True
+ """
+ )
+
+ result = pytester.runpytest_subprocess(
+ "-p",
+ "conftest",
+ str(test_file),
+ "-o",
+ "testpaths=.",
+ "--device=cuda",
+ "--dtype=float32",
+ "--run-device-agnostic",
+ )
+ result.assert_outcomes(passed=2)