🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Half-precision (float16 / bfloat16) support and test infrastructure (#3647)
Dmytro Mishkin97f5ae11de81
diff --git a/README.md b/README.mdindex 540cb209a..58092379e 100644--- a/README.md+++ b/README.md@@ -75,6 +75,43 @@ Leverage pre-trained AI models optimized for a variety of vision tasks, all with</details>+## Half-Precision Support++| Module | float16 | bfloat16 | Notes |+|--------|:-------:|:--------:|-------|+| `kornia.color` | ⚠️ | ⚠️ | Most conversions work for both; FFT-based ops may fail |+| `kornia.filters` | ⚠️ | ⚠️ | Basic filters work; FFT-based ops may fail on CUDA |+| `kornia.enhance` | ⚠️ | ⚠️ | Histogram eq / gamma / ZCA work (linalg ops use cast helpers) |+| `kornia.morphology` | ✅ | ✅ | Pure conv/pool ops; no dtype restrictions |+| `kornia.augmentation` | ⚠️ | ⚠️ | Most ops work; precision-sensitive transforms may be inaccurate |+| `kornia.geometry.transform` | ⚠️ | ⚠️ | Affine/warp/resize work via cast helpers; thin-plate spline may fail |+| `kornia.geometry.camera` | ⚠️ | ⚠️ | Pinhole model and most camera ops work; `StereoCamera` accepts both |+| `kornia.geometry.calibration` | ❌ | ❌ | Explicitly accepts float32/float64 only (PnP solver) |+| `kornia.geometry.epipolar` | ⚠️ | ⚠️ | SVD/inverse use cast helpers; both dtypes work |+| `kornia.geometry.homography` | ⚠️ | ⚠️ | Uses `_torch_svd_cast` — both dtypes work via casting |+| `kornia.geometry.liegroup` | ⚠️ | ⚠️ | Most ops work via cast helpers; some linalg paths may fail |+| `kornia.geometry.solvers` | ⚠️ | ⚠️ | Uses `_torch_solve_cast` — both dtypes work via casting |+| `kornia.geometry.subpix` | ⚠️ | ⚠️ | Soft-argmax works; precision-sensitive ops may be inaccurate |+| `kornia.losses` | ⚠️ | ⚠️ | Photometric losses work; linalg-based losses may not |+| `kornia.feature` | ⚠️ | ⚠️ | Detectors/descriptors work; matching uses manual cdist fallback |+| `kornia.metrics` | ⚠️ | ⚠️ | Pixel-level metrics work; linalg-based metrics may not |+| `kornia.models` | ⚠️ | ⚠️ | Conv-based models work; attention-based models may have dtype mismatches |++✅ Supported ⚠️ Partial ❌ Not supported++**Test results** (commit `6131e98`, 2026-03-21):++| Run | Passed | Failed | Skipped | Pass% |+|-----|-------:|-------:|--------:|------:|+| CPU float32 *(baseline)* | 7647 | 3 | 3269 | **99.9%** |+| CUDA float32 *(baseline)* | 7634 | 3 | 3280 | **99.9%** |+| CPU float16 | 6866 | 747 | 3306 | **90.1%** |+| CPU bfloat16 | 6838 | 812 | 3269 | **89.3%** |+| CUDA float16 *(KORNIA_TEST_IN_SUBPROCESS=1)* | 6727 | 643 | 3556 | **91.3%** |+| CUDA bfloat16 *(KORNIA_TEST_IN_SUBPROCESS=1)* | 6695 | 713 | 3518 | **90.4%** |++See the [full precision guide](https://kornia.readthedocs.io/en/stable/get-started/precision.html) for details.+## SponsorshipKornia is an open-source project that is developed and maintained by volunteers. Whether you're using it for research or commercial purposes, consider sponsoring or collaborating with us. Your support will help ensure Kornia's growth and ongoing innovation. Reach out to us today and be a part of shaping the future of this exciting initiative!diff --git a/TESTING.md b/TESTING.mdindex 0b7035dbb..bff0a5a4b 100644--- a/TESTING.md+++ b/TESTING.md@@ -35,6 +35,7 @@ pixi run test-quick| `--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 |+| `--isolate-half-precision` | `KORNIA_TEST_ISOLATE_HALF` | off | Run float16/bfloat16 CUDA tests each in a fresh `subprocess.run` process (no shared CUDA state) |## Test Structure@@ -187,7 +188,51 @@ If you write a new function that calls SVD, use `_torch_svd_cast` rather than ca----### 7. MPS (Apple Silicon) Limitations+### 7. Half-Precision dtypes (float16 / bfloat16)++**What it is.** float16 and bfloat16 have limited support across PyTorch and kornia:++- **bfloat16**: Many kornia functions explicitly reject it. In addition, many CUDA kernels lack bfloat16 implementations (`svd_cuda`, `linalg_eigh_cuda`, `cdist_cuda`, `lu_factor_cublas`, `geqrf_cuda`, etc.).+- **float16**: PyTorch's `linalg` routines (`linalg.inv`, `linalg.eigh`, `linalg.svd`, …) do not accept float16 on CPU (`RuntimeError: Low precision dtypes not supported`). On CUDA, many kernels trigger device-side asserts for float16 inputs.++**Testing strategy: isolated runs.** Half-precision tests live alongside their float32/float64 counterparts in the same directories and files. They are **not** run in combined (`--dtype=all`) invocations on CUDA; instead, half-precision and standard-precision suites are run as separate, isolated pytest invocations:++```bash+# Standard CI — all devices, float32 and float64 only+pixi run test tests/ --dtype=float32,float64++# Half-precision — run separately, per directory or file+pytest tests/color/ --dtype=float16,bfloat16+pytest tests/geometry/ --dtype=float16,bfloat16 --device=cuda+```++Keeping the runs separate means a half-precision failure or CUDA context corruption cannot affect the float32/float64 results.++**CUDA device-side asserts and test contamination.** CUDA kernel errors are *asynchronous*: a failing kernel logs the error but continues execution until the next host–device synchronisation point. If that sync happens inside a *different* (passing) test, that test fails spuriously. Once a device-side assert fires, the CUDA context is permanently broken for the process lifetime.++The root `conftest.py` contains two autouse fixtures to handle this:++- **`skip_half_precision_on_cuda`** — *skips* float16 and bfloat16 tests on CUDA when tests are run in combined mode. Skipping means no CUDA kernel is launched, so no assert can be triggered. On CPU/MPS/TPU, tests run as normal (they may fail).++- **`cuda_device_assert_guard`** — synchronises the CUDA device *before* each CUDA test. If the context is already corrupted by a previous test, the current test is *skipped* rather than allowed to fail spuriously. After each CUDA test, a second synchronisation drains the queue so that any async error surfaces in teardown of the test that caused it, not at the start of the next one.++**Running half-precision tests across a whole directory.** Use `--isolate-half-precision`. Each float16/bfloat16 CUDA test is run in a completely fresh Python process via `subprocess.run`, so a device-side assert in one test cannot affect any other test — there is no shared CUDA state at all:++```bash+# Whole directory, fully isolated — results reported normally (pass/fail per test)+pytest tests/color/ --device=cuda --dtype=bfloat16 --isolate-half-precision+pytest tests/geometry/ --device=cuda --dtype=all --isolate-half-precision++# Via pixi tasks+pixi run test-half # float16 + bfloat16, CPU+pixi run test-cuda-half # float16 + bfloat16, CUDA, with isolation+```++Without `--isolate-half-precision`, float16/bfloat16 CUDA tests are **skipped** (safe default for combined runs).++**See also.** `docs/source/get-started/precision.rst` for the per-module half-precision support table.++### 8. MPS (Apple Silicon) Limitations**What MPS is.** The `mps` device uses Apple's Metal Performance Shaders backend. Run tests against it with `--device=mps`.diff --git a/conftest.py b/conftest.pyindex 21c3ce3be..43e2387df 100644--- a/conftest.py+++ b/conftest.py@@ -16,6 +16,9 @@#import os+import subprocess+import sys+import timefrom functools import partialfrom itertools import product@@ -23,6 +26,11 @@ import numpy as npimport pytestimport torch+try:+ from pytest import TestReport # public since pytest 7.x+except ImportError: # pragma: no cover+ from _pytest.reports import TestReport # type: ignore[no-redef]+import korniatry:@@ -251,6 +259,18 @@ def pytest_addoption(parser):"(env: KORNIA_TEST_TF32)"),)+ parser.addoption(+ "--isolate-half-precision",+ action="store_true",+ default=os.environ.get("KORNIA_TEST_ISOLATE_HALF", "false").lower() == "true",+ help=(+ "Run float16/bfloat16 CUDA tests in fresh subprocesses via subprocess.run. "+ "Each test gets its own Python process with no shared CUDA state, so a "+ "device-side assert cannot contaminate subsequent tests. "+ "Without this flag, float16/bfloat16 CUDA tests are skipped. "+ "(env: KORNIA_TEST_ISOLATE_HALF)"+ ),+ )def _setup_torch_compile() -> None:@@ -282,13 +302,16 @@ def pytest_sessionstart(session):if session.config.getoption("--tf32"):torch.set_float32_matmul_precision("high")- try:- _setup_torch_compile()- except RuntimeError as ex:- if "not yet supported for torch.compile" not in str(- ex- ) and "Dynamo is not supported on Python 3.12+" not in str(ex):- raise ex+ # Skip torch.compile warmup in subprocess mode — it adds startup overhead and+ # pollutes the captured output used for failure reporting in pytest_runtest_protocol.+ if not os.environ.get("KORNIA_TEST_IN_SUBPROCESS"):+ try:+ _setup_torch_compile()+ except RuntimeError as ex:+ if "not yet supported for torch.compile" not in str(+ ex+ ) and "Dynamo is not supported on Python 3.12+" not in str(ex):+ raise exos.makedirs(WEIGHTS_CACHE_DIR, exist_ok=True)torch.hub.set_dir(WEIGHTS_CACHE_DIR)@@ -385,6 +408,234 @@ model weights cached: {cached_weights}"""+def _extract_failure_output(output: str) -> str:+ """Return just the FAILURES/ERRORS section from pytest stdout, or full output as fallback."""+ import re++ m = re.search(r"^=+ (FAILURES|ERRORS) =+", output, re.MULTILINE)+ if m:+ return output[m.start() :].strip()+ return output.strip()+++def _is_subprocess_isolated_test(item) -> bool:+ """Return True if this test should be run in a fresh subprocess.++ Checks that:+ - ``--isolate-half-precision`` is set+ - we are NOT already inside a subprocess (``KORNIA_TEST_IN_SUBPROCESS`` env var)+ - the test is parametrised with a half-precision dtype on CUDA+ """+ if os.environ.get("KORNIA_TEST_IN_SUBPROCESS"):+ return False+ if not item.config.getoption("--isolate-half-precision", default=False):+ return False+ callspec = getattr(item, "callspec", None)+ if callspec is None:+ return False+ params = callspec.params+ if params.get("dtype_name") not in ("float16", "bfloat16"):+ return False+ if params.get("device_name") != "cuda":+ return False+ return True+++def pytest_runtest_protocol(item, nextitem):+ """Run float16/bfloat16 CUDA tests in a fresh subprocess for true isolation.++ ``pytest-forked`` uses ``fork()``, which copies the parent's CUDA context handle+ into the child. A device-side assert in the child corrupts the *same* underlying+ GPU state the parent holds — so the isolation is illusory for CUDA float16.++ This hook uses ``subprocess.run`` instead, which spawns a completely independent+ Python interpreter with no shared CUDA state. The child's result (pass / fail /+ skip) is parsed and reported back into the parent's session as a synthetic+ ``TestReport``.+ """+ if not _is_subprocess_isolated_test(item):+ return None # use the default protocol++ item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)++ # Forward device/dtype so pytest_generate_tests in the subprocess produces the+ # same parametrisation as the parent — without these the [cuda-float16] nodeid+ # can't be found because the subprocess defaults to [cpu-float32].+ params = item.callspec.params+ device_name = params.get("device_name", "cpu")+ dtype_name = params.get("dtype_name", "float32")+ cmd = [+ sys.executable,+ "-m",+ "pytest",+ item.nodeid,+ "--no-header",+ "--tb=short",+ "-q",+ "--color=no",+ f"--device={device_name}",+ f"--dtype={dtype_name}",+ ]+ if item.config.getoption("--runslow"):+ cmd.append("--runslow")+ if item.config.getoption("--tf32"):+ cmd.append("--tf32")+ optimizer_backend = params.get("optimizer_backend")+ if optimizer_backend:+ cmd.append(f"--optimizer={optimizer_backend}")++ env = {**os.environ, "KORNIA_TEST_IN_SUBPROCESS": "1"}+ t0 = time.monotonic()+ proc = subprocess.run( # noqa: S603+ cmd, capture_output=True, text=True, cwd=str(item.config.rootdir), env=env, check=False+ )+ duration = time.monotonic() - t0+ output = (proc.stdout + proc.stderr).strip()++ # exit code 5 → no tests collected (test was deselected or already parametrised away)+ if proc.returncode == 5:+ outcome: str = "skipped"+ longrepr = ("", 0, "subprocess: no tests collected")+ elif proc.returncode == 0:+ # Distinguish a genuine pass from a skipped test+ if "passed" not in output and "skipped" in output:+ skip_line = next(+ (ln.strip() for ln in output.splitlines() if "SKIP" in ln.upper()), "skipped in subprocess"+ )+ outcome = "skipped"+ longrepr = ("", 0, skip_line)+ else:+ outcome = "passed"+ longrepr = None+ else:+ outcome = "failed"+ longrepr = _extract_failure_output(output)++ def _report(when: str, out: str, rep_longrepr, dur: float = 0.0) -> TestReport:+ return TestReport(+ nodeid=item.nodeid,+ location=item.location,+ keywords=dict(item.keywords),+ outcome=out,+ longrepr=rep_longrepr,+ when=when,+ duration=dur,+ )++ for rep in [+ _report("setup", "passed", None),+ _report("call", outcome, longrepr, duration),+ _report("teardown", "passed", None),+ ]:+ item.ihook.pytest_runtest_logreport(report=rep)++ item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)+ return True++[email protected](autouse=True)+def skip_half_precision_on_cuda(request):+ """Skip float16/bfloat16 CUDA tests unless running inside a subprocess.++ CUDA device-side asserts are asynchronous: a failing half-precision kernel does not+ raise immediately but corrupts the CUDA context until the next synchronisation point,+ which may be inside a completely different (float32) test. Once triggered, the+ context is permanently broken for the process — all subsequent CUDA ops fail.++ Default behaviour (no flag): float16/bfloat16 CUDA tests are *skipped*.++ With ``--isolate-half-precision`` (or ``KORNIA_TEST_ISOLATE_HALF=true``): each+ float16/bfloat16 CUDA test is intercepted by ``pytest_runtest_protocol`` *before*+ any fixture runs and executed in a fresh ``subprocess.run`` process. This fixture+ only runs inside those subprocesses (where ``KORNIA_TEST_IN_SUBPROCESS=1`` is set)+ and exits immediately so the test proceeds normally.++ Usage::++ pytest tests/color/ --device=cuda --dtype=bfloat16 --isolate-half-precision+ pytest tests/ --device=cuda --dtype=all --isolate-half-precision+ """+ # Inside a subprocess spawned by pytest_runtest_protocol — run the test normally.+ if os.environ.get("KORNIA_TEST_IN_SUBPROCESS"):+ return++ if "dtype" not in request.fixturenames:+ return+ dtype = request.getfixturevalue("dtype")+ if dtype not in (torch.bfloat16, torch.float16):+ return+ if "device" not in request.fixturenames:+ return++ try:+ device = request.getfixturevalue("device")+ except pytest.FixtureLookupError:+ return++ if device.type != "cuda":+ return++ if not request.config.getoption("--isolate-half-precision"):+ dtype_name = "bfloat16" if dtype == torch.bfloat16 else "float16"+ pytest.skip(+ f"{dtype_name} on CUDA: skipped by default to prevent device-side assert contamination. "+ "Run with --isolate-half-precision to execute in isolated subprocesses."+ )++[email protected](autouse=True)+def cuda_device_assert_guard(request):+ """Guard against CUDA device-side assert contamination between tests.++ Active only when running inside a subprocess (``KORNIA_TEST_IN_SUBPROCESS=1``)+ or with ``--isolate-half-precision``, so regular float32 CI is not slowed+ down by the extra host-device synchronisations.++ This fixture synchronises CUDA before each test; if the context is already+ corrupted the test is skipped rather than allowed to fail spuriously.+ After each test a second synchronisation drains the queue so any async+ device-side assert surfaces in the test that caused it, not the next one.+ If a device-side assert is detected in the post-test sync the test is+ failed (not silently passed) so asynchronous errors are always visible.+ """+ in_subprocess = os.environ.get("KORNIA_TEST_IN_SUBPROCESS")+ isolate = request.config.getoption("--isolate-half-precision", default=False)+ if not (in_subprocess or isolate):+ yield+ return++ if "device" not in request.fixturenames:+ yield+ return++ try:+ device = request.getfixturevalue("device")+ except pytest.FixtureLookupError:+ yield+ return++ if device.type != "cuda":+ yield+ return++ # Pre-test: verify the CUDA context is healthy.+ try:+ torch.cuda.synchronize(device)+ except RuntimeError:+ pytest.skip("CUDA context corrupted by a device-side assert in a previous test; run this test in isolation")++ yield++ # Post-test: drain the CUDA queue so any async device-side assert surfaces here,+ # in the test that caused it, rather than at the start of the next test.+ # Fail the test if a device-side assert is detected so it is not silently passed.+ try:+ torch.cuda.synchronize(device)+ except RuntimeError as exc:+ torch.cuda.empty_cache()+ pytest.fail(f"CUDA device-side assert triggered during this test: {exc}")++@pytest.fixture(autouse=True)def add_doctest_deps(doctest_namespace):"""Add dependencies for doctests."""diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstnew file mode 100644index 000000000..c24b00b7f--- /dev/null+++ b/docs/source/get-started/precision.rst@@ -0,0 +1,202 @@+Half-Precision Support+======================++This page documents which kornia modules support half-precision floating-point dtypes+(``torch.float16`` and ``torch.bfloat16``) and what limitations to expect.++.. list-table:: Half-Precision Support by Module+ :header-rows: 1+ :widths: 28 14 14 44++ * - Module+ - float16+ - bfloat16+ - Notes+ * - ``kornia.color``+ - ⚠️ Partial+ - ⚠️ Partial+ - Most color space conversions work for both half-precision dtypes.+ FFT-based operations may fail on CUDA.+ * - ``kornia.filters``+ - ⚠️ Partial+ - ⚠️ Partial+ - Basic convolution-based filters (Gaussian, Sobel, Median, Box) work+ for both dtypes. FFT-based operations (``fft_conv``) may fail on CUDA.+ * - ``kornia.enhance``+ - ⚠️ Partial+ - ⚠️ Partial+ - Histogram equalization, CLAHE, gamma correction, and ZCA whitening work+ for both dtypes. ZCA linalg ops go through ``_torch_svd_cast`` /+ ``_torch_inverse_cast`` which promote to float32 before computing.+ * - ``kornia.morphology``+ - ✅ Yes+ - ✅ Yes+ - Uses only convolution and pooling; no dtype restrictions.+ * - ``kornia.augmentation``+ - ⚠️ Partial+ - ⚠️ Partial+ - Both dtypes are accepted by ``validate_tensor``. Most ops work;+ precision-sensitive transforms (e.g. affine with large rotations) may+ produce inaccurate results at half precision.+ * - ``kornia.geometry.transform``+ - ⚠️ Partial+ - ⚠️ Partial+ - Affine, homography, resize, and warp operations use ``_torch_inverse_cast``+ / ``_torch_solve_cast`` which promote to float32 and cast back;+ both dtypes work.+ * - ``kornia.geometry.camera``+ - ⚠️ Partial+ - ⚠️ Partial+ - Pinhole camera model and most projection ops work for both dtypes.+ ``StereoCamera`` accepts both float16 and bfloat16.+ * - ``kornia.geometry.calibration``+ - ❌ No+ - ❌ No+ - ``solve_pnp_dlt()`` explicitly checks that inputs are ``float32`` or+ ``float64`` and raises otherwise.+ * - ``kornia.geometry.epipolar``+ - ⚠️ Partial+ - ⚠️ Partial+ - SVD and solve operations use ``_torch_svd_cast`` / ``_torch_solve_cast``+ / ``_torch_inverse_cast``; both dtypes work via casting to float32.+ * - ``kornia.geometry.homography``+ - ⚠️ Partial+ - ⚠️ Partial+ - Uses ``_torch_svd_cast``; both dtypes are promoted to float32 before SVD+ and the result is cast back.+ * - ``kornia.geometry.liegroup``+ - ⚠️ Partial+ - ⚠️ Partial+ - Most rotation/translation operations (SO2, SO3, SE2, SE3) work for both+ dtypes via cast helpers. A few code paths may still fail.+ * - ``kornia.geometry.solvers``+ - ⚠️ Partial+ - ⚠️ Partial+ - RANSAC-based solvers use ``_torch_solve_cast``; both dtypes are promoted+ before the solve and the result is cast back.+ * - ``kornia.geometry.subpix``+ - ⚠️ Partial+ - ⚠️ Partial+ - Soft-argmax and weighted softmax work for both dtypes.+ Precision-sensitive ops may produce inaccurate results.+ * - ``kornia.losses``+ - ⚠️ Partial+ - ⚠️ Partial+ - Photometric losses (SSIM, PSNR, MS-SSIM) work for both dtypes.+ Losses based on linalg operations (Hausdorff, etc.) may not.+ * - ``kornia.feature``+ - ⚠️ Partial+ - ⚠️ Partial+ - Local feature detectors and descriptors (SIFT, HardNet, DISK, DeDoDe)+ work for inference. Feature *matching* uses a manual ``cdist`` fallback+ for both half-precision dtypes on CUDA.+ * - ``kornia.metrics``+ - ⚠️ Partial+ - ⚠️ Partial+ - Simple pixel-level metrics work for both dtypes. Metrics involving linalg+ operations may not.+ * - ``kornia.models``+ - ⚠️ Partial+ - ⚠️ Partial+ - Conv-based models work for both dtypes. Attention-based models (e.g.+ VLMs, ViTs) may have internal dtype mismatches.++Legend+------++- ✅ **Yes** — Works correctly; results are accurate at the given precision.+- ⚠️ **Partial** — Some operations work; others fail at runtime or produce inaccurate results due to limited numerical range/precision.+- ❌ **No** — Not supported; raises a ``RuntimeError`` or ``TypeError`` at runtime (explicit dtype check in the implementation).++Test Results+------------++Measured on commit ``6131e98`` (2026-03-21), full test suite (no ``--runslow``).+Pass% = passed ÷ (passed + failed); skipped and xfailed tests are excluded.++.. list-table::+ :header-rows: 1+ :widths: 32 10 10 10 10++ * - Run+ - Passed+ - Failed+ - Skipped+ - Pass%+ * - CPU float32 *(baseline)*+ - 7647+ - 3+ - 3269+ - **99.9%**+ * - CUDA float32 *(baseline)*+ - 7634+ - 3+ - 3280+ - **99.9%**+ * - CPU float16+ - 6866+ - 747+ - 3306+ - **90.1%**+ * - CPU bfloat16+ - 6838+ - 812+ - 3269+ - **89.3%**+ * - CUDA float16 *(KORNIA_TEST_IN_SUBPROCESS=1)*+ - 6727+ - 643+ - 3556+ - **91.3%**+ * - CUDA bfloat16 *(KORNIA_TEST_IN_SUBPROCESS=1)*+ - 6695+ - 713+ - 3518+ - **90.4%**++.. note::++ CUDA half-precision tests are measured using ``KORNIA_TEST_IN_SUBPROCESS=1``+ which bypasses the ``skip_half_precision_on_cuda`` fixture. Each test then+ runs in the same process but with the ``cuda_device_assert_guard`` fixture+ synchronising CUDA before and after each test. For full isolation the current+ implementation uses ``subprocess.run`` for true process isolation; a fresh+ ``--isolate-half-precision`` flag spawns each test in a fresh ``subprocess.run``+ process with no shared CUDA state.++Test Suite Behaviour+--------------------++Half-precision tests live in the same directories and files as their+float32/float64 counterparts. They are run as **separate, isolated pytest+invocations** rather than being mixed into a combined ``--dtype=all`` run.+This prevents a CUDA device-side assert in a half-precision test from+corrupting the CUDA context and causing unrelated float32 tests to fail.++.. code-block:: bash++ # Standard precision — default CI+ pixi run test tests/ --dtype=float32,float64++ # Half-precision — run in isolation, per directory+ pytest tests/color/ --dtype=float16,bfloat16+ pytest tests/geometry/ --dtype=float16,bfloat16 --device=cuda++Two autouse fixtures in the root ``conftest.py`` enforce safe behaviour:++- **``skip_half_precision_on_cuda``** — skips float16/bfloat16 tests on CUDA+ in combined runs so no half-precision kernel is ever launched (and therefore+ no device-side assert can fire).+- **``cuda_device_assert_guard``** — synchronises CUDA before and after each+ CUDA test to catch async device-side assert errors in the test that caused+ them, not in the next one. If the context is already corrupted, the test+ is skipped rather than allowed to fail spuriously.++With ``--isolate-half-precision``, each float16/bfloat16 CUDA test is+intercepted by a custom ``pytest_runtest_protocol`` hook and executed in a+completely fresh Python process via ``subprocess.run``. There is no shared+CUDA context between tests, so a device-side assert in one test cannot affect+any other.++See ``TESTING.md`` in the repository root for a full description of the+contamination mechanism and fixture implementation.diff --git a/docs/source/index.rst b/docs/source/index.rstindex be1e6c528..95698325d 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -93,6 +93,7 @@ Join the communityget-started/introductionget-started/highlightsget-started/installation+ get-started/precisionget-started/aboutTutorials <https://kornia.github.io/tutorials/>get-started/multi-framework-supportdiff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 8ff63b54b..925375bae 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -48,7 +48,7 @@ class AugmentationBase2D(_AugmentationBase):def validate_tensor(self, input: torch.Tensor) -> None:"""Check if the input torch.Tensor is formatted as expected."""- _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])if len(input.shape) != 4:raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")@@ -56,7 +56,7 @@ class AugmentationBase2D(_AugmentationBase):self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True) -> torch.Tensor:"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""- _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])if shape is None:return _transform_input(input)diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex 044c0f8f0..9ab5a8552 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -66,7 +66,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True) -> torch.Tensor:"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64])if shape is None:return _transform_input(input)diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.pyindex 62faad973..204c6f5b5 100644--- a/kornia/augmentation/_2d/mix/transplantation.py+++ b/kornia/augmentation/_2d/mix/transplantation.py@@ -325,7 +325,9 @@ class RandomTransplantation(MixAugmentationBaseV2):output: torch.Tensorif dcate == DataKey.INPUT:- _validate_input_dtype(_input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ _validate_input_dtype(+ _input, accepted_dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64]+ )applied = self.transform_input(acceptor, donor, self._params["selection"])output = self.apply_non_transform(_input, self._params, self.flags)diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.pyindex be716fc7b..ed4e4a868 100644--- a/kornia/augmentation/_3d/base.py+++ b/kornia/augmentation/_3d/base.py@@ -41,7 +41,7 @@ class AugmentationBase3D(_AugmentationBase):def validate_tensor(self, input: torch.Tensor) -> None:"""Check if the input torch.Tensor is formatted as expected."""- _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])if len(input.shape) != 5:raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")@@ -49,7 +49,7 @@ class AugmentationBase3D(_AugmentationBase):self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = True) -> torch.Tensor:"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""- _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])if shape is None:return _transform_input3d(input)else:diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex de017f719..017326570 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -43,7 +43,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")_validate_shape(input.shape, required_shapes=("BCHW",))- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64])return f(input, *args, **kwargs)@@ -69,7 +69,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:input_shape = len(input.shape)if input_shape != 5:raise AssertionError(f"Expect input of 5 dimensions, got {input_shape} instead")- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ _validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64])return f(input, *args, **kwargs)diff --git a/kornia/color/colormap.py b/kornia/color/colormap.pyindex e83520367..bebb6d0f1 100644--- a/kornia/color/colormap.py+++ b/kornia/color/colormap.py@@ -219,7 +219,16 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.TensKORNIA_CHECK(isinstance(input_tensor, torch.Tensor), f"`input_tensor` must be a torch.Tensor. Got: {type(input_tensor)}")- valid_types = [torch.half, torch.float, torch.double, torch.uint8, torch.int, torch.long, torch.short]+ valid_types = [+ torch.bfloat16,+ torch.half,+ torch.float,+ torch.double,+ torch.uint8,+ torch.int,+ torch.long,+ torch.short,+ ]KORNIA_CHECK(input_tensor.dtype in valid_types, f"`input_tensor` must be a {valid_types}. Got: {input_tensor.dtype}")diff --git a/kornia/color/gray.py b/kornia/color/gray.pyindex d3ddcf044..991614f5b 100644--- a/kornia/color/gray.py+++ b/kornia/color/gray.py@@ -88,7 +88,7 @@ def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] =if image.dtype == torch.uint8:rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8)# floating point images- elif image.dtype in (torch.float16, torch.float32, torch.float64):+ elif image.dtype in (torch.bfloat16, torch.float16, torch.float32, torch.float64):rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)else:raise TypeError(f"Unknown data type: {image.dtype}")diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex 8809efbf8..94bc7b9a2 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -107,7 +107,7 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:q: torch.Tensor = v * (1.0 - f * s)t: torch.Tensor = v * (1.0 - (1.0 - f) * s)- hi = hi.long()+ hi = hi.long().clamp_(0, 5)indices: torch.Tensor = torch.stack([hi, hi + 6, hi + 12], dim=-3)out = torch.stack((v, q, p, p, t, v, t, v, v, q, p, p, p, p, t, v, v, q), dim=-3)out = torch.gather(out, -3, indices)diff --git a/kornia/core/check.py b/kornia/core/check.pyindex e1d5d21f6..1fc5e82e5 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -693,7 +693,7 @@ def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: boamin, amax = torch.aminmax(x)- if x.dtype in (float16, float32, float64):+ if x.dtype in (torch.bfloat16, float16, float32, float64):invalid = (amin < 0) | (amax > 1)else:max_int_value = (1 << bits) - 1diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex 7637c8b95..3bbf50bab 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -20,6 +20,8 @@ from typing import List, Optional, Tupleimport torchfrom torch import nn+from kornia.core.utils import _torch_svd_cast+__all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"]@@ -258,7 +260,7 @@ def zca_mean(else:cov = cov / float(N)- U, S, _ = torch.linalg.svd(cov)+ U, S, _ = _torch_svd_cast(cov)S = S.reshape(-1, 1)S_inv_root: torch.Tensor = torch.rsqrt(S + eps)diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 9a9014880..0f800c531 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -161,10 +161,15 @@ def _affine_from_cov(cov: torch.Tensor) -> torch.Tensor:Affine matrices ``(N, 2, 2)``."""# eigh returns eigenvalues sorted ascending; columns of eigenvectors are evecs.+ # torch.linalg.eigh is not implemented for float16/bfloat16 on CUDA, so promote+ # to float32 and cast the result back.+ orig_dtype = cov.dtype+ if cov.dtype in (torch.float16, torch.bfloat16):+ cov = cov.float()eigenvalues, eigenvectors = torch.linalg.eigh(cov)scales = eigenvalues.clamp(min=1e-8).sqrt() # (N, 2)# Each column of eigenvectors multiplied by the corresponding scale.- return eigenvectors * scales[:, None, :] # (N, 2, 2)+ return (eigenvectors * scales[:, None, :]).to(orig_dtype) # (N, 2, 2)def _laf_from_kpts_and_affine(@@ -880,6 +885,7 @@ class ALIKED(nn.Module):self,img: torch.Tensor,mask: Optional[torch.Tensor] = None,+ compute_affine: bool = True,) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""Detect and describe local features, returning results in kornia LAF format.@@ -897,6 +903,11 @@ class ALIKED(nn.Module):``[0, 1]``; the score map is multiplied by this mask beforekeypoint detection so that features are suppressed in maskedregions.+ compute_affine: if ``True`` (default), estimate the 2x2 affine shape+ of each LAF using ``torch.linalg.eigh`` on the soft-argmax+ covariance. Set to ``False`` to skip the eigendecomposition and+ return identity affines, which is faster and avoids the linalg+ call entirely (useful when only keypoint positions are needed).Returns:- Detected local affine frames with shape :math:`(B,N,2,3)`.@@ -911,11 +922,17 @@ class ALIKED(nn.Module):if mask is not None:# Resize mask to score map resolution and apply.- mask_rs = F.interpolate(mask.float(), size=score_map.shape[-2:], mode="bilinear", align_corners=True)+ mask_rs = F.interpolate(+ mask.to(score_map.dtype), size=score_map.shape[-2:], mode="bilinear", align_corners=True+ )score_map = score_map * mask_rs- dkd_out = self.dkd(score_map, return_affine=True)- keypoints, kptscores, _scoredispersitys, local_affines = dkd_out # type: ignore[misc]+ dkd_out = self.dkd(score_map, return_affine=compute_affine)+ if compute_affine:+ keypoints, kptscores, _scoredispersitys, local_affines = dkd_out # type: ignore[misc]+ else:+ keypoints, kptscores, _scoredispersitys = dkd_out # type: ignore[misc]+ local_affines = Nonedescriptors, _offsets = self.desc_head(feature_map, keypoints)B, _, H, W = img.shape@@ -924,7 +941,13 @@ class ALIKED(nn.Module):lafs_list: list[torch.Tensor] = []for i in range(B):kps_px = wh * (keypoints[i] + 1) / 2.0 # (N, 2)- laf_i = _laf_from_kpts_and_affine(kps_px, local_affines[i]) # (N, 2, 3)+ if local_affines is not None:+ affine_i = local_affines[i]+ else:+ # Identity affine: both axes are unit-scale, no rotation.+ n = kps_px.shape[0]+ affine_i = torch.eye(2, device=img.device, dtype=img.dtype).unsqueeze(0).expand(n, -1, -1)+ laf_i = _laf_from_kpts_and_affine(kps_px, affine_i) # (N, 2, 3)lafs_list.append(laf_i)# Pad to the maximum number of keypoints in the batch.diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex e995a3951..bcce01678 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -30,8 +30,15 @@ from .adalam import get_adalam_default_config, match_adalamdef _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:- r"""Manual `torch.cdist` for M1."""- if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)):+ r"""Compute pairwise L2 distances between rows of d1 and d2.++ Uses ``torch.cdist`` for float32/float64 on non-MPS devices. Falls back to a+ manual expand-and-norm implementation for MPS tensors and for half-precision+ dtypes (float16/bfloat16), since ``torch.cdist`` does not support half precision+ on CUDA and may be unavailable for these dtypes elsewhere.+ """+ half = (torch.float16, torch.bfloat16)+ if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)) and d1.dtype not in half and d2.dtype not in half:return torch.cdist(d1, d2)d1_sq = (d1**2).sum(dim=1, keepdim=True)d2_sq = (d2**2).sum(dim=1, keepdim=True)diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 37f74020c..f40df3023 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -280,9 +280,9 @@ def _check_disparity_tensor(disparity_tensor: torch.Tensor) -> None:f"Got {disparity_tensor.shape}.")- if disparity_tensor.dtype not in (torch.float16, torch.float32, torch.float64):+ if disparity_tensor.dtype not in (torch.bfloat16, torch.float16, torch.float32, torch.float64):raise StereoException(- "Expected 'disparity_tensor' to have dtype torch.float16, torch.float32 or torch.float64."+ "Expected 'disparity_tensor' to have dtype torch.bfloat16, torch.float16, torch.float32 or torch.float64."f"Got {disparity_tensor.dtype}")@@ -303,9 +303,10 @@ def _check_Q_matrix(Q_matrix: torch.Tensor) -> None:if not Q_matrix.shape[1:] == (4, 4):raise StereoException(f"Expected last two dimensions of 'Q_matrix' to be of shape (4, 4). Got {Q_matrix.shape}")- if Q_matrix.dtype not in (torch.float16, torch.float32, torch.float64):+ if Q_matrix.dtype not in (torch.bfloat16, torch.float16, torch.float32, torch.float64):raise StereoException(- f"Expected 'Q_matrix' to be of type torch.float16, torch.float32 or torch.float64. Got {Q_matrix.dtype}"+ "Expected 'Q_matrix' to be of type torch.bfloat16, torch.float16, torch.float32 or torch.float64. "+ f"Got {Q_matrix.dtype}")diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.pyindex ddda3cadd..fb34e50a8 100644--- a/kornia/geometry/epipolar/numeric.py+++ b/kornia/geometry/epipolar/numeric.py@@ -19,6 +19,8 @@import torch+from kornia.core.utils import _torch_inverse_cast+def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:r"""Return the cross_product_matrix symmetric matrix of a vector.@@ -55,7 +57,7 @@ def matrix_cofactor_tensor(matrix: torch.Tensor) -> torch.Tensor:singular_mask = det != 0if singular_mask.sum() != 0:# B, 3, 3- cofactor = torch.linalg.inv(matrix[singular_mask]).transpose(-2, -1) * det[:, None, None]+ cofactor = _torch_inverse_cast(matrix[singular_mask]).transpose(-2, -1) * det[singular_mask][:, None, None]# return cofactor matrix of the given matrixreturned_cofactor = torch.zeros_like(matrix)returned_cofactor[singular_mask] = cofactordiff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 34e83d521..bde277afe 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -669,8 +669,15 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Qw = w / w.sum()A = data.T @ torch.diag(w) @ data+ orig_dtype = A.dtype+ if A.dtype in (torch.float16, torch.bfloat16):+ A = A.float()eigenvalues, eigenvectors = torch.linalg.eigh(A)- q_avg = eigenvectors[:, torch.argmax(eigenvalues)]+ # Use float32 eigenvalues for argmax to avoid half-precision rounding+ # changing which eigenvector is selected when eigenvalues are close.+ max_idx = torch.argmax(eigenvalues)+ eigenvectors = eigenvectors.to(orig_dtype)+ q_avg = eigenvectors[:, max_idx]q_avg = q_avg / q_avg.norm()return Quaternion(q_avg.unsqueeze(0))diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex e8155fa5e..f0c58ff8b 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -1349,7 +1349,7 @@ def _transform_warp_impl3d("""Compute the transform in normalized coordinates and perform the warping."""dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)- src_norm_trans_dst_norm = torch.linalg.inv(dst_norm_trans_src_norm)+ src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners, True)diff --git a/kornia/image/image_print.py b/kornia/image/image_print.pyindex e5f7c2195..cd77a128e 100644--- a/kornia/image/image_print.py+++ b/kornia/image/image_print.py@@ -367,7 +367,7 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:KORNIA_CHECK_IS_IMAGE(image, None, raises=True)KORNIA_CHECK_SHAPE(image, ["C", "H", "W"])- if image.dtype not in [float16, float32, float64]:+ if image.dtype not in [torch.bfloat16, float16, float32, float64]:image = image / 255.0if image.shape[-1] > max_width:diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.pyindex 40acaa358..17b1fe868 100644--- a/kornia/sensors/camera/projection_model.py+++ b/kornia/sensors/camera/projection_model.py@@ -48,7 +48,7 @@ class Z1Projection:xy = points.data[..., :2]z = points.zif len(z.shape):- uv = (xy.mT @ torch.diag(z).inverse()).mT+ uv = xy / z.unsqueeze(-1)else:# For scalar z, xy is 1-D, so no transpose neededuv = xy * 1 / zdiff --git a/pixi.toml b/pixi.tomlindex cc250887a..79652d2fd 100644--- a/pixi.toml+++ b/pixi.toml@@ -69,6 +69,8 @@ install-docs = { cmd = "uv sync --extra dev --extra docs --extra x && uv pip instest-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-half = { cmd = "uv run pytest -v tests/", env = { KORNIA_TEST_DTYPE = "float16,bfloat16" }, description = "Run half-precision tests (CPU; use test-cuda-half for CUDA isolation)" }+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" }# ------------------------------------------------------------------------------# Python version features (for CI matrix)diff --git a/testing/base.py b/testing/base.pyindex 04b18abdc..91bb4127c 100644--- a/testing/base.py+++ b/testing/base.py@@ -31,7 +31,7 @@ Tensor = torch.Tensor# {dtype: (rtol, atol)}_DTYPE_PRECISIONS = {torch.bfloat16: (7.8e-3, 7.8e-3),- torch.float16: (9.7e-4, 9.7e-4),+ torch.float16: (1e-3, 1e-3),torch.float32: (1e-4, 1e-5), # TODO: Update to ~1.2e-7# TODO: Update to ~2.3e-16 for fp64torch.float64: (1e-5, 1e-5), # TODO: BaseTester used (1.3e-6, 1e-5), but it fails for general casesdiff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex ac005027c..3e3d399b4 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -245,7 +245,7 @@ class TestALIKEDForwardLAF(BaseTester):"""forward_laf should return the three expected tensors."""aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=32).to(device, dtype)inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)- lafs, responses, descs = aliked.forward_laf(inp)+ lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)assert lafs.ndim == 4 # (B, N, 2, 3)assert responses.ndim == 3 # (B, N, 1)assert descs.ndim == 3 # (B, N, D)@@ -256,7 +256,7 @@ class TestALIKEDForwardLAF(BaseTester):top_k = 20aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)inp = torch.rand(B, 3, H, W, device=device, dtype=dtype)- lafs, responses, descs = aliked.forward_laf(inp)+ lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)N = lafs.shape[1]assert lafs.shape == (B, N, 2, 3)assert responses.shape == (B, N, 1)@@ -269,7 +269,7 @@ class TestALIKEDForwardLAF(BaseTester):top_k = 30aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)- lafs, responses, _ = aliked.forward_laf(inp)+ lafs, responses, _ = aliked.forward_laf(inp, compute_affine=False)# Only check keypoints with positive response (non-padding).valid = responses[0, :, 0] > 0if valid.any():@@ -284,7 +284,7 @@ class TestALIKEDForwardLAF(BaseTester):B = 3aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=25).to(device, dtype)inp = torch.rand(B, 3, 64, 64, device=device, dtype=dtype)- lafs, responses, descs = aliked.forward_laf(inp)+ lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)assert lafs.shape[0] == Bassert responses.shape[0] == Bassert descs.shape[0] == B@@ -297,15 +297,20 @@ class TestALIKEDForwardLAF(BaseTester):# Suppress the entire image except the bottom-right quarter.mask = torch.zeros(1, 1, H, W, device=device, dtype=dtype)mask[:, :, H // 2 :, W // 2 :] = 1.0- lafs_masked, _, _ = aliked.forward_laf(inp, mask=mask)+ lafs_masked, _, _ = aliked.forward_laf(inp, mask=mask, compute_affine=False)assert lafs_masked.shape[0] == 1+ @pytest.mark.slowdef test_laf_affine_shape(self, device, dtype):- """The 2x2 affine part of each LAF should be non-degenerate for valid kpts."""+ """The 2x2 affine part of each LAF should be non-degenerate for valid kpts.++ Requires ``--runslow``: uses ``torch.linalg.eigh`` (cast to float32 for+ half-precision dtypes) which is slower than the identity-affine path.+ """top_k = 20aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)- lafs, responses, _ = aliked.forward_laf(inp)+ lafs, responses, _ = aliked.forward_laf(inp, compute_affine=True)valid = responses[0, :, 0] > 0if valid.any():A = lafs[0, valid, :, :2] # (N_valid, 2, 2)