π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
ci: add a blocking MPS regression gate (#4160)
Dmytro Mishkin023028b60f5f
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.ymlindex b71bb677d..71548e90f 100644--- a/.github/workflows/pr_test_cpu.yml+++ b/.github/workflows/pr_test_cpu.yml@@ -154,6 +154,26 @@ jobs:model-weights-${{ needs.pre-tests.outputs.hash }}model-weights-+ # Single blocking MPS leg: newest Python, newest pinned torch, float32, on the Apple-silicon+ # macos-latest image (macos-14 segfaults inside MPS kernels; 15 and 26 verified working).+ # The exact known-failure baseline is pinned as strict xfails (see #4159): a new failure,+ # changed failure, skipped pin, or fixed pin makes the job red and requires review.+ tests-mps:+ needs: [pre-tests]+ uses: ./.github/workflows/tests.yml+ with:+ os: macos-latest+ python-version: '["3.13"]'+ pytorch-version: '["2.9.1"]'+ pytorch-dtype: float32+ device: mps+ pytest-extra: --xfail-known-failures+ cache-path: weights/+ cache-key: model-weights-${{ needs.pre-tests.outputs.hash }}+ cache-restore-keys: |+ model-weights-${{ needs.pre-tests.outputs.hash }}+ model-weights-+typecheck:needs: [pre-tests]uses: ./.github/workflows/typecheck.yml@@ -163,7 +183,7 @@ jobs:uses: ./.github/workflows/tutorials.ymlcollector:- needs: [changes, pre-tests, tests, dynamo, typecheck]+ needs: [changes, pre-tests, tests, tests-mps, dynamo, typecheck]if: always()runs-on: ubuntu-lateststeps:diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 4636908d3..bf7d1d160 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -17,6 +17,13 @@ on:required: falsetype: stringdefault: float32+ device:+ # KORNIA_TEST_DEVICE for the run: cpu (default) or mps. An mps leg must run on an+ # Apple-silicon macOS runner; the "Verify MPS device" step below refuses to let it+ # pass by skipping every test when the runner does not expose Metal.+ required: false+ type: string+ default: cpupytest-extra:required: falsetype: string@@ -117,10 +124,18 @@ jobs:echo "ATEN_CPU_CAPABILITY=avx2" >> $GITHUB_ENVecho "DNNL_MAX_CPU_ISA=AVX2" >> $GITHUB_ENV+ # The `device` fixture skips every test when the requested device is missing, so an mps+ # leg on a runner without a Metal device would be green with zero tests run. Fail here+ # instead. macos-14 images segfault inside MPS kernels; macos-15 and later work.+ - name: Verify MPS device+ if: inputs.device == 'mps'+ run: |+ pixi run -e ${{ steps.pixi-env.outputs.name }} uv run --no-sync python -c 'import torch; assert torch.backends.mps.is_available(), "MPS device not available on this runner"; x = torch.ones(2, device="mps"); assert (x + x).sum().item() == 4.0; print("MPS ok:", torch.mps.recommended_max_memory() // 2**20, "MiB recommended max memory")'+- name: Run testsshell: bashenv:- KORNIA_TEST_DEVICE: cpu+ KORNIA_TEST_DEVICE: ${{ inputs.device }}KORNIA_TEST_DTYPE: ${{ inputs.pytorch-dtype }}KORNIA_TEST_RUNSLOW: ${{ inputs.runslow }}KORNIA_TEST_OPTIMIZER: ${{ inputs.optimizer }}diff --git a/AGENTS.md b/AGENTS.mdindex 5156fc37e..b0b347fc8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -90,6 +90,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather- For focused CPU half-precision coverage, add `--dtype=float16,bfloat16` to a `test-module` run. `pixi run test-half` runs the whole CPU test suite.- CUDA `float16`/`bfloat16` tests need per-test subprocess isolation; use `pixi run -e cuda test-cuda-half` or pytest's `--isolate-half-precision` option.- MPS does not support float64 gradcheck. MPS autocast can also change the effective dtype; inspect nearby tests before changing tolerances or skips.+- The blocking MPS job runs `--device=mps --dtype=float32 --xfail-known-failures`. Its exact strict-xfail baseline is `testing/known_failure_xfails/mps_float32.txt` and is tracked in #4159. A fix removes its manifest line; a rename or reparametrization updates the node ID; a new failure is fixed or explicitly documented before being added. The manifest contract requires a full-suite run, without `-k` or a partial path.- TF32 matmul is disabled by default; `--tf32` enables it. cuDNN convolutions still use PyTorch's TF32 default. Tests marked `tf32` are xfailed at collection unless `--tf32` is passed, and that marker is non-strict, so a default run reports neither their failure nor their recovery.- Preserve device and dtype rather than creating implicit CPU or default-dtype tensors. Use the injected `device` and `dtype` fixtures in tests.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 66523e0df..e81406c05 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -147,6 +147,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `RandomTransplantation` and `RandomTransplantation3D` transplanted nothing on MPS when no `excluded_labels`+ were given: PyTorch's MPS backend evaluates `all()` over the empty excluded-label axis to an undefined value,+ usually `False`, so every donor label was filtered out and the output equalled the input. The filter is now skipped when there is+ nothing to exclude. (#4160)* `VisualPrompter.predict()` called without any prompt (the "run the prediction without prompts" example on theSegment Anything page) raised `TypeError: object of type 'NoneType' has no len()` from the prompt augmentationcontainer; it now predicts from the image embedding alone, as documented. (#4178)diff --git a/TESTING.md b/TESTING.mdindex 88d8fc7ee..442a0f3c4 100644--- a/TESTING.md+++ b/TESTING.md@@ -253,6 +253,12 @@ Without `--isolate-half-precision`, float16/bfloat16 CUDA tests are **skipped**The `padding_mode="border"` issue in `F.grid_sample` (2D) is worked around in the implementation (`kornia/feature/laf.py`) by clamping the sampling grid to `[-1, 1]` and using `padding_mode="zeros"`, which is mathematically equivalent.+**CI coverage.** Pull-request CI runs one blocking MPS leg (`tests-mps` in `.github/workflows/pr_test_cpu.yml`): the newest Python and the newest pinned PyTorch, `float32`, on the GitHub-hosted `macos-latest` Apple-silicon image. The exact known-failure baseline from [#4159](https://github.com/kornia/kornia/issues/4159) lives in `testing/known_failure_xfails/mps_float32.txt`. `--xfail-known-failures` applies those entries as strict xfails with their exact exception types. A new failure, a different exception, a skipped recorded test, or a fixed test therefore makes CI red.++Run the identical contract locally with `pixi run test-mps`. `PYTORCH_ENABLE_MPS_FALLBACK=1` silently routes missing MPS kernels to the CPU and invalidates the baseline, so unset it first. The manifest is a full-suite contract and is not intended for `-k` or partial-directory runs; use `pixi run test-module ... --device=mps --dtype=float32` for focused diagnosis without the manifest. "Full suite" means the suite as an `mps`-only run collects it: tests marked `device_agnostic` are deselected there and covered by the CPU jobs, so they never appear in the manifest.++When an MPS failure is fixed, remove its line from `mps_float32.txt`. When a test is renamed or reparametrized, update its node ID. Treat an unlisted failure as a regression to fix; add it only when the new limitation is understood and documented in #4159. After a deliberate Python, PyTorch, or runner-image update, regenerate the full manifest from that CI job's final `short test summary info`, recording one exact exception type and node ID per `FAILED` line.+**Writing new tests that work on MPS.** Follow these rules:1. **Never create `float64` tensors on the device in non-gradcheck tests.** Use the `dtype` fixture, or if the algorithm requires double precision, skip explicitly:diff --git a/conftest.py b/conftest.pyindex 08bd8f400..fe8fee804 100644--- a/conftest.py+++ b/conftest.py@@ -34,6 +34,7 @@ except ImportError: # pragma: no coverimport korniafrom testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reason+from testing.known_failures import mark_known_failurestry:import torch._dynamo@@ -196,6 +197,17 @@ def pytest_collection_modifyitems(config, items):# Filter out tests with "dynamo" or "compile" in their nameitems[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]+ if config.getoption("--xfail-known-failures"):+ devices = _parse_test_option(config, "--device", TEST_DEVICES)+ dtypes = _parse_test_option(config, "--dtype", TEST_DTYPES)+ if len(devices) != 1 or len(dtypes) != 1:+ raise pytest.UsageError("--xfail-known-failures requires exactly one --device and one --dtype")+ try:+ tracker = mark_known_failures(items, devices[0], dtypes[0])+ except (OSError, ValueError) as error:+ raise pytest.UsageError(str(error)) from error+ config.pluginmanager.register(tracker, "known-failure-tracker")+# gradcheck requires float64. MPS does not support it at all, and XLA lowers a float64 request# to float32, where gradcheck's default eps=1e-6 makes the numerical Jacobian invalid β so a# float64 gradcheck on the tpu fixture fails for a pure precision reason. Skip on both.@@ -321,6 +333,14 @@ def pytest_addoption(parser):"on one device anyway. (env: KORNIA_TEST_RUN_DEVICE_AGNOSTIC)"),)+ parser.addoption(+ "--xfail-known-failures",+ action="store_true",+ help=(+ "Strictly xfail the complete recorded baseline for the selected device and dtype. "+ "A new failure, changed exception, skipped pin, or fixed pin fails the run."+ ),+ )def _setup_torch_compile() -> None:diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.pyindex 204c6f5b5..602f79a7a 100644--- a/kornia/augmentation/_2d/mix/transplantation.py+++ b/kornia/augmentation/_2d/mix/transplantation.py@@ -263,8 +263,11 @@ class RandomTransplantation(MixAugmentationBaseV2):current_mask = mask[params["donor_indices"][d]]labels = current_mask.unique()- # Remove any label which is part of the excluded labels- labels = labels[(labels.view(1, -1) != self.excluded_labels.view(-1, 1)).all(dim=0)]+ # Remove any label which is part of the excluded labels. Skip the reduction when there is nothing+ # to exclude: on MPS (PyTorch 2.9) ``all`` over an empty axis yields an undefined result, usually+ # False, where CPU and CUDA return True, and the filter would then discard every label.+ if self.excluded_labels.numel() > 0:+ labels = labels[(labels.view(1, -1) != self.excluded_labels.view(-1, 1)).all(dim=0)]if len(labels) > 0:selected_label = labels[torch.randperm(len(labels))[0]]diff --git a/pixi.toml b/pixi.tomlindex 342b57fa1..f23993563 100644--- a/pixi.toml+++ b/pixi.toml@@ -44,6 +44,7 @@ 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-mps = { cmd = "uv run pytest tests/ --xfail-known-failures", env = { KORNIA_TEST_DEVICE = "mps", KORNIA_TEST_DTYPE = "float32" }, description = "Run blocking MPS float32 tests against the strict known-failure baseline (unset PYTORCH_ENABLE_MPS_FALLBACK)" }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/)" }# Qualitylint = { cmd = "uv run pre-commit run ruff-check --all-files && uv run pre-commit run ruff-format --all-files" }diff --git a/testing/known_failure_xfails/mps_float32.txt b/testing/known_failure_xfails/mps_float32.txtnew file mode 100644index 000000000..bf8e541db--- /dev/null+++ b/testing/known_failure_xfails/mps_float32.txt@@ -0,0 +1,207 @@+# Exact failure baseline from https://github.com/kornia/kornia/actions/runs/33676811355+# macos-26-arm64, Python 3.13, PyTorch 2.9.1, MPS float32, no CPU fallback,+# one pytest process for the full suite (tests marked device_agnostic are deselected on an mps-only run).+# Remove an entry when it becomes a strict XPASS; fix or explicitly add any new failure. Tracked in #4159.+# Format: <exact exception type>\t<pytest node ID>+AssertionError tests/augmentation/_3d/test_random_affine_3d.py::TestRandomAffine3D::test_batch_random_affine_3d[mps-float32]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-constant-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-constant-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-constant-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-constant-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-constant-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-replicate-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-replicate-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-replicate-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-replicate-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-replicate-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-circular-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-circular-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-circular-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-circular-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-circular-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-constant-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-constant-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-constant-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-constant-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-constant-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-replicate-direction0-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-replicate-direction0-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-replicate-direction1-20.0]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-replicate-direction1-angle1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-True-bilinear-replicate-direction1-angle2]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomPerspective3DBackward::test_param[mps-float32-False-False-bilinear-distortion_scale1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomPerspective3DBackward::test_param[mps-float32-False-True-bilinear-distortion_scale1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomPerspective3DBackward::test_param[mps-float32-True-False-bilinear-distortion_scale1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomPerspective3DBackward::test_param[mps-float32-True-True-bilinear-distortion_scale1]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-False-bilinear-degrees4]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-False-bilinear-degrees5]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-False-bilinear-degrees6]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-False-bilinear-degrees7]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-True-bilinear-degrees4]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-True-bilinear-degrees5]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-True-bilinear-degrees6]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-False-True-bilinear-degrees7]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-False-bilinear-degrees4]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-False-bilinear-degrees5]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-False-bilinear-degrees6]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-False-bilinear-degrees7]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-True-bilinear-degrees4]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-True-bilinear-degrees5]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-True-bilinear-degrees6]+NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomRotation3DBackward::test_param[mps-float32-True-True-bilinear-degrees7]+RuntimeError tests/color/test_yuv.py::TestYuv420ToRgb::test_empty_input[mps-float32]+RuntimeError tests/color/test_yuv.py::TestYuv422ToRgb::test_empty_input[mps-float32]+NotImplementedError tests/contrib/test_image_stitcher.py::TestImageStitcher::test_smoke[mps-float32-ransac]+NotImplementedError tests/contrib/test_image_stitcher.py::TestImageStitcher::test_smoke[mps-float32-vanilla]+NotImplementedError tests/core/test_helpers.py::TestSolveWithMask::test_all_bad[mps-float32]+NotImplementedError tests/core/test_helpers.py::TestSolveWithMask::test_smoke[mps-float32]+NotImplementedError tests/feature/test_affine_shape_estimator.py::TestLAFAffineShapeEstimator::test_degenerate_ellipse_boundary_has_finite_backward[mps]+NotImplementedError tests/feature/test_affine_shape_estimator.py::TestLAFAffineShapeEstimator::test_non_positive_definite_shape_falls_back_with_finite_backward[mps]+NotImplementedError tests/feature/test_laf.py::TestExtractPatchesPyr::test_atlas_guards_preserve_level_border_value_and_gradient[mps-float32]+NotImplementedError tests/feature/test_laf.py::TestExtractPatchesPyr::test_nonfinite_laf_returns_zero_patch_with_safe_backward[mps-float32]+NotImplementedError tests/feature/test_laf.py::TestExtractPatchesSimple::test_nonfinite_laf_returns_zero_patch_with_safe_backward[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_cardinality[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_descriptors_normalized[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_keypoint_coordinates_in_image[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_match_xfeat_returns_paired_keypoints[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_smoke[mps-float32]+RuntimeError tests/feature/test_xfeat.py::TestXFeat::test_top_k_respected[mps-float32]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[mps-float32-20]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[mps-float32-6]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted[mps-float32-16]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted[mps-float32-20]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted_rand[mps-float32-25]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_project[mps-float32-20]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_project[mps-float32-6]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_smoke[mps-float32-20]+NotImplementedError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_smoke[mps-float32-6]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[mps-float32-10-5]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[mps-float32-5-5]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_epipolar_constraint[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-1-5]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-16-5]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-2-6]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-3-7]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-1-5]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-2-6]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-3-7]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_smoke[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_masking[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_shape[mps-float32-1-3]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_shape[mps-float32-2-3]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_shape[mps-float32-2-8]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_shape[mps-float32-3-2]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_smoke[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_two_view[mps-float32]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_unbatched[mps-float32-10]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_unbatched[mps-float32-15]+NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssentialChooseSolution::test_unbatched[mps-float32-20]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_7point_opencv[mps-float32]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_opencv_svd[mps-float32]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[mps-float32-1-8]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[mps-float32-2-9]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[mps-float32-3-10]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[mps-float32-1]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[mps-float32-2]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[mps-float32-3]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[mps-float32-1-8]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[mps-float32-2-8]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[mps-float32-3-10]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_smoke[mps-float32]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[mps-float32]+NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson_7point[mps-float32]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_shape[mps-float32-1]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_shape[mps-float32-2]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_shape[mps-float32-4]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_simple[mps-float32]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_smoke[mps-float32]+NotImplementedError tests/geometry/epipolar/test_projection.py::TestProjectionFromKRt::test_krt_from_projection[mps-float32]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_module[mps-float32]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_noisy_correspondences_dlt[mps-float32-eigh]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_shape[mps-float32-eigh-1-3]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_shape[mps-float32-eigh-2-4]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_shape[mps-float32-eigh-3-5]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_smoke[mps-float32-eigh]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_solver_consistency[mps-float32]+NotImplementedError tests/geometry/epipolar/test_triangulation.py::TestTriangulation::test_two_view[mps-float32]+AssertionError tests/geometry/solvers/test_polynomial_solver.py::TestQuarticSolver::test_solve_quartic[mps-float32-coeffs6-expected_solutions6]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_clean_points_lu[mps-float32-1]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_clean_points_lu[mps-float32-2]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_clean_points_lu[mps-float32-5]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_nocrash[mps-float32]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_nocrash_lu[mps-float32]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_points_noweights[mps-float32-1-4]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_points_noweights[mps-float32-2-5]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_points_noweights[mps-float32-3-6]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_scaled_fixed_points[mps-float32]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape[mps-float32-1-4]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape[mps-float32-2-5]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape[mps-float32-3-6]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape_noweights[mps-float32-1-4]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape_noweights[mps-float32-2-5]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape_noweights[mps-float32-3-6]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_smoke[mps-float32]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_clean_points[mps-float32-1]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_clean_points[mps-float32-2]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_shape[mps-float32-1-4]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_shape[mps-float32-2-5]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_shape[mps-float32-3-6]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_smoke[mps-float32]+AssertionError tests/geometry/test_line.py::TestFitLine::test_fit_line2[mps-float32]+AssertionError tests/geometry/test_line.py::TestFitLine::test_fit_line3[mps-float32]+AssertionError tests/geometry/test_line.py::TestFitLine::test_fit_line_weighted[mps-float32]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_average_identity[mps-float32-10]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_average_identity[mps-float32-1]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_average_identity[mps-float32-2]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_average_identity[mps-float32-5]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_opposite_quaternions[mps-float32]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_output_is_normalized[mps-float32]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_single_quaternion_returns_itself[mps-float32]+NotImplementedError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_weighted_bias[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_forward_enforces_essential_constraint[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_polish_enforces_essential_constraint[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_project_to_essential[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_smoke[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACFundamental::test_smoke[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACSeed::test_different_seeds_differ[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACSeed::test_no_seed_differs_from_seeded[mps-float32]+NotImplementedError tests/geometry/test_ransac.py::TestRANSACSeed::test_same_seed_reproducible[mps-float32]+NotImplementedError tests/geometry/transform/test_image_registrator.py::TestImageRegistrator::test_register_with_shape_mismatch[mps]+RuntimeError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_forth_back[mps-float32]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize0-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize0-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize1-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize1-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize2-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-False-dsize2-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize0-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize0-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize1-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize1-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize2-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_destination_is_autograd_connected[mps-float32-True-dsize2-warp_perspective3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_source_policy[mps-float32-warp_affine3d]+NotImplementedError tests/geometry/transform/test_imgwarp3d.py::test_empty_source_policy[mps-float32-warp_perspective3d]+AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_log_quaternion[mps-float32-0-x]+AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_log_quaternion[mps-float32-0-y]+AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_log_quaternion[mps-float32-0-z]+NotImplementedError tests/integration/test_warp.py::TestWarping::test_smoke[mps]+NotImplementedError tests/losses/test_hd.py::TestHausdorffLoss::test_numeric_3d[mps-float32]+NotImplementedError tests/losses/test_hd.py::TestHausdorffLoss::test_smoke_none[mps-float32-HausdorffERLoss3D-shape1-mean]+NotImplementedError tests/losses/test_hd.py::TestHausdorffLoss::test_smoke_none[mps-float32-HausdorffERLoss3D-shape1-none]+NotImplementedError tests/losses/test_hd.py::TestHausdorffLoss::test_smoke_none[mps-float32-HausdorffERLoss3D-shape1-sum]+AssertionError tests/losses/test_ssim.py::TestSSIM3DLoss::test_ssim[mps-float32-shape0-sum-11]+AssertionError tests/losses/test_ssim.py::TestSSIM3DLoss::test_ssim[mps-float32-shape0-sum-5]+AssertionError tests/losses/test_ssim.py::TestSSIM3DLoss::test_ssim[mps-float32-shape1-sum-11]+AssertionError tests/losses/test_ssim.py::TestSSIM3DLoss::test_ssim[mps-float32-shape1-sum-5]+AssertionError tests/losses/test_ssim.py::TestSSIMLoss::test_ssim[mps-float32-batch_shape1-sum-11]+AssertionError tests/losses/test_ssim.py::TestSSIMLoss::test_ssim[mps-float32-batch_shape1-sum-5]+AssertionError tests/metrics/test_ssim3d.py::TestSSIM3d::test_smoke[mps-float32-shape0-same-5-1.0]+AssertionError tests/metrics/test_ssim3d.py::TestSSIM3d::test_smoke[mps-float32-shape3-valid-3-1.0]+AssertionError tests/metrics/test_ssim3d.py::TestSSIM3d::test_smoke[mps-float32-shape4-same-3-1.0]diff --git a/testing/known_failures.py b/testing/known_failures.pynew file mode 100644index 000000000..4f1a226f4--- /dev/null+++ b/testing/known_failures.py@@ -0,0 +1,138 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++from pathlib import Path+from typing import Any, Sequence++import pytest++ISSUE_URL = "https://github.com/kornia/kornia/issues/4159"+_MANIFEST_DIR = Path(__file__).with_name("known_failure_xfails")+_EXCEPTION_TYPES: dict[str, type[BaseException]] = {+ "AssertionError": AssertionError,+ "NotImplementedError": NotImplementedError,+ "RuntimeError": RuntimeError,+ "TypeError": TypeError,+ "pytest.fail.Exception": pytest.fail.Exception,+}+++def manifest_path(device: str, dtype: str, manifest_dir: Path | None = None) -> Path:+ """Return the known-failure manifest path for one test configuration."""+ return (manifest_dir or _MANIFEST_DIR) / f"{device}_{dtype}.txt"+++class KnownFailureTracker:+ """Require every manifest entry to finish under its exact strict xfail."""++ def __init__(self, failures: dict[str, type[BaseException]], path: Path, reason: str) -> None:+ self.pending = set(failures)+ self._expected_exceptions = failures.copy()+ self.path = path+ self.reason = reason+ self._matched: set[str] = set()+ self._invalid: set[str] = set()+ self._collect_only = False++ @pytest.hookimpl(hookwrapper=True, tryfirst=True)+ def pytest_runtest_makereport(self, item: Any, call: Any) -> Any:+ """Record only call-phase xfails caused by the exact recorded exception type."""+ outcome = yield+ report = outcome.get_result()+ if report.nodeid not in self.pending:+ return+ wasxfail = getattr(report, "wasxfail", None)+ if (+ report.when == "call"+ and report.outcome == "skipped"+ and wasxfail == self.reason+ and call.excinfo is not None+ and type(call.excinfo.value) is self._expected_exceptions[report.nodeid]+ ):+ self._matched.add(report.nodeid)+ elif report.outcome in {"skipped", "failed"} or wasxfail is not None:+ self._invalid.add(report.nodeid)++ def pytest_runtest_logfinish(self, nodeid: str) -> None:+ """Accept an entry only after setup, call, and teardown reports are known."""+ if nodeid in self._matched and nodeid not in self._invalid:+ self.pending.remove(nodeid)+ self._matched.discard(nodeid)+ self._invalid.discard(nodeid)++ def pytest_sessionfinish(self, session: pytest.Session) -> None:+ """Fail when a recorded test passed, skipped, or failed in a different way."""+ self._collect_only = session.config.getoption("collectonly")+ if self._collect_only:+ return+ if self.pending and session.exitstatus == pytest.ExitCode.OK:+ session.exitstatus = pytest.ExitCode.TESTS_FAILED++ def pytest_terminal_summary(self, terminalreporter: Any) -> None:+ """Explain how to update entries whose recorded outcome changed."""+ if not self.pending or self._collect_only:+ return+ count = len(self.pending)+ noun = "failure" if count == 1 else "failures"+ terminalreporter.write_line(f"ERROR: {count} known {noun} did not reproduce exactly; update {self.path}:")+ for nodeid in sorted(self.pending):+ terminalreporter.write_line(nodeid)+++def load_known_failures(+ device: str, dtype: str, manifest_dir: Path | None = None+) -> tuple[dict[str, type[BaseException]], Path]:+ """Load exact node IDs and exception types for one device/dtype configuration."""+ path = manifest_path(device, dtype, manifest_dir)+ failures: dict[str, type[BaseException]] = {}+ for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):+ if not line or line.startswith("#"):+ continue+ try:+ exception_name, nodeid = line.split("\t", maxsplit=1)+ except ValueError as error:+ raise ValueError(f"{path}:{line_number}: expected '<exception>\\t<node ID>'") from error+ if exception_name not in _EXCEPTION_TYPES:+ raise ValueError(f"{path}:{line_number}: unknown exception type: {exception_name}")+ parameter_ids = nodeid.rsplit("[", maxsplit=1)[-1].removesuffix("]").split("-")+ if device not in parameter_ids:+ raise ValueError(f"{path}:{line_number}: node ID does not select {device}: {nodeid}")+ if nodeid in failures:+ raise ValueError(f"{path}:{line_number}: duplicate node ID: {nodeid}")+ failures[nodeid] = _EXCEPTION_TYPES[exception_name]+ return failures, path+++def mark_known_failures(+ items: Sequence[Any], device: str, dtype: str, manifest_dir: Path | None = None+) -> KnownFailureTracker:+ """Strictly xfail the complete known-failure set for one test configuration."""+ failures, path = load_known_failures(device, dtype, manifest_dir)+ collected = {item.nodeid for item in items}+ missing = failures.keys() - collected+ if missing:+ preview = "\n".join(sorted(missing)[:10])+ raise ValueError(f"{len(missing)} failures from {path} were not collected:\n{preview}")++ reason = f"Known {device}/{dtype} failure tracked in {ISSUE_URL}"+ tracker = KnownFailureTracker(failures, path, reason)+ for item in items:+ if exception_type := failures.get(item.nodeid):+ item.add_marker(pytest.mark.xfail(reason=reason, raises=exception_type, strict=True))+ return trackerdiff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex d509d8139..e39fb5795 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -493,6 +493,24 @@ class TestRandomTransplantation(BaseTester):self.assert_close(mask_out, mask_out_expected)self.assert_close(image_out, mask_out_expected.unsqueeze(dim=1))+ def test_no_excluded_labels_transplants(self, device, dtype):+ # With nothing excluded every donor label stays eligible, so with p=1 some pixels change. On MPS the+ # ``all`` reduction over the empty excluded-label axis is undefined (usually False, and it varies between+ # processes) and used to drop every label, which made this class flaky there.+ torch.manual_seed(22)+ mask = torch.zeros(2, 4, 4, device=device, dtype=dtype)+ mask[0, :2, :2] = 1+ mask[1, 2:, 2:] = 2+ image = mask.clone().unsqueeze(dim=1)++ f = RandomTransplantation(p=1)+ image_out, mask_out = f(image, mask)++ assert len(f._params["selected_labels"]) == 2+ assert f._params["selection"].any()+ assert not torch.equal(mask_out, mask)+ self.assert_close(image_out.squeeze(dim=1), mask_out)+def test_mask_only(self, device, dtype):torch.manual_seed(22)diff --git a/tests/test_known_failures.py b/tests/test_known_failures.pynew file mode 100644index 000000000..63b163ba2--- /dev/null+++ b/tests/test_known_failures.py@@ -0,0 +1,196 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++from pathlib import Path++import pytest++from testing.known_failures import ISSUE_URL, load_known_failures, mark_known_failures++pytest_plugins = ["pytester"]+++def _write_manifest(directory: Path, contents: str) -> None:+ (directory / "mps_float32.txt").write_text(contents)+++class TestLoadKnownFailures:+ def test_loads_nodeids_and_exception_types(self, tmp_path: Path) -> None:+ _write_manifest(+ tmp_path,+ "# tracked in kornia#4159\n"+ "AssertionError\ttests/a.py::test_a[mps-float32]\n"+ "RuntimeError\ttests/b.py::TestB::test_b[mps]\n",+ )++ failures, path = load_known_failures("mps", "float32", tmp_path)++ assert failures == {+ "tests/a.py::test_a[mps-float32]": AssertionError,+ "tests/b.py::TestB::test_b[mps]": RuntimeError,+ }+ assert path == tmp_path / "mps_float32.txt"++ def test_rejects_duplicate_nodeids(self, tmp_path: Path) -> None:+ _write_manifest(+ tmp_path,+ "AssertionError\ttests/a.py::test_a[mps-float32]\nRuntimeError\ttests/a.py::test_a[mps-float32]\n",+ )++ with pytest.raises(ValueError, match="duplicate node ID"):+ load_known_failures("mps", "float32", tmp_path)++ def test_rejects_unknown_exception_types(self, tmp_path: Path) -> None:+ _write_manifest(tmp_path, "UnknownError\ttests/a.py::test_a[mps-float32]\n")++ with pytest.raises(ValueError, match="unknown exception type"):+ load_known_failures("mps", "float32", tmp_path)++ def test_rejects_entries_for_the_wrong_device(self, tmp_path: Path) -> None:+ _write_manifest(tmp_path, "AssertionError\ttests/a.py::test_a[cpu-float32]\n")++ with pytest.raises(ValueError, match="does not select mps"):+ load_known_failures("mps", "float32", tmp_path)+++class _Item:+ def __init__(self, nodeid: str) -> None:+ self.nodeid = nodeid+ self.markers: list[pytest.MarkDecorator] = []++ def add_marker(self, marker: pytest.MarkDecorator) -> None:+ self.markers.append(marker)+++class TestMarkKnownFailures:+ def test_marks_exact_nodeid_strictly_with_expected_exception(self, tmp_path: Path) -> None:+ nodeid = "tests/a.py::test_a[mps-float32]"+ _write_manifest(tmp_path, f"AssertionError\t{nodeid}\n")+ item = _Item(nodeid)++ tracker = mark_known_failures([item], "mps", "float32", tmp_path)++ assert len(item.markers) == 1+ assert item.markers[0].mark.kwargs == {+ "raises": AssertionError,+ "reason": tracker.reason,+ "strict": True,+ }+ assert tracker.reason == f"Known mps/float32 failure tracked in {ISSUE_URL}"++ def test_rejects_manifest_entries_that_were_not_collected(self, tmp_path: Path) -> None:+ _write_manifest(tmp_path, "AssertionError\ttests/missing.py::test_missing[mps-float32]\n")++ with pytest.raises(ValueError, match=r"1 failures .* were not collected"):+ mark_known_failures([], "mps", "float32", tmp_path)+++def _run_manifest_case(pytester: pytest.Pytester, test_body: str, extra_marker: str = "") -> pytest.RunResult:+ nodeid = "test_sample.py::test_known_failure[mps-float32]"+ _write_manifest(pytester.path, f"RuntimeError\t{nodeid}\n")+ pytester.makeconftest(+ """+ from pathlib import Path++ from testing.known_failures import mark_known_failures+++ def pytest_collection_modifyitems(config, items):+ tracker = mark_known_failures(items, "mps", "float32", Path(__file__).parent)+ config.pluginmanager.register(tracker, "known-failure-tracker")+ """+ )+ pytester.makepyfile(+ test_sample=f"""+ import pytest+++ {extra_marker}+ @pytest.mark.parametrize("unused", [None], ids=["mps-float32"])+ def test_known_failure(unused, request):+ {test_body}+ """+ )+ return pytester.runpytest("-q")+++class TestKnownFailureOutcomes:+ def test_accepts_exact_manifest_xfail(self, pytester: pytest.Pytester) -> None:+ result = _run_manifest_case(pytester, "raise RuntimeError('known failure')")++ result.assert_outcomes(xfailed=1)+ assert result.ret == pytest.ExitCode.OK++ @pytest.mark.parametrize(+ ("test_body", "extra_marker"),+ [+ ("pass", ""),+ ("raise AssertionError('wrong failure type')", ""),+ ("raise NotImplementedError('subclass of RuntimeError')", ""),+ ("pytest.skip('disabled test')", ""),+ (+ "raise RuntimeError('known failure')",+ "@pytest.mark.skip(reason='disabled test')",+ ),+ (+ "raise RuntimeError('known failure')",+ "@pytest.mark.xfail(reason='different xfail marker', strict=False)",+ ),+ (+ "request.addfinalizer(lambda: pytest.skip('disabled in teardown')); "+ "raise RuntimeError('known failure')",+ "",+ ),+ (+ "raise RuntimeError('known failure')",+ "@pytest.fixture(autouse=True)\n"+ " def fail_setup():\n"+ " raise RuntimeError('setup failure')",+ ),+ ],+ ids=[+ "fixed",+ "wrong-exception",+ "exception-subclass",+ "runtime-skip",+ "static-skip",+ "prior-xfail",+ "teardown-skip",+ "setup-failure",+ ],+ )+ def test_rejects_changed_or_bypassed_outcome(+ self, pytester: pytest.Pytester, test_body: str, extra_marker: str+ ) -> None:+ result = _run_manifest_case(pytester, test_body, extra_marker)++ assert result.ret == pytest.ExitCode.TESTS_FAILED+ output = result.stdout.str()+ assert "ERROR: 1 known failure did not reproduce exactly" in output+ assert "test_sample.py::test_known_failure[mps-float32]" in output+++def test_recorded_mps_float32_baseline() -> None:+ failures, path = load_known_failures("mps", "float32")++ # The exact count changes with every fix that removes a manifest line; the contract is the file, not a number.+ assert len(failures) > 0+ assert path.name == "mps_float32.txt"+ assert all(issubclass(exception, BaseException) for exception in failures.values())+ assert ISSUE_URL == "https://github.com/kornia/kornia/issues/4159"