Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(compile): torch.compile conformance test for the promised operators (#5819), with scheduled and PR CI jobs (#6199)

Dmytro Mishkin5c3cd635c3a4
diff --git a/.github/scripts/onnx_conformance_packages.py b/.github/scripts/conformance_packages.py
similarity index 75%
rename from .github/scripts/onnx_conformance_packages.py
rename to .github/scripts/conformance_packages.py
index c4416b1f6..badba565c 100755
--- a/.github/scripts/onnx_conformance_packages.py
+++ b/.github/scripts/conformance_packages.py
@@ -16,11 +16,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-"""Map a pull request's changed paths to the ``--onnx-conformance`` selection of its CI run (#5819).
+"""Map a pull request's changed paths to the package selection of its conformance runs (#5819).
-Reads the changed paths on stdin (one per line, as ``git diff --name-only`` prints them, or separated by any
-whitespace: no kornia path contains a space) and prints ``all``, a comma-separated list of stable-core packages, or
-nothing when no change can affect a promised operator (the conformance job is then skipped).
+``python conformance_packages.py onnx`` prints the ``--onnx-conformance`` value, ``python conformance_packages.py
+compile`` the ``--compile-conformance`` one. Reads the changed paths on stdin (one per line, as ``git diff --name-only``
+prints them, or separated by any whitespace: no kornia path contains a space) and prints ``all``, a comma-separated list
+of stable-core packages, or nothing when no change can affect a promised operator (the conformance job is then
+skipped).
A changed module under ``kornia/`` selects the stable-core package it belongs to and every stable-core package with a
module that imports it, directly or through other modules. The import graph is read from the checkout with ``ast``:
@@ -31,15 +33,18 @@ selects ``losses``, whose PSNR losses call it, while a ``kornia/contrib`` module
nothing.
``all`` is selected by code every package runs (``kornia/core``, ``kornia/utils``, ``kornia/onnx``, the modules
-directly under ``kornia/``), by the sources of the promise and its test (the survey snapshot, the stability page, the
-survey under ``docs/export_support/``, ``testing/``, the test, the root ``conftest.py``, this script, the workflows that
-run it) and by the dependency pins.
+directly under ``kornia/``), by the sources of the promises and their tests (the survey snapshot, the stability page,
+the survey under ``docs/export_support/``, ``testing/``, the promise's own test, the root ``conftest.py``, this script,
+the workflows that run it) and by the dependency pins. The two promises differ only in their own test file and
+known-failure manifests (``testing/known_failure_xfails/<onnx|compile>_conformance_*``), which select ``all`` for their
+promise and nothing for the other.
Standard library only: the ``changes`` job runs it before any environment is installed.
"""
from __future__ import annotations
+import argparse
import ast
import functools
import sys
@@ -49,8 +54,8 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
-# The stable core of docs/source/get-started/stability.rst; the same tuple as testing/onnx_conformance.py, which
-# tests/scripts/test_onnx_conformance_packages.py checks.
+# The stable core of docs/source/get-started/stability.rst; the same tuple as testing/conformance.py, which
+# tests/scripts/test_conformance_packages.py checks.
STABLE_CORE = (
"geometry",
"augmentation",
@@ -77,8 +82,7 @@ ALL_PREFIXES = (
ALL_FILES = (
"docs/source/_data/export_support.json",
"docs/source/get-started/stability.rst",
- "tests/onnx/test_conformance.py",
- ".github/scripts/onnx_conformance_packages.py",
+ ".github/scripts/conformance_packages.py",
".github/workflows/tests.yml",
".github/workflows/pr_test_cpu.yml",
".github/workflows/scheduled_test_cpu.yml",
@@ -86,6 +90,13 @@ ALL_FILES = (
"pyproject.toml",
"uv.lock",
)
+# Each promise's own test, by the snapshot field it promises (testing/conformance.py PROMISES).
+TEST_FILES = {
+ "onnx": "tests/onnx/test_conformance.py",
+ "compile": "tests/test_inductor_conformance.py",
+}
+# Each promise's known-failure manifests: an edit selects all of that promise and nothing of the other.
+MANIFEST_PREFIX = "testing/known_failure_xfails/{}_conformance_"
def module_index(root: Path) -> dict[str, Path]:
@@ -182,14 +193,24 @@ def _graph(root: Path) -> tuple[dict[str, str], dict[str, set[str]]]:
return {path.relative_to(root).as_posix(): module for module, path in index.items()}, importers(index)
-def select(paths: Iterable[str], root: Path = REPO) -> str:
- """Return the ``--onnx-conformance`` value for a set of changed paths, ``""`` when nothing is selected."""
+def select(paths: Iterable[str], root: Path = REPO, *, promise: str) -> str:
+ """Return the ``--<promise>-conformance`` value for a set of changed paths, ``""`` when nothing is selected."""
changed: set[str] = set()
for raw in paths:
path = raw.strip()
if not path:
continue
- if path.startswith(ALL_PREFIXES) or path in ALL_FILES or path.startswith("pixi."):
+ manifest_of = [other for other in TEST_FILES if path.startswith(MANIFEST_PREFIX.format(other))]
+ if manifest_of:
+ if manifest_of == [promise]:
+ return "all"
+ continue
+ if (
+ path.startswith(ALL_PREFIXES)
+ or path in ALL_FILES
+ or path == TEST_FILES[promise]
+ or path.startswith("pixi.")
+ ):
return "all"
parts = path.split("/")
if parts[0] != "kornia":
@@ -220,9 +241,12 @@ def select(paths: Iterable[str], root: Path = REPO) -> str:
return ",".join(p for p in STABLE_CORE if p in packages)
-def main() -> int:
- """Print the selection for the changed paths read from stdin."""
- print(select(sys.stdin.read().split()))
+def main(argv: list[str] | None = None) -> int:
+ """Print the selection of a promise for the changed paths read from stdin."""
+ parser = argparse.ArgumentParser(description="Print the conformance package selection for changed paths on stdin.")
+ parser.add_argument("promise", choices=sorted(TEST_FILES), help="the conformance test the selection is for")
+ args = parser.parse_args(argv)
+ print(select(sys.stdin.read().split(), promise=args.promise))
return 0
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index aa166b92b..5f6effef4 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -20,6 +20,7 @@ jobs:
outputs:
run-tests: ${{ steps.filter.outputs.run-tests }}
onnx-conformance: ${{ steps.filter.outputs.onnx-conformance }}
+ compile-conformance: ${{ steps.filter.outputs.compile-conformance }}
steps:
- uses: actions/checkout@v7
with:
@@ -33,15 +34,19 @@ jobs:
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
echo "run-tests=true" >> "$GITHUB_OUTPUT"
echo "onnx-conformance=all" >> "$GITHUB_OUTPUT"
+ echo "compile-conformance=all" >> "$GITHUB_OUTPUT"
exit 0
fi
changed=$(git diff --no-renames --name-only "${BASE_SHA}...HEAD")
- # The packages whose promised ONNX operators this change can affect, importers included (#5819); empty
- # skips the job.
- conformance=$(python3 .github/scripts/onnx_conformance_packages.py <<< "$changed")
+ # The packages whose promised ONNX and torch.compile operators this change can affect, importers included
+ # (#5819); empty skips the job.
+ conformance=$(python3 .github/scripts/conformance_packages.py onnx <<< "$changed")
echo "onnx-conformance=$conformance" >> "$GITHUB_OUTPUT"
echo "ONNX conformance selection: '${conformance}'"
+ conformance=$(python3 .github/scripts/conformance_packages.py compile <<< "$changed")
+ echo "compile-conformance=$conformance" >> "$GITHUB_OUTPUT"
+ echo "torch.compile conformance selection: '${conformance}'"
if grep -Eqv '^(docs/|.*\.md$|LICENSE$|COPYRIGHT$)' <<< "$changed"; then
echo "run-tests=true" >> "$GITHUB_OUTPUT"
else
@@ -245,7 +250,7 @@ jobs:
# ONNX conformance (#5819): every promised operator of the packages this PR can affect must export with the dynamo
# exporter and match eager in onnxruntime, and a legacy export that succeeds must not give wrong values. The
# `changes` job maps the changed paths to the packages they belong to plus every package that imports them
- # (.github/scripts/onnx_conformance_packages.py); the whole set runs on main twice a day on torch 2.9.1 and 2.14.0
+ # (.github/scripts/conformance_packages.py); the whole set runs on main twice a day on torch 2.9.1 and 2.14.0
# (scheduled_test_cpu.yml). No promised operator needs pretrained weights, so the job does not wait for `pre-tests`
# and also runs when only the survey or its snapshot under docs/ changed.
onnx-conformance:
@@ -258,7 +263,25 @@ jobs:
pytorch-version: '["2.14.0"]'
pytorch-dtype: float32
test-path: tests/onnx/test_conformance.py
- pytest-extra: --onnx-conformance=${{ needs.changes.outputs.onnx-conformance }}
+ # pytest-timeout fails a case that runs past 10 min and names it, rather than the job timeout ending the run
+ pytest-extra: --onnx-conformance=${{ needs.changes.outputs.onnx-conformance }} --timeout=600
+
+ # torch.compile conformance (#5819): every promised operator of the packages this PR can affect must compile with
+ # torch.compile(fullgraph=True) and the default inductor backend and match eager, selected like the ONNX job
+ # above (its own test file aside). The test compiles each case itself and does not use KORNIA_TEST_OPTIMIZER;
+ # inductor builds its kernels with the runner's g++.
+ compile-conformance:
+ needs: [changes]
+ if: needs.changes.outputs.compile-conformance != ''
+ uses: ./.github/workflows/tests.yml
+ with:
+ os: ubuntu-latest
+ python-version: '["3.11"]'
+ pytorch-version: '["2.14.0"]'
+ pytorch-dtype: float32
+ test-path: tests/test_inductor_conformance.py
+ # pytest-timeout fails a case that runs past 10 min and names it, rather than the job timeout ending the run
+ pytest-extra: --compile-conformance=${{ needs.changes.outputs.compile-conformance }} --timeout=600
typecheck:
needs: [pre-tests]
@@ -268,7 +291,7 @@ jobs:
# `collector` does not wait for it, so at PR time it cost ~12 runner-minutes without gating.
collector:
- needs: [changes, pre-tests, tests, tests-mps, half-precision, dynamo, onnx-conformance, typecheck]
+ needs: [changes, pre-tests, tests, tests-mps, half-precision, dynamo, onnx-conformance, compile-conformance, typecheck]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
diff --git a/.github/workflows/scheduled_test_cpu.yml b/.github/workflows/scheduled_test_cpu.yml
index 02c18b152..8ce79694a 100644
--- a/.github/workflows/scheduled_test_cpu.yml
+++ b/.github/workflows/scheduled_test_cpu.yml
@@ -99,8 +99,8 @@ jobs:
CHANGED_FILES=$(git diff --name-only "$PREV_SHA" HEAD)
- # Skip only if every changed file is documentation. The ONNX survey, its snapshot and the stability page
- # live under docs/ but define what the ONNX conformance job checks (#5819).
+ # Skip only if every changed file is documentation. The export survey, its snapshot and the stability page
+ # live under docs/ but define what the ONNX and compile conformance jobs check (#5819).
SHOULD_SKIP="true"
for file in $CHANGED_FILES; do
if [[ "$file" =~ ^docs/export_support/ ]] || \
@@ -210,7 +210,23 @@ jobs:
pytorch-version: '["2.9.1", "2.14.0"]'
pytorch-dtype: float32
test-path: tests/onnx/test_conformance.py
- pytest-extra: --onnx-conformance=all
+ # pytest-timeout fails a case that runs past 10 min and names it, rather than the job timeout ending the run
+ pytest-extra: --onnx-conformance=all --timeout=600
+
+ # torch.compile conformance (#5819) of every promised operator on both enforced torch releases; the PR run covers
+ # 2.14.0 for the packages a change touches and the packages that import them.
+ compile-conformance:
+ needs: [check-skip]
+ if: needs.check-skip.outputs.should-skip == 'false'
+ uses: ./.github/workflows/tests.yml
+ with:
+ os: ubuntu-latest
+ python-version: '["3.11"]'
+ pytorch-version: '["2.9.1", "2.14.0"]'
+ pytorch-dtype: float32
+ test-path: tests/test_inductor_conformance.py
+ # pytest-timeout fails a case that runs past 10 min and names it, rather than the job timeout ending the run
+ pytest-extra: --compile-conformance=all --timeout=600
tests-cpu-windows:
needs: [check-skip, pre-tests]
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index cb23d17ad..7f3e89a38 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -35,7 +35,7 @@ on:
default: cpu
test-path:
# Run only this test file or directory (`pixi run test-module <test-path>`) instead of the
- # whole suite (`pixi run test`, the default when empty). The ONNX conformance jobs use it.
+ # whole suite (`pixi run test`, the default when empty). The conformance jobs use it.
required: false
type: string
default: ""
diff --git a/AGENTS.md b/AGENTS.md
index 4943fe731..8d035524a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -57,7 +57,9 @@ Supported fixtures include CPU, CUDA, MPS, and TPU when available, and `float16`
`test-module` forwards its arguments to `pytest`, so a node ID or a `-k` expression narrows a run to a single test.
-Use `KORNIA_TEST_RUNSLOW=true` to include slow tests. `KORNIA_TEST_OPTIMIZER=inductor` enables the dynamo and compile tests, which are deselected when the variable is unset. `pixi run doctest` skips docstring examples that would download an uncached model checkpoint, so it stays fast and works offline; use `pixi run doctest-weights` (or `KORNIA_DOCTEST_DOWNLOAD=1`) to run those examples for real, which costs ~838 MB on a cold cache. Pull-request CI relies on the restored weights cache and skips whatever it misses; the scheduled run on `main` (00:23 and 12:23 UTC) downloads, so the model examples are always exercised somewhere. Before presenting a code change as finished, run the full pre-commit command above together with focused tests and other relevant checks; `pixi run lint` runs only the Ruff hooks.
+Use `KORNIA_TEST_RUNSLOW=true` to include slow tests. `KORNIA_TEST_OPTIMIZER=inductor` enables the dynamo and compile tests, which are deselected when the variable is unset; the torch.compile conformance test has its own option (below). `pixi run doctest` skips docstring examples that would download an uncached model checkpoint, so it stays fast and works offline; use `pixi run doctest-weights` (or `KORNIA_DOCTEST_DOWNLOAD=1`) to run those examples for real, which costs ~838 MB on a cold cache. Pull-request CI relies on the restored weights cache and skips whatever it misses; the scheduled run on `main` (00:23 and 12:23 UTC) downloads, so the model examples are always exercised somewhere. Before presenting a code change as finished, run the full pre-commit command above together with focused tests and other relevant checks; `pixi run lint` runs only the Ruff hooks.
+
+The stable-core operators the survey records as compiling without a graph break and matching eager are promised (#5819): `tests/test_inductor_conformance.py` compiles each with `torch.compile(..., fullgraph=True)` and the default inductor backend and compares the result with eager. It is opt-in, `pixi run test-module tests/test_inductor_conformance.py --compile-conformance=<package>|all`; run it for the packages a change touches and the packages that import them (`git diff --name-only origin/main... | python .github/scripts/conformance_packages.py compile` prints that selection), and see [TESTING.md](TESTING.md) for its known-failure manifests.
### Comparing a branch against another revision
@@ -143,7 +145,7 @@ Follow the methodology contract and new-benchmark checklist in [benchmarks/READM
ONNX support is a real subsystem, not a generic export afterthought. Inspect `kornia/onnx/`, its mixins in `kornia/core/`, and existing ONNX tests before changing export behavior. Development uses the optional `onnx`, `onnxruntime`, and `onnxscript` packages. Test both graph construction/export and runtime behavior when the change affects both.
-The stable-core operators the survey records as exporting are promised (#5819): `tests/onnx/test_conformance.py` exports each with the dynamo exporter and the legacy one and compares onnxruntime with eager. It is opt-in, `pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=<package>|all`; run it for the packages a change touches and the packages that import them (`git diff --name-only origin/main... | python .github/scripts/onnx_conformance_packages.py` prints that selection), and see [TESTING.md](TESTING.md) for its known-failure manifests.
+The stable-core operators the survey records as exporting are promised (#5819): `tests/onnx/test_conformance.py` exports each with the dynamo exporter and the legacy one and compares onnxruntime with eager. It is opt-in, `pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=<package>|all`; run it for the packages a change touches and the packages that import them (`git diff --name-only origin/main... | python .github/scripts/conformance_packages.py onnx` prints that selection), and see [TESTING.md](TESTING.md) for its known-failure manifests.
## Helping users diagnose problems
diff --git a/TESTING.md b/TESTING.md
index 08cd4b250..4e9d920be 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -43,6 +43,7 @@ pixi run test-quick
| `--known-failure-manifest=PATH` | none | unset | Replay a candidate manifest instead of the checked-in profile manifest |
| `--run-device-agnostic` | `KORNIA_TEST_RUN_DEVICE_AGNOSTIC` | off | Run `@pytest.mark.device_agnostic` tests even when CPU is not in the device matrix |
| `--onnx-conformance=PACKAGES` | `KORNIA_TEST_ONNX_CONFORMANCE` | unset | Run the ONNX conformance test for these stable-core packages (`geometry,color`, ...) or `all`; deselected otherwise (see below) |
+| `--compile-conformance=PACKAGES` | `KORNIA_TEST_COMPILE_CONFORMANCE` | unset | Run the torch.compile conformance test for these stable-core packages or `all`; deselected otherwise (see below) |
## Test Structure
@@ -71,6 +72,7 @@ The `device` and `dtype` fixtures are injected automatically from the CLI option
| `@pytest.mark.slow` | Long-running test; skipped unless `--runslow` is passed |
| `@pytest.mark.tf32` | Known to fail under TF32 (see section below); xfail unless `--tf32` |
| `@pytest.mark.onnx_conformance` | Part of the ONNX conformance test; deselected unless `--onnx-conformance` selects packages |
+| `@pytest.mark.compile_conformance` | Part of the torch.compile conformance test; deselected unless `--compile-conformance` selects packages |
### ONNX conformance (#5819)
@@ -90,7 +92,7 @@ pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=geometry,
```
The run takes minutes, so it is opt-in. Pull requests run it on torch 2.14.0 for the packages their changes reach
-(`.github/scripts/onnx_conformance_packages.py`: a changed module selects its stable-core package and every
+(`.github/scripts/conformance_packages.py onnx`: a changed module selects its stable-core package and every
stable-core package with a module that imports it, directly or not; `kornia/core`, `kornia/utils`, `kornia/onnx`, the
survey and its snapshot, the stability page, the test and its support, and the dependency pins select `all`); the
scheduled run on `main` checks `all` on torch 2.9.1 and 2.14.0. No promised case needs pretrained weights, and the test
@@ -98,8 +100,34 @@ never downloads.
Known failures are strict xfails in `testing/known_failure_xfails/onnx_conformance_torch<major>.<minor>.txt`, one
manifest per enforced torch release, in the `<exception>\t<node ID>` format of the other manifests, each entry under
-a comment naming its tracking issue. Entries of packages a run does not select are not checked. Delete an entry when
-its case passes (a strict XPASS fails the run); a new failure of a promised operator is a regression to fix.
+a comment naming its tracking issue. The exception type names the kind of failure (`STATUS_EXCEPTIONS` in
+`testing/conformance.py`): `AssertionError` for a result that differs from eager, `RuntimeError` for a failed export,
+checker or onnxruntime run (or, in the compile test, a failed compile), `ValueError` for a failed eager run, so a known
+failure that changes kind fails the run. Entries of packages a run does not select are not checked. Delete an entry
+when its case passes (a strict XPASS fails the run); a new failure of a promised operator is a regression to fix.
+
+### torch.compile conformance (#5819)
+
+`tests/test_inductor_conformance.py` holds the torch.compile promise the same way: every record of the survey snapshot
+with compile status `ok` (no graph break, values matching eager) in a stable-core package, without anything built from
+pretrained weights, must compile with `torch.compile(..., fullgraph=True)` and the default inductor backend and match
+eager execution (the same dtype, values within the case's tolerance). Each case is called once, at its registry input
+shapes, through the survey's own `docs/export_support/probe_compile.py`, with Dynamo reset around it; a recompile at
+another shape is not part of the promise. The selection, the drift guard, the pinned promised set and the manifests
+(`testing/known_failure_xfails/compile_conformance_torch<major>.<minor>.txt`) work as for the ONNX test, and both live
+in `testing/conformance.py`.
+
+```bash
+pixi run test-module tests/test_inductor_conformance.py --compile-conformance=all
+pixi run test-module tests/test_inductor_conformance.py --compile-conformance=color
+```
+
+It has its own option and does not read `KORNIA_TEST_OPTIMIZER`, and its tests are named after inductor because the
+root `conftest.py` drops tests whose name contains `compile` or `dynamo` when that variable is unset. Inductor needs a
+C++ compiler; onnx and onnxruntime are not needed. Pull requests run it on torch 2.14.0 for the packages
+`.github/scripts/conformance_packages.py compile` selects (the same mapping as the ONNX job, with this test file and
+its manifests in place of the ONNX ones); the scheduled run on `main` checks `all` on torch 2.9.1 and 2.14.0. Both
+conformance jobs run with `--timeout=600`.
---
diff --git a/changelog.d/6199.fixed.md b/changelog.d/6199.fixed.md
new file mode 100644
index 000000000..6fed70e76
--- /dev/null
+++ b/changelog.d/6199.fixed.md
@@ -0,0 +1,3 @@
+`kornia.enhance.threshold` and `kornia.enhance.Threshold` compile with `torch.compile(..., fullgraph=True)` on
+torch 2.9 and earlier, where they failed: the supported-type check no longer iterates the `ThresholdType` enum
+while tracing, which Dynamo there cannot do.
diff --git a/conftest.py b/conftest.py
index e385dbbef..47d9c3c45 100644
--- a/conftest.py
+++ b/conftest.py
@@ -34,7 +34,7 @@ from torch.distributions import Distribution
import kornia
from kornia.core.download import load_state_dict_from_url
-from testing import onnx_conformance
+from testing import conformance
from testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reason
from testing.half_precision_ci import (
FailureRecorder,
@@ -288,12 +288,15 @@ def _validate_complete_known_failure_run(config, option: str) -> None:
def pytest_configure(config) -> None:
"""Apply known-failure profiles before pytest_generate_tests reads device and dtype."""
- try:
- config._onnx_conformance = onnx_conformance.parse_selection(config.getoption(onnx_conformance.OPTION))
- except ValueError as error:
- raise pytest.UsageError(str(error)) from error
- if config._onnx_conformance:
- config.pluginmanager.register(onnx_conformance.KnownFailurePlugin(), "onnx-conformance-known-failures")
+ config._conformance = {}
+ for promise in conformance.PROMISES:
+ try:
+ config._conformance[promise.marker] = conformance.selection(config, promise)
+ except ValueError as error:
+ raise pytest.UsageError(str(error)) from error
+ if config._conformance[promise.marker]:
+ plugin = conformance.KnownFailurePlugin(promise)
+ config.pluginmanager.register(plugin, f"{promise.field}-conformance-known-failures")
profile = _configure_known_failure_profile(config)
config._known_failure_profile = profile
if profile is None:
@@ -432,10 +435,13 @@ def pytest_collection_modifyitems(config, items):
# Filter out tests with "dynamo" or "compile" in their name
items[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]
- # The ONNX conformance test (#5819) is opt-in: --onnx-conformance names the packages whose promised operators it
- # runs. When it is given, onnx_conformance.KnownFailurePlugin turns the known failures into strict xfails.
- if not config._onnx_conformance:
- conformance_items = [item for item in items if item.get_closest_marker(onnx_conformance.MARKER) is not None]
+ # The ONNX and torch.compile conformance tests (#5819) are opt-in: --onnx-conformance and --compile-conformance
+ # name the packages whose promised operators they run. When one is given, conformance.KnownFailurePlugin turns its
+ # known failures into strict xfails.
+ for promise in conformance.PROMISES:
+ if config._conformance[promise.marker]:
+ continue
+ conformance_items = [item for item in items if item.get_closest_marker(promise.marker) is not None]
if conformance_items:
config.hook.pytest_deselected(items=conformance_items)
conformance_ids = {id(item) for item in conformance_items}
@@ -593,17 +599,18 @@ def pytest_addoption(parser):
"(env: KORNIA_TEST_RUN_MPS_PROCESS_ABORT)"
),
)
- parser.addoption(
- onnx_conformance.OPTION,
- action="store",
- default=os.environ.get(onnx_conformance.ENV_VAR, ""),
- metavar="PACKAGES",
- help=(
- "Run the ONNX conformance test (tests/onnx/test_conformance.py, #5819) for these stable-core "
- "packages, comma-separated (geometry,color,...), or 'all'; it is deselected without this option. "
- f"(env: {onnx_conformance.ENV_VAR})"
- ),
- )
+ for promise in conformance.PROMISES:
+ parser.addoption(
+ promise.option,
+ action="store",
+ default=os.environ.get(promise.env_var, ""),
+ metavar="PACKAGES",
+ help=(
+ f"Run the {promise.name} conformance test ({promise.test_file}, #5819) for these stable-core "
+ "packages, comma-separated (geometry,color,...), or 'all'; it is deselected without this option. "
+ f"(env: {promise.env_var})"
+ ),
+ )
parser.addoption(
"--xfail-known-failures",
action="store_true",
diff --git a/docs/export_support/README.md b/docs/export_support/README.md
index 812a1a2c9..ea9b05dee 100644
--- a/docs/export_support/README.md
+++ b/docs/export_support/README.md
@@ -25,20 +25,24 @@ For each case:
then an `onnxruntime` run compared against eager: the same dtype, and values within the case's tolerance.
- **torch.export** and **torch.compile** (`probe_compile.py`): `torch.export.export`, then
`torch._dynamo.explain` for the graph-break count and a `torch.compile` run compared against
- eager.
+ eager. The count is the operator's own: the wrapper returns a tensor output without probing its
+ attributes, which would be a break of its own after a resumed frame. An explain count of 0 is not
+ proof of a single graph (Dynamo can run part of a frame eagerly without recording a break; #6194);
+ the conformance test compiles with `fullgraph=True`.
Random operators cannot be compared value-for-value (the RNG stream differs inside the graph), so
they are reported as *ok-unverified* when the captured program runs and returns finite outputs of
the right shape.
-The cases also drive the ONNX conformance test, `tests/onnx/test_conformance.py` (#5819): every
-case the snapshot records as ONNX "ok" in a stable-core package, and not tagged `pretrained`, is
-promised, and the test runs it through the same `harness.run_case` on every pull request that
-touches its package or a module it imports. Renaming,
-skipping or dropping a promised case therefore fails that test, and the harness must not change
-the process it is imported into: the survey's own process settings (quiet logging and warnings,
-four threads) are applied by `run_cases` and `probe_compile.py` through
-`harness.configure_survey_process()`, not at import.
+The cases also drive the conformance tests of #5819. Every case the snapshot records as ONNX "ok"
+in a stable-core package, and not tagged `pretrained`, is promised to `tests/onnx/test_conformance.py`,
+which runs it through the same `harness.run_case`; every such case recorded as compile "ok" is promised
+to `tests/test_inductor_conformance.py`, which runs it through `probe_compile.run_case(case,
+export=False, fullgraph=True)`. Pull requests run both for the packages they touch and the packages
+that import them. Renaming, skipping or dropping a promised case therefore fails those tests, and the
+harness and the probe must not change the process they are imported into: the survey's own process
+settings (quiet logging and warnings, four threads, the compile probe's per-case timeout and Dynamo
+cache limit) are applied by `run_cases` and `probe_compile.main`, not at import.
## Regenerating the snapshot
diff --git a/docs/export_support/cases_feature.py b/docs/export_support/cases_feature.py
index e94e962f5..37f89fd9f 100644
--- a/docs/export_support/cases_feature.py
+++ b/docs/export_support/cases_feature.py
@@ -37,6 +37,8 @@ IMG_BIG = torch.rand(1, 1, 64, 80) # detectors need a pyramid
IMG3_BIG = torch.rand(1, 3, 64, 80)
IMG3_96 = torch.rand(1, 3, 64, 96) # divisible by 16 and 32 (DISK / XFeat)
IMG3_DEDODE = torch.rand(1, 3, 56, 84) # divisible by 14
+# 8-pixel checkerboard: strong corners, so the Harris response (~1e-3 on noise) is large against the default atol
+IMG_CORNERS = ((torch.arange(32)[:, None] // 8 + torch.arange(40)[None, :] // 8) % 2).float()[None, None]
PATCH32 = torch.rand(2, 1, 32, 32)
PATCH41 = torch.rand(2, 1, 41, 41)
PATCH19 = torch.rand(2, 1, 19, 19)
@@ -142,7 +144,7 @@ CASES: list = []
# ----------------------------------------------------------------------------- responses
R = "feature.responses"
CASES += [
- case("feature.harris_response", R, KF.harris_response, [IMG]),
+ case("feature.harris_response", R, KF.harris_response, [IMG_CORNERS]),
case("feature.harris_response[sigmas]", R, KF.harris_response, [IMG, torch.tensor([1.5])], note="sigmas (B,) live"),
case("feature.harris_response[diff]", R, KF.harris_response, [IMG], {"grads_mode": "diff"}),
case("feature.gftt_response", R, KF.gftt_response, [IMG]),
@@ -156,7 +158,7 @@ CASES += [
tags=("3d",),
),
case("feature.dog_response_single", R, KF.dog_response_single, [IMG], {"sigma1": 1.0, "sigma2": 1.6}),
- case("feature.CornerHarris", R, KF.CornerHarris(0.04), [IMG]),
+ case("feature.CornerHarris", R, KF.CornerHarris(0.04), [IMG_CORNERS]),
case("feature.CornerGFTT", R, KF.CornerGFTT(), [IMG]),
case("feature.BlobHessian", R, KF.BlobHessian(), [IMG]),
case(
diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.py
index c0c254f09..0dd7be7c9 100644
--- a/docs/export_support/cases_geomA.py
+++ b/docs/export_support/cases_geomA.py
@@ -146,6 +146,10 @@ boxes_xyxy = torch.tensor([[[2.0, 3.0, 20.0, 25.0], [10.0, 5.0, 35.0, 30.0]]])
boxes_quad = Boxes.from_tensor(boxes_xyxy, mode="xyxy").data # (1,2,4,2)
boxes3d_xyzxyz = torch.tensor([[[1.0, 2.0, 1.0, 10.0, 12.0, 6.0], [3.0, 3.0, 2.0, 14.0, 14.0, 7.0]]]) # (1,2,6)
boxes3d_hexa = Boxes3D.from_tensor(boxes3d_xyzxyz, mode="xyzxyz").data # (1,2,8,3)
+# depths, heights and widths all distinct, for the shape cases: a graph that swapped two of them would not match
+boxes3d_hexa_shapes = Boxes3D.from_tensor(
+ torch.tensor([[[1.0, 2.0, 1.0, 10.0, 12.0, 6.0], [3.0, 3.0, 2.0, 14.0, 9.0, 9.0]]]), mode="xyzxyz"
+).data # (1,2,8,3): (d, h, w) = (5, 10, 9) and (7, 6, 11)
nms_boxes = torch.tensor([[10.0, 10.0, 20.0, 20.0], [15.0, 5.0, 15.0, 25.0], [100.0, 100.0, 150.0, 150.0]])
nms_scores = torch.tensor([0.9, 0.8, 0.7])
kpts = torch.tensor([[[5.0, 6.0], [20.0, 10.0], [30.0, 25.0]]]) # (1,3,2)
@@ -622,7 +626,7 @@ CASES += [
note="size baked; input (N,8,3)",
),
case("bbox.infer_bbox_shape", G, infer_bbox_shape, [boxes_quad[0]]),
- case("bbox.infer_bbox_shape3d", G, infer_bbox_shape3d, [boxes3d_hexa[0]], tags=("3d",)),
+ case("bbox.infer_bbox_shape3d", G, infer_bbox_shape3d, [boxes3d_hexa_shapes[0]], tags=("3d",)),
case("bbox.transform_bbox", G, transform_bbox, [homo33, boxes_xyxy], note="mode=xyxy default (B,N,4)"),
case(
"bbox.transform_bbox[xywh]",
@@ -798,7 +802,7 @@ CASES += [
"boxes.Boxes3D.get_boxes_shape",
G,
lambda b: Boxes3D(b, mode="xyzxyz_plus").get_boxes_shape(),
- [boxes3d_hexa],
+ [boxes3d_hexa_shapes],
tags=("3d",),
),
case(
diff --git a/docs/export_support/cases_geomB.py b/docs/export_support/cases_geomB.py
index 3190e11f3..ced530b21 100644
--- a/docs/export_support/cases_geomB.py
+++ b/docs/export_support/cases_geomB.py
@@ -68,6 +68,13 @@ hp2_4 = hp2[:, :4]
ls1 = torch.rand(1, N, 2, 2) * torch.tensor([40.0, 32.0])
ls2 = L.transform_points(H_gt, ls1.reshape(1, -1, 2)).reshape(1, N, 2, 2)
w_ones = torch.ones(1, N)
+# Correspondences about a pixel off the model, for the distance and transfer-error cases: on the exact ones above those
+# are ~0, and a graph that returned zeros would match them within atol. A private generator keeps the registry's global
+# random stream, and with it every other case's inputs, unchanged.
+_noise = torch.Generator().manual_seed(1)
+pts2_off = pts2 + torch.randn(pts2.shape, generator=_noise)
+hp2_off = hp2 + torch.randn(hp2.shape, generator=_noise)
+ls2_off = ls2 + torch.randn(ls2.shape, generator=_noise)
# rotations / quaternions
aa = torch.tensor([[0.1, -0.2, 0.3], [1.0, 0.5, -0.4]]) # (2,3) axis-angle
@@ -309,10 +316,10 @@ CASES = [
_ch(
"line_segment_transfer_error_one_way",
K.geometry.homography.line_segment_transfer_error_one_way,
- [ls1, ls2, H_gt],
+ [ls1, ls2_off, H_gt],
),
- _ch("oneway_transfer_error", K.geometry.homography.oneway_transfer_error, [hp1, hp2, H_gt]),
- _ch("symmetric_transfer_error", K.geometry.homography.symmetric_transfer_error, [hp1, hp2, H_gt]),
+ _ch("oneway_transfer_error", K.geometry.homography.oneway_transfer_error, [hp1, hp2_off, H_gt]),
+ _ch("symmetric_transfer_error", K.geometry.homography.symmetric_transfer_error, [hp1, hp2_off, H_gt]),
_ch(
"sample_is_valid_for_homography",
K.geometry.homography.sample_is_valid_for_homography,
@@ -365,17 +372,17 @@ CASES = [
_ce("normalize_transformation", E.normalize_transformation, [F_gt * 3.0]),
_ce("get_perpendicular", E.get_perpendicular, [torch.rand(1, N, 3) + 0.1, pts1]),
_ce("get_closest_point_on_epipolar_line", E.get_closest_point_on_epipolar_line, [pts1, pts2, F_gt]),
- _ce("sampson_epipolar_distance", E.sampson_epipolar_distance, [pts1, pts2, F_gt]),
+ _ce("sampson_epipolar_distance", E.sampson_epipolar_distance, [pts1, pts2_off, F_gt]),
_ce(
"sampson_epipolar_distance[no-matmul]",
E.sampson_epipolar_distance,
- [pts1, pts2, F_gt],
+ [pts1, pts2_off, F_gt],
{"use_matmul_at_less_than_points": 0},
note="einsum path",
),
- _ce("symmetrical_epipolar_distance", E.symmetrical_epipolar_distance, [pts1, pts2, F_gt]),
- _ce("left_to_right_epipolar_distance", E.left_to_right_epipolar_distance, [pts1, pts2, F_gt]),
- _ce("right_to_left_epipolar_distance", E.right_to_left_epipolar_distance, [pts1, pts2, F_gt]),
+ _ce("symmetrical_epipolar_distance", E.symmetrical_epipolar_distance, [pts1, pts2_off, F_gt]),
+ _ce("left_to_right_epipolar_distance", E.left_to_right_epipolar_distance, [pts1, pts2_off, F_gt]),
+ _ce("right_to_left_epipolar_distance", E.right_to_left_epipolar_distance, [pts1, pts2_off, F_gt]),
_ce("projection_from_KRt", E.projection_from_KRt, [Kmat, R2, t2]),
_ce("projections_from_fundamental", E.projections_from_fundamental, [F_gt], atol=1e-3),
_ce("KRt_from_projection", E.KRt_from_projection, [P2], atol=1e-3),
diff --git a/docs/export_support/harness.py b/docs/export_support/harness.py
index 1968240e2..437f71353 100644
--- a/docs/export_support/harness.py
+++ b/docs/export_support/harness.py
@@ -32,7 +32,8 @@ the graph. The harness:
Importing this module (or a registry) leaves the process alone: the survey entry points (``run_cases``,
``probe_compile.main``) call ``configure_survey_process`` for their quieter, fixed-thread-count settings, so
-``tests/onnx/test_conformance.py`` can drive ``run_case`` inside a pytest session.
+``tests/onnx/test_conformance.py`` can drive ``run_case`` inside a pytest session. ``onnx`` and ``onnxruntime`` are
+imported where they are used, so the compile probe and ``tests/test_inductor_conformance.py`` do not need them.
Usage from a registry file::
@@ -58,15 +59,16 @@ import subprocess
import time
import traceback
import warnings
-from typing import Any
+from typing import TYPE_CHECKING, Any
import numpy as np
-import onnx
-import onnxruntime as ort
import torch
from torch import nn
from torch.utils._pytree import tree_flatten
+if TYPE_CHECKING:
+ import onnx
+
SEED = 1234
OPSET = 18 # the opset the dynamo export requests, and the ceiling of the legacy one
@@ -75,7 +77,12 @@ def configure_survey_process() -> None:
"""Quiet logs and warnings and fix the thread count, for a process that runs survey probes and nothing else."""
logging.disable(logging.CRITICAL)
warnings.filterwarnings("ignore")
- ort.set_default_logger_severity(3)
+ try:
+ import onnxruntime as ort
+ except ImportError: # the compile probe runs without it
+ pass
+ else:
+ ort.set_default_logger_severity(3)
torch.set_num_threads(4)
@@ -129,8 +136,13 @@ def case(
def _flatten_outputs(out: Any) -> list[torch.Tensor]:
+ # A tensor first, before any attribute probe: on torch 2.5 ``hasattr(tensor, "data")`` inside a ``torch.export``
+ # trace raises "Attempting to use FunctionalTensor on its own", which fails the export of every operator that
+ # returns a plain tensor (the dynamo ONNX exporter then falls back to its TorchScript-trace strategy).
+ if isinstance(out, torch.Tensor):
+ return [out]
# dataclass-like kornia containers (Boxes, Keypoints, Se3, Quaternion, Image...) expose tensors via attributes
- if hasattr(out, "data") and isinstance(out.data, torch.Tensor) and not isinstance(out, torch.Tensor):
+ if hasattr(out, "data") and isinstance(out.data, torch.Tensor):
return [out.data]
if hasattr(out, "__dict__") and not isinstance(out, (torch.Tensor, dict, list, tuple)):
vals = []
@@ -188,21 +200,39 @@ def to_np(x: torch.Tensor) -> np.ndarray:
return x.numpy()
-def close(a: np.ndarray, b: np.ndarray, atol: float, rtol: float) -> tuple[bool, str]:
- """Compare a reference ``a`` with ``b``: the same shape and dtype, then the values within ``atol`` / ``rtol``."""
- a, b = np.asarray(a), np.asarray(b)
+def _dtype_name(x: Any) -> str:
+ """The dtype of a tensor or an array as numpy names it (``float32``, ``bfloat16``, ``bool``)."""
+ return str(x.dtype).removeprefix("torch.") if isinstance(x, torch.Tensor) else str(np.asarray(x).dtype)
+
+
+def close(a: Any, b: Any, atol: float, rtol: float) -> tuple[bool, str]:
+ """Compare a reference ``a`` with a candidate ``b``, tensors or arrays: the same shape and dtype, then the values.
+
+ The dtypes are compared before any conversion (``to_np`` widens bfloat16), the values within ``atol`` / ``rtol``.
+ Complex values are compared componentwise, including their NaN patterns: a NaN in one component must not hide
+ a mismatch in the other.
+ """
+ dtype_a, dtype_b = _dtype_name(a), _dtype_name(b)
+ a = to_np(a) if isinstance(a, torch.Tensor) else np.asarray(a)
+ b = to_np(b) if isinstance(b, torch.Tensor) else np.asarray(b)
if a.shape != b.shape:
return False, f"shape {a.shape} vs {b.shape}"
- if a.dtype != b.dtype:
- return False, f"dtype {a.dtype} vs {b.dtype}"
+ if dtype_a != dtype_b:
+ return False, f"dtype {dtype_a} vs {dtype_b}"
if bool in (a.dtype, b.dtype):
ok = bool(np.array_equal(a, b))
return ok, "" if ok else f"{int((a != b).sum())} bool mismatches"
+ if np.iscomplexobj(a):
+ for component in ("real", "imag"):
+ ok, why = close(getattr(a, component), getattr(b, component), atol, rtol)
+ if not ok:
+ return False, f"{component}: {why}"
+ return True, ""
a64, b64 = a.astype(np.float64), b.astype(np.float64)
nan_a, nan_b = np.isnan(a64), np.isnan(b64)
if nan_a.any() or nan_b.any():
if not np.array_equal(nan_a, nan_b):
- return False, f"NaN pattern differs (torch {int(nan_a.sum())}, ort {int(nan_b.sum())} NaNs)"
+ return False, f"NaN pattern differs (reference {int(nan_a.sum())}, candidate {int(nan_b.sum())} NaNs)"
a64, b64 = a64[~nan_a], b64[~nan_b]
ok = bool(np.allclose(a64, b64, atol=atol, rtol=rtol))
if ok:
@@ -231,6 +261,8 @@ def shape_and_finite(ref: list[torch.Tensor], out: list[Any]) -> str | None:
def op_types(model: onnx.ModelProto) -> list[str]:
+ import onnx
+
s: set[str] = set()
def walk(graph: onnx.GraphProto) -> None:
@@ -295,6 +327,8 @@ def legacy_opset() -> int:
def export(m: nn.Module, inputs: list[torch.Tensor], dynamo: bool = True) -> onnx.ModelProto:
"""Export ``m`` called on ``inputs`` with the dynamo exporter (opset 18) or the legacy TorchScript one."""
+ import onnx
+
buf = io.BytesIO()
if dynamo:
kwargs: dict[str, Any] = {
@@ -328,6 +362,9 @@ def export(m: nn.Module, inputs: list[torch.Tensor], dynamo: bool = True) -> onn
def run_case(c: dict[str, Any], dynamo: bool = True) -> dict[str, Any]:
"""Probe one case (see the module docstring) with the dynamo or the legacy exporter; return its record."""
+ import onnx
+ import onnxruntime as ort
+
rec: dict[str, Any] = {k: c[k] for k in ("name", "group", "note", "tags", "check")}
rec["n_inputs"] = len(c["inputs"])
rec["input_shapes"] = [list(x.shape) + [str(x.dtype).replace("torch.", "")] for x in c["inputs"]]
@@ -343,8 +380,10 @@ def run_case(c: dict[str, Any], dynamo: bool = True) -> dict[str, Any]:
wrap = make_wrapper(target, c["kwargs"], len(c["inputs"]), c["method"])
inputs = [x.detach().clone() for x in c["inputs"]]
torch.manual_seed(SEED)
+ # Eager and the export each run on their own copy: the export reads none of the state the eager call leaves
+ # on a module, and neither leaves state (a dynamo export's fake tensors) on the case, which later tests reuse.
with torch.no_grad():
- ref = wrap(*copy.deepcopy(inputs))
+ ref = copy.deepcopy(wrap)(*copy.deepcopy(inputs))
rec["n_outputs"] = len(ref)
rec["output_shapes"] = [list(x.shape) + [str(x.dtype).replace("torch.", "")] for x in ref]
except Exception as e:
@@ -355,7 +394,7 @@ def run_case(c: dict[str, Any], dynamo: bool = True) -> dict[str, Any]:
torch.manual_seed(SEED)
# the legacy exporter traces with the real tensors, so an operator that updates its input in place would
# otherwise leave onnxruntime fed with the updated values
- model = export(wrap, copy.deepcopy(inputs), dynamo=dynamo)
+ model = export(copy.deepcopy(wrap), copy.deepcopy(inputs), dynamo=dynamo)
except Exception as e:
rec.update(
status="export-fail",
@@ -417,7 +456,7 @@ def run_case(c: dict[str, Any], dynamo: bool = True) -> dict[str, Any]:
return rec
bad = []
for i, (a, b) in enumerate(zip(ref, outs)):
- ok, why = close(to_np(a), b, c["atol"], c["rtol"])
+ ok, why = close(a, b, c["atol"], c["rtol"])
if not ok:
bad.append(f"out{i}: {why}")
if bad:
diff --git a/docs/export_support/probe_compile.py b/docs/export_support/probe_compile.py
index f7666c8cc..43862c510 100644
--- a/docs/export_support/probe_compile.py
+++ b/docs/export_support/probe_compile.py
@@ -24,6 +24,10 @@ Per case records:
compile: ok | ok-breaks:N | ok-unverified | mismatch | fail | eager-fail | skipped
(torch.compile default inductor backend, fullgraph=False; N = dynamo graph breaks)
plus the target's importable qualified name when it has one.
+
+``run_case(c, export=False, fullgraph=True)`` is the compile step alone with ``torch.compile(..., fullgraph=True)``,
+where a graph break fails the case: the check ``tests/test_inductor_conformance.py`` runs on the promised cases.
+Importing this module leaves the process alone (``main`` installs the per-case timeout and the survey's settings).
"""
from __future__ import annotations
@@ -43,11 +47,11 @@ from harness import (
_kornia_frames,
close,
configure_survey_process,
+ err_full,
err_str,
make_wrapper,
prepare_resume,
shape_and_finite,
- to_np,
)
from torch import nn
@@ -70,12 +74,12 @@ def _alarm(signum, frame):
_HAS_ALARM = hasattr(signal, "SIGALRM") # POSIX only; on Windows the probes simply run without a timeout
-if _HAS_ALARM:
- signal.signal(signal.SIGALRM, _alarm)
def _set_alarm(seconds: int) -> None:
- if _HAS_ALARM:
+ # only under main's handler: another process (a pytest session) keeps its own SIGALRM, and without a handler
+ # the signal would end the process
+ if _HAS_ALARM and signal.getsignal(signal.SIGALRM) is _alarm:
signal.alarm(seconds)
@@ -97,69 +101,71 @@ def _compare(ref: list[torch.Tensor], out: list[torch.Tensor], c: dict[str, Any]
return f"{len(out)} outputs vs {len(ref)}"
bad = []
for i, (a, b) in enumerate(zip(ref, out)):
- ok, why = close(to_np(a), to_np(b), c["atol"], c["rtol"])
+ ok, why = close(a, b, c["atol"], c["rtol"])
if not ok:
bad.append(f"out{i}: {why}")
return "; ".join(bad)[:400] if bad else None
-def run_case(c: dict[str, Any]) -> dict[str, Any]:
- rec: dict[str, Any] = {
- "name": c["name"],
- "group": c["group"],
- "note": c["note"],
- "tags": c["tags"],
- "qualname": qualname(c["target"], c["method"]),
- }
- if c["skip"]:
- rec.update(export="skipped", compile="skipped", skip=c["skip"])
- return rec
- t0 = time.time()
- try:
- target = c["target"]
- if isinstance(target, nn.Module):
- target.eval()
- wrap = make_wrapper(target, c["kwargs"], len(c["inputs"]), c["method"])
- inputs = [x.detach().clone() for x in c["inputs"]]
- torch.manual_seed(SEED)
- with torch.no_grad():
- ref = list(wrap(*copy.deepcopy(inputs)))
- except Exception as e:
- if "PythonDispatcherTLS" in str(e):
- raise Poisoned(rec["name"]) from e
- st = "no-tensor-output" if "NO_TENSOR_OUTPUT" in str(e) else "eager-fail"
- rec.update(export=st, compile=st, error=err_str(e))
- return rec
+def _reference(c: dict[str, Any]) -> tuple[nn.Module, list[torch.Tensor], list[torch.Tensor]]:
+ """The case's wrapper, a copy of its inputs, and its eager outputs.
- # ---- torch.export
+ The eager call runs on a copy of the wrapper, and the export and compile steps take their own copies, so none
+ reads the state another left on a module (an augmentation's params, a crop's cached points, an export's fake
+ tensors): a compiled graph that skips computing such state cannot pass by reading what eager left there, and the
+ case, which later tests reuse, stays as it was built.
+ """
+ target = c["target"]
+ if isinstance(target, nn.Module):
+ target.eval()
+ wrap = make_wrapper(target, c["kwargs"], len(c["inputs"]), c["method"])
+ inputs = [x.detach().clone() for x in c["inputs"]]
+ torch.manual_seed(SEED)
+ with torch.no_grad():
+ ref = list(copy.deepcopy(wrap)(*copy.deepcopy(inputs)))
+ return wrap, inputs, ref
+
+
+def export_step(wrap: nn.Module, inputs: list[torch.Tensor]) -> dict[str, Any]:
+ """``torch.export.export`` of the wrapper: the ``export`` fields of a record."""
+ rec: dict[str, Any] = {}
_set_alarm(TIMEOUT)
try:
torch.manual_seed(SEED)
with torch.no_grad():
- torch.export.export(wrap, tuple(copy.deepcopy(inputs)))
+ torch.export.export(copy.deepcopy(wrap), tuple(copy.deepcopy(inputs)))
rec["export"] = "ok"
- except BaseException as e:
- if isinstance(e, KeyboardInterrupt):
- raise
+ except Exception as e: # not BaseException: KeyboardInterrupt and a test's outcome (pytest-timeout) end the run
rec.update(export="fail", export_error=err_str(e), export_where=_kornia_frames(e))
finally:
_set_alarm(0)
- rec["export_s"] = round(time.time() - t0, 1)
+ return rec
+
+
+def compile_step(
+ c: dict[str, Any], wrap: nn.Module, inputs: list[torch.Tensor], ref: list[torch.Tensor], fullgraph: bool = False
+) -> dict[str, Any]:
+ """``torch.compile`` (default inductor backend) of the wrapper, compared with ``ref``: the ``compile`` fields.
- # ---- torch.compile (dynamo capture stats, then inductor run)
+ With ``fullgraph=False`` (the survey) ``torch._dynamo.explain`` counts the graph breaks first; with
+ ``fullgraph=True`` a graph break fails the compile, so a passing case has none. Dynamo is reset before and after.
+ """
+ rec: dict[str, Any] = {}
t1 = time.time()
_set_alarm(TIMEOUT)
try:
torch._dynamo.reset()
- torch.manual_seed(SEED)
- with torch.no_grad():
- ex = torch._dynamo.explain(wrap)(*copy.deepcopy(inputs))
- breaks = int(ex.graph_break_count)
+ breaks = 0
+ if not fullgraph:
+ torch.manual_seed(SEED)
+ with torch.no_grad():
+ ex = torch._dynamo.explain(copy.deepcopy(wrap))(*copy.deepcopy(inputs))
+ breaks = int(ex.graph_break_count)
+ torch._dynamo.reset()
rec["graph_breaks"] = breaks
if breaks:
rec["break_reasons"] = sorted({str(r.reason)[:160] for r in ex.break_reasons})[:5]
- torch._dynamo.reset()
- compiled = torch.compile(wrap)
+ compiled = torch.compile(copy.deepcopy(wrap), fullgraph=fullgraph)
torch.manual_seed(SEED)
with torch.no_grad():
out = list(compiled(*copy.deepcopy(inputs)))
@@ -171,10 +177,10 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:
rec["compile"] = ("ok" if breaks == 0 else f"ok-breaks:{breaks}") if why is None else "mismatch"
if why:
rec["compile_error"] = why
- except BaseException as e:
- if isinstance(e, KeyboardInterrupt):
- raise
- rec.update(compile="fail", compile_error=err_str(e), compile_where=_kornia_frames(e))
+ except Exception as e: # the survey's own Timeout is one; a pytest outcome or KeyboardInterrupt is not
+ rec.update(
+ compile="fail", compile_error=err_str(e), compile_error_full=err_full(e), compile_where=_kornia_frames(e)
+ )
finally:
_set_alarm(0)
torch._dynamo.reset()
@@ -182,8 +188,38 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:
return rec
+def run_case(c: dict[str, Any], export: bool = True, fullgraph: bool = False) -> dict[str, Any]:
+ """Probe one case: eager reference, ``torch.export`` (unless ``export=False``), then ``torch.compile``."""
+ rec: dict[str, Any] = {
+ "name": c["name"],
+ "group": c["group"],
+ "note": c["note"],
+ "tags": c["tags"],
+ "qualname": qualname(c["target"], c["method"]),
+ }
+ if c["skip"]:
+ rec.update(export="skipped", compile="skipped", skip=c["skip"])
+ return rec
+ t0 = time.time()
+ try:
+ wrap, inputs, ref = _reference(c)
+ except Exception as e:
+ if "PythonDispatcherTLS" in str(e):
+ raise Poisoned(rec["name"]) from e
+ st = "no-tensor-output" if "NO_TENSOR_OUTPUT" in str(e) else "eager-fail"
+ rec.update(export=st, compile=st, error=err_str(e))
+ return rec
+ if export:
+ rec.update(export_step(wrap, inputs))
+ rec["export_s"] = round(time.time() - t0, 1)
+ rec.update(compile_step(c, wrap, inputs, ref, fullgraph=fullgraph))
+ return rec
+
+
def main() -> None:
configure_survey_process()
+ if _HAS_ALARM:
+ signal.signal(signal.SIGALRM, _alarm)
torch._dynamo.config.cache_size_limit = 64
torch._dynamo.config.suppress_errors = False
mod = importlib.import_module(sys.argv[1])
diff --git a/kornia/enhance/threshold.py b/kornia/enhance/threshold.py
index 9d37dd709..f26aff12a 100644
--- a/kornia/enhance/threshold.py
+++ b/kornia/enhance/threshold.py
@@ -46,6 +46,11 @@ class ThresholdType(IntEnum):
THRESH_OTSU = 8
+# The fixed types ``threshold`` implements. Built once here: iterating the enum class inside ``threshold`` breaks
+# ``torch.compile(fullgraph=True)`` on torch 2.9 (Dynamo cannot trace ``EnumMeta.__iter__`` there).
+_FIXED_TYPES = frozenset(int(x) for x in ThresholdType if x != ThresholdType.THRESH_OTSU)
+
+
def _integer_threshold(input: Tensor, thresh: Union[float, Tensor]) -> tuple[Tensor, Tensor]:
"""Return ``input > thresh`` and the value THRESH_TRUNC writes, for an integer ``input``.
@@ -118,7 +123,7 @@ def threshold(
raise NotImplementedError("THRESH_OTSU is not implemented yet. Please use a fixed threshold type.")
KORNIA_CHECK(
- t in {int(x) for x in ThresholdType if x != ThresholdType.THRESH_OTSU},
+ t in _FIXED_TYPES,
lambda: f"Unsupported threshold type: {type}. Supported: BINARY, BINARY_INV, TRUNC, TOZERO, TOZERO_INV.",
)
diff --git a/pyproject.toml b/pyproject.toml
index 56aac8944..4a7945046 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -173,6 +173,7 @@ filterwarnings = [
]
markers = [
"device_agnostic: run CPU-only test logic once in a CPU-containing device matrix",
+ "compile_conformance: torch.compile conformance of the promised operators (#5819); deselected unless --compile-conformance selects packages",
"mps_process_abort: aborts the pytest process on MPS on virtualized Apple GPUs (#4204); skipped there unless --run-mps-process-abort",
"onnx_conformance: ONNX conformance of the promised operators (#5819); deselected unless --onnx-conformance selects packages",
"slow: mark test as slow to run",
diff --git a/testing/conformance.py b/testing/conformance.py
new file mode 100644
index 000000000..50a2042ca
--- /dev/null
+++ b/testing/conformance.py
@@ -0,0 +1,589 @@
+# 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.
+#
+
+"""Support for the conformance tests of #5819: kornia's ONNX and torch.compile promises, checked with the survey's
+own cases.
+
+Two promises share this machinery, ``ONNX`` and ``COMPILE``. The promised cases of each are the records of the
+committed survey snapshot (``docs/source/_data/export_support.json``) whose status for it (field ``onnx`` or
+``compile``) is ``ok`` and whose package is in the stable core of ``docs/source/get-started/stability.rst``, minus
+everything built with pretrained weights (registry tag ``pretrained``): the stable core holds only the classical,
+non-pretrained parts of ``kornia.feature``. Each is run by case name through the survey's own code, so the tests and
+the survey page cannot drift apart:
+
+- ``tests/onnx/test_conformance.py`` exports through ``docs/export_support/harness.py`` (``run_onnx_case``);
+- ``tests/test_inductor_conformance.py`` compiles through ``docs/export_support/probe_compile.py``
+ (``run_compile_case``: ``torch.compile(..., fullgraph=True)``, default inductor backend).
+
+Each run is opt-in: ``--onnx-conformance`` or ``--compile-conformance`` with ``<package>[,<package>...]`` or ``all``
+(env ``KORNIA_TEST_ONNX_CONFORMANCE`` / ``KORNIA_TEST_COMPILE_CONFORMANCE``); without it the root ``conftest.py``
+deselects every test with that promise's marker. Known failures are strict xfails listed per promise and torch release
+in ``testing/known_failure_xfails/<onnx|compile>_conformance_torch<major>.<minor>.txt``.
+"""
+
+from __future__ import annotations
+
+import ast
+import contextlib
+import functools
+import hashlib
+import importlib
+import io
+import json
+import logging
+import pickle
+import re
+import signal
+import sys
+import warnings
+from dataclasses import dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Iterable, Iterator, Sequence
+
+import pytest
+import torch
+
+from testing.known_failures import _EXCEPTION_TYPES, KnownFailureTracker
+
+REPO = Path(__file__).resolve().parents[1]
+EXPORT_SUPPORT = REPO / "docs" / "export_support"
+SNAPSHOT = REPO / "docs" / "source" / "_data" / "export_support.json"
+MANIFEST_DIR = Path(__file__).with_name("known_failure_xfails")
+
+
+@dataclass(frozen=True)
+class Promise:
+ """One conformance promise: the snapshot status it promises, how a run selects it, and where its tests live."""
+
+ name: str # in messages: "ONNX", "torch.compile"
+ field: str # the snapshot's status field, and the stem of the option, marker and manifests
+ test_file: str
+ case_tests: tuple[str, ...] # the per-case tests, parametrized by case name
+
+ @property
+ def option(self) -> str:
+ return f"--{self.field}-conformance"
+
+ @property
+ def env_var(self) -> str:
+ return f"KORNIA_TEST_{self.field.upper()}_CONFORMANCE"
+
+ @property
+ def marker(self) -> str:
+ return f"{self.field}_conformance"
+
+
+ONNX = Promise(
+ "ONNX", "onnx", "tests/onnx/test_conformance.py", ("test_export_matches_eager", "test_legacy_export_is_not_wrong")
+)
+# The root conftest deselects tests whose name or id contains "compile" or "dynamo" unless KORNIA_TEST_OPTIMIZER is set,
+# so the compile promise's tests are named after inductor; only the option and the marker say "compile".
+COMPILE = Promise("torch.compile", "compile", "tests/test_inductor_conformance.py", ("test_inductor_matches_eager",))
+PROMISES = (ONNX, COMPILE)
+# The torch releases whose manifests the scheduled conformance jobs enforce (scheduled_test_cpu.yml).
+ENFORCED_TORCH_RELEASES = ("2.9", "2.14")
+
+# The stable core of docs/source/get-started/stability.rst, as the ``kornia.<package>`` names the snapshot records.
+# tests/scripts/test_conformance_packages.py checks it against that page and against the CI path mapping.
+STABLE_CORE = (
+ "geometry",
+ "augmentation",
+ "color",
+ "filters",
+ "enhance",
+ "losses",
+ "metrics",
+ "morphology",
+ "io",
+ "image",
+ "core",
+ "feature",
+)
+
+# The registries that hold each package's promised cases. ``cases_models.py`` is never imported: it builds the
+# pretrained models of ``kornia.models``, none of which is promised, and downloads their weights on a cold cache.
+# A promised case outside its package's registries fails test_promised_cases_are_registered.
+REGISTRIES_OF = {
+ "geometry": ("cases_geomA", "cases_geomB"),
+ "augmentation": ("cases_aug",),
+ "color": ("cases_misc",),
+ "filters": ("cases_misc",),
+ "enhance": ("cases_misc",),
+ "losses": ("cases_misc",),
+ "metrics": ("cases_misc",),
+ "morphology": ("cases_misc",),
+ "io": (),
+ "image": ("cases_misc",),
+ "core": (),
+ "feature": ("cases_feature",),
+}
+REGISTRIES = ("cases_aug", "cases_feature", "cases_geomA", "cases_geomB", "cases_misc")
+
+# Legacy (TorchScript) export statuses that pass: the export worked and matched, or it failed loudly.
+LEGACY_PASSES = ("ok", "export-fail", "checker-fail", "ort-load-fail", "ort-run-fail")
+
+# The exception a per-case test raises for a status that does not pass, so that a manifest entry pins the kind of
+# failure: a known failure that changes kind (a graph break that turns into a wrong value, an eager regression of a
+# pinned case) then fails as an unexpected exception instead of staying a strict xfail.
+STATUS_EXCEPTIONS: dict[str, type[Exception]] = {
+ # the export or compile ran and the result differs from eager: value, dtype, shape or output count
+ "mismatch": AssertionError,
+ # the export, the ONNX checker, onnxruntime or the compile failed (a graph break, a backend error)
+ "fail": RuntimeError,
+ "export-fail": RuntimeError,
+ "checker-fail": RuntimeError,
+ "ort-load-fail": RuntimeError,
+ "ort-run-fail": RuntimeError,
+ # the eager reference itself failed, or returned no tensor
+ "eager-fail": ValueError,
+ "no-tensor-output": ValueError,
+}
+
+# torch's process-wide module hooks that a failed or (on torch 2.5) a successful non-strict ``torch.export`` trace can
+# leave registered; a later ``torch.compile`` of a module with buffers then fails. The runners remove what they added.
+REGISTRATION_HOOKS = (
+ "_global_buffer_registration_hooks",
+ "_global_module_registration_hooks",
+ "_global_parameter_registration_hooks",
+)
+
+
+def parse_selection(promise: Promise, value: str | None) -> tuple[str, ...]:
+ """Return the packages a ``--<promise>-conformance`` value selects; ``()`` when it is unset (``None`` or ``""``).
+
+ Args:
+ promise: the promise whose option carries the value.
+ value: ``all``, or comma-separated package names with or without the ``kornia.`` prefix.
+
+ Returns:
+ The selected packages, in ``STABLE_CORE`` order.
+
+ Raises:
+ ValueError: when a name is empty (a blank value, a stray comma) or not a stable-core package.
+ """
+ if value is None or value == "":
+ return ()
+ names = [v.strip().removeprefix("kornia.") for v in value.split(",")]
+ if not all(names):
+ raise ValueError(f"{promise.option}: empty package name in {value!r}; give packages or all")
+ unknown = sorted(set(names) - set(STABLE_CORE) - {"all"})
+ if unknown:
+ raise ValueError(f"{promise.option}: unknown package(s) {unknown}; choose from {', '.join(STABLE_CORE)} or all")
+ if "all" in names:
+ return STABLE_CORE
+ return tuple(p for p in STABLE_CORE if p in names)
+
+
+def selection(config: pytest.Config, promise: Promise) -> tuple[str, ...]:
+ """The packages the session selects for ``promise``."""
+ return parse_selection(promise, config.getoption(promise.option))
+
+
+def pretrained_cases() -> frozenset[str]:
+ """Names of the registry cases tagged ``pretrained``, read from the registry sources without importing them."""
+ names: set[str] = set()
+ for registry in REGISTRIES:
+ path = EXPORT_SUPPORT / f"{registry}.py"
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))):
+ if not isinstance(node, ast.Call):
+ continue
+ tags = next((kw.value for kw in node.keywords if kw.arg == "tags"), None)
+ if not isinstance(tags, (ast.Tuple, ast.List)):
+ continue
+ if not any(isinstance(tag, ast.Constant) and tag.value == "pretrained" for tag in tags.elts):
+ continue
+ first = node.args[0] if node.args else None
+ if not (isinstance(first, ast.Constant) and isinstance(first.value, str)):
+ raise ValueError(f"{path}:{node.lineno}: a case tagged pretrained needs a literal name")
+ names.add(first.value)
+ return frozenset(names)
+
+
+def promised_cases(promise: Promise) -> dict[str, str]:
+ """Map every case ``promise`` covers to its package (``geometry``, ``color``, ...), in snapshot order."""
+ pretrained = pretrained_cases()
+ promised: dict[str, str] = {}
+ for record in json.loads(SNAPSHOT.read_text(encoding="utf-8"))["cases"]:
+ package = record["package"].removeprefix("kornia.")
+ if record[promise.field] != "ok" or package not in STABLE_CORE or record["name"] in pretrained:
+ continue
+ if package == "feature" and record["section"] == "models":
+ continue
+ promised[record["name"]] = package
+ return promised
+
+
+def promised_digest(names: Iterable[str]) -> str:
+ """SHA-256 of the sorted names, one per line: what ``test_promised_set_is_pinned`` compares."""
+ return hashlib.sha256("\n".join(sorted(names)).encode()).hexdigest()
+
+
+def selected_cases(promise: Promise, packages: Sequence[str]) -> list[str]:
+ """Return the promised case names of ``packages``, in snapshot order."""
+ return [name for name, package in promised_cases(promise).items() if package in packages]
+
+
+def parametrize_cases(metafunc: pytest.Metafunc, promise: Promise) -> None:
+ """Parametrize a per-case test (argument ``case_name``) with the promised cases the session selects."""
+ if "case_name" not in metafunc.fixturenames:
+ return
+ names = selected_cases(promise, selection(metafunc.config, promise))
+ # Without a selection the root conftest deselects the placeholder; with one that has no promised case it skips.
+ metafunc.parametrize("case_name", names or [pytest.param(None, id="unselected")])
+
+
+def _no_downloads() -> Iterator[None]:
+ """Make a weights download raise instead: no case the registries build may reach the network here."""
+ from testing.doctest_downloads import install_download_guard
+
+ undo: list[tuple[Any, str, Any]] = []
+
+ def set_attribute(obj: Any, name: str, value: Any) -> None:
+ undo.append((obj, name, getattr(obj, name)))
+ setattr(obj, name, value)
+
+ def refuse(url: str) -> None:
+ raise RuntimeError(f"weights are not in the cache (the conformance test does not download): {url}")
+
+ try:
+ install_download_guard(set_attribute, refuse)
+ yield
+ finally:
+ for obj, name, value in reversed(undo):
+ setattr(obj, name, value)
+
+
+def import_survey_module(name: str) -> ModuleType:
+ """Import ``docs/export_support/<name>.py`` without letting the import touch the process.
+
+ The registries seed the global RNG and build their inputs (and the pretrained models of cases that are not
+ promised) at import, and print the traceback of a model they cannot build: the RNG state is restored, downloads
+ refused and the output dropped.
+ """
+ path = str(EXPORT_SUPPORT)
+ sys.path.insert(0, path)
+ try:
+ sink = io.StringIO()
+ with (
+ torch.random.fork_rng(devices=[]),
+ _no_downloads(),
+ contextlib.redirect_stdout(sink),
+ contextlib.redirect_stderr(sink),
+ ):
+ return importlib.import_module(name)
+ finally:
+ sys.path.remove(path)
+
+
+def registries_of(packages: Sequence[str]) -> tuple[str, ...]:
+ """The registries holding the promised cases of ``packages``, in ``REGISTRIES`` order."""
+ needed = {registry for package in packages for registry in REGISTRIES_OF[package]}
+ return tuple(registry for registry in REGISTRIES if registry in needed)
+
+
+def registry_cases(registries: tuple[str, ...] = REGISTRIES) -> dict[str, dict[str, Any]]:
+ """Every case of ``registries`` by name; a name registered twice is an error."""
+ cases: dict[str, dict[str, Any]] = {}
+ for registry in registries:
+ for case in import_survey_module(registry).CASES:
+ if case["name"] in cases:
+ raise ValueError(f"case {case['name']!r} is registered twice ({registry})")
+ cases[case["name"]] = case
+ return cases
+
+
+def promised_case(promise: Promise, case_name: str | None) -> dict[str, Any]:
+ """The registry case of a promised name; skips the ``unselected`` placeholder, fails when nothing runs it."""
+ if case_name is None:
+ pytest.skip("the selected packages have no promised case")
+ case = registry_cases(registries_of([promised_cases(promise)[case_name]])).get(case_name)
+ if case is None or case["skip"] or not case["check"]:
+ pytest.fail(f"{case_name!r} is promised but no registry case runs it; see test_promised_cases_are_registered")
+ return case
+
+
+def registration_problems(promise: Promise, packages: Sequence[str]) -> list[str]:
+ """Promised cases of ``packages`` that no registry case runs and compares with eager (the drift guard)."""
+ registries = registries_of(packages)
+ cases = registry_cases(registries)
+ problems = []
+ for name in selected_cases(promise, packages):
+ case = cases.get(name)
+ if case is None:
+ problems.append(f"{name}: no case of that name in {', '.join(registries) or 'no registry'}")
+ elif case["skip"]:
+ problems.append(f"{name}: skipped ({case['skip']})")
+ elif not case["check"]:
+ problems.append(f"{name}: check=False, the output is not compared with eager")
+ # The promise leaves out pretrained cases by reading the registry sources; the imported registries must agree.
+ tagged = {name for name, case in cases.items() if "pretrained" in case["tags"]}
+ if disagree := tagged ^ (pretrained_cases() & cases.keys()):
+ problems.append(f"registry tags and the static pretrained scan disagree on {sorted(disagree)}")
+ return problems
+
+
+def pin_problems(promise: Promise, count: int, digest: str) -> list[str]:
+ """How the promised set differs from the pinned ``count`` and ``digest``, or breaks the naming rules."""
+ # The promise is read from the snapshot, so a regeneration that measured a case as failing would quietly drop it.
+ # Pinning the names makes a change of the promised set a reviewed change of these two constants.
+ promised = promised_cases(promise)
+ problems = []
+ if (len(promised), promised_digest(promised)) != (count, digest):
+ problems.append(
+ "the promised set changed; review the snapshot diff, then update PROMISED_COUNT and PROMISED_DIGEST"
+ f" (now {len(promised)}, {promised_digest(promised)})"
+ )
+ if outside := [name for name in promised if name.startswith(("models.", "contrib."))]:
+ problems.append(f"promised cases outside the stable core: {outside}")
+ if pretrained := sorted(promised.keys() & pretrained_cases()):
+ problems.append(f"promised cases built with pretrained weights: {pretrained}")
+ # The root conftest deselects or skips tests whose id contains these words, which would drop the case silently.
+ if words := [name for name in promised if any(word in name.lower() for word in ("dynamo", "compile", "autocast"))]:
+ problems.append(f"promised case names the root conftest deselects or skips: {words}")
+ return problems
+
+
+def registration_hooks() -> dict[str, frozenset[Any]]:
+ """The handles registered in each of torch's process-wide module registration hooks that this torch has."""
+ from torch.nn.modules import module
+
+ return {
+ name: frozenset(hooks) for name in REGISTRATION_HOOKS if isinstance(hooks := getattr(module, name, None), dict)
+ }
+
+
+def _restore_registration_hooks() -> Iterator[None]:
+ from torch.nn.modules import module
+
+ before = registration_hooks()
+ try:
+ yield
+ finally:
+ for name, handles in before.items():
+ hooks = getattr(module, name)
+ for handle in [handle for handle in hooks if handle not in handles]:
+ del hooks[handle]
+
+
+def _compile_configs() -> tuple[Any, ...]:
+ """The dynamo and inductor config modules, or none on a torch whose Dynamo cannot be imported."""
+ try:
+ from torch._dynamo import config as dynamo_config
+ from torch._inductor import config as inductor_config
+ except ImportError:
+ return ()
+ return dynamo_config, inductor_config
+
+
+def _same_value(a: Any, b: Any) -> bool:
+ """Whether two copies of a torch config value are equal; a value need not define ``==``, so compare pickles."""
+ try:
+ if a is b or bool(a == b):
+ return True
+ except Exception: # noqa: BLE001, S110 -- an ``==`` that cannot answer falls through to the pickles
+ pass
+ try:
+ return pickle.dumps(a) == pickle.dumps(b)
+ except Exception: # noqa: BLE001 -- a value pickle rejects is equal only to itself
+ return False
+
+
+def changed_config_keys(before: dict[str, Any], after: dict[str, Any]) -> list[str]:
+ """The keys whose values differ between two ``get_config_copy()`` results of one torch config module."""
+ return [key for key in before.keys() | after.keys() if not _same_value(before.get(key), after.get(key))]
+
+
+def _restore_compile_configs() -> Iterator[None]:
+ """Put back every dynamo and inductor config key whose value changed inside the block.
+
+ ``get_config_copy`` and ``setattr`` are the config API every supported torch has (torch 2.5's ``save_config``
+ fails on its own Dynamo config).
+ """
+ saved = [(config, config.get_config_copy()) for config in _compile_configs()]
+ try:
+ yield
+ finally:
+ for config, before in saved:
+ for key in changed_config_keys(before, config.get_config_copy()):
+ setattr(config, key, before[key])
+
+
+def run_onnx_case(case: dict[str, Any], dynamo: bool) -> dict[str, Any]:
+ """Run one case through the ONNX survey harness, leaving the global RNG and torch's module hooks as they were."""
+ harness = import_survey_module("harness")
+ with torch.random.fork_rng(devices=[]), _restore_registration_hooks():
+ return harness.run_case(case, dynamo=dynamo)
+
+
+def run_compile_case(case: dict[str, Any]) -> dict[str, Any]:
+ """Compile one case with ``fullgraph=True`` through the survey's compile probe and compare it with eager.
+
+ The probe resets Dynamo before and after the case; the global RNG, torch's module hooks and the dynamo and
+ inductor configs are left as they were.
+ """
+ probe = import_survey_module("probe_compile")
+ with torch.random.fork_rng(devices=[]), _restore_registration_hooks(), _restore_compile_configs():
+ return probe.run_case(case, export=False, fullgraph=True)
+
+
+def raise_for_status(record: dict[str, Any], passes: Sequence[str], step: str = "") -> None:
+ """Raise the ``STATUS_EXCEPTIONS`` type of a record whose status is not in ``passes``, with ``describe``'s message.
+
+ Args:
+ record: a survey record.
+ passes: the statuses that pass.
+ step: as for ``describe``: ``""`` for a harness record, ``"compile"`` for a compile probe record.
+ """
+ status = record[step or "status"]
+ if status not in passes:
+ raise STATUS_EXCEPTIONS.get(status, AssertionError)(describe(record, step))
+
+
+def describe(record: dict[str, Any], step: str = "") -> str:
+ """A failure message naming the status, the error and the kornia frames involved.
+
+ Args:
+ record: a survey record.
+ step: ``""`` for a harness record (``status``, ``error``, ...), ``"compile"`` for a compile probe record
+ (``compile``, ``compile_error``, ...).
+ """
+ prefix = f"{step}_" if step else ""
+ # the compile probe records an eager failure under ``error``, before any step ran
+ lines = [f"{record[step or 'status']}: {record.get(prefix + 'error') or record.get('error', '')}"]
+ lines += [f" at {frame}" for frame in record.get(prefix + "where") or ()]
+ if record.get(prefix + "error_full"):
+ lines.append(record[prefix + "error_full"][-1500:])
+ return "\n".join(lines)
+
+
+def process_state() -> dict[str, Any]:
+ """The process-wide state a survey run must leave alone, for ``state_changes``."""
+ configs = _compile_configs() # first: importing Dynamo the first time adds sympy's warning filter
+ state: dict[str, Any] = {
+ "threads": torch.get_num_threads(),
+ "logging": logging.root.manager.disable,
+ "filters": list(warnings.filters),
+ "rng": torch.random.get_rng_state(),
+ "hooks": registration_hooks(),
+ }
+ if hasattr(signal, "SIGALRM"):
+ state["alarm handler"] = signal.getsignal(signal.SIGALRM)
+ for config in configs:
+ state[config.__name__] = config.get_config_copy()
+ return state
+
+
+def state_changes(before: dict[str, Any], after: dict[str, Any]) -> list[str]:
+ """What changed between two ``process_state`` snapshots.
+
+ A torch.export trace or a Dynamo frame conversion may add torch's own warning filters (torch 2.5 adds one for
+ module "torch.distributed"); the harness used to add a blanket "ignore everything" one. So a new filter passes only
+ when it names a torch module.
+ """
+ changes = []
+ for key in before.keys() | after.keys():
+ old, new = before.get(key), after.get(key)
+ if key == "rng":
+ if not torch.equal(old, new):
+ changes.append("the global CPU RNG state")
+ elif key == "filters":
+ added = [f for f in new if f not in old]
+ if not all(f[3] is not None and f[3].pattern.startswith("torch") for f in added):
+ changes.append(f"warning filters added: {added}")
+ elif key.startswith("torch."): # a dynamo or inductor config
+ changes += [f"{key}.{name}" for name in sorted(changed_config_keys(old, new))]
+ elif isinstance(old, dict) and isinstance(new, dict):
+ changes += [f"{key}.{name}" for name in sorted(old.keys() | new.keys()) if old.get(name) != new.get(name)]
+ elif old != new:
+ changes.append(f"{key}: {old!r} -> {new!r}"[:300])
+ return sorted(changes)
+
+
+def manifest_path(promise: Promise, version: str | None = None) -> Path:
+ """A promise's known-failure manifest of a torch release (default: the running one).
+
+ For example ``onnx_conformance_torch2.14.txt``.
+ """
+ major, minor = (version or torch.__version__).split("+")[0].split(".")[:2]
+ return MANIFEST_DIR / f"{promise.marker}_torch{major}.{minor}.txt"
+
+
+def load_known_failures(promise: Promise, path: Path) -> dict[str, type[BaseException]]:
+ """Read ``<exception type>\\t<node ID>`` lines; every node ID must name a per-case test of a promised case."""
+ node = re.compile(rf"^{re.escape(promise.test_file)}::(?P<test>\w+)\[(?P<case>.+)\]$")
+ failures: dict[str, type[BaseException]] = {}
+ for 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}:{number}: expected '<exception>\\t<node ID>'") from error
+ if exception_name not in _EXCEPTION_TYPES:
+ raise ValueError(f"{path}:{number}: unknown exception type: {exception_name}")
+ match = node.match(nodeid)
+ if match is None or match["test"] not in promise.case_tests:
+ raise ValueError(f"{path}:{number}: not a per-case node of {promise.test_file}: {nodeid}")
+ if match["case"] not in promised_cases(promise):
+ raise ValueError(f"{path}:{number}: {match['case']!r} is not a promised case (renamed or dropped?)")
+ if nodeid in failures:
+ raise ValueError(f"{path}:{number}: duplicate node ID: {nodeid}")
+ failures[nodeid] = _EXCEPTION_TYPES[exception_name]
+ return failures
+
+
+class KnownFailurePlugin:
+ """Apply a promise's manifest for this torch to the final selection (after ``-k``, ``-m``, ``--deselect``)."""
+
+ def __init__(self, promise: Promise) -> None:
+ self.promise = promise
+
+ @pytest.hookimpl(trylast=True)
+ def pytest_collection_modifyitems(self, config: pytest.Config, items: list[Any]) -> None:
+ try:
+ tracker = mark_known_failures(self.promise, items)
+ except (OSError, ValueError) as error:
+ raise pytest.UsageError(str(error)) from error
+ if tracker is not None:
+ config.pluginmanager.register(tracker, f"{self.promise.field}-conformance-known-failure-tracker")
+
+
+def mark_known_failures(promise: Promise, items: Sequence[Any], path: Path | None = None) -> KnownFailureTracker | None:
+ """Strictly xfail the collected entries of a promise's manifest for the running torch; ``None`` when it has none.
+
+ Entries of packages the run did not select are not collected and not checked. A collected entry that passes
+ (strict XPASS), skips, or fails with another exception type fails the session through the tracker.
+ """
+ path = path or manifest_path(promise)
+ if not path.exists():
+ return None
+ failures = load_known_failures(promise, path)
+ collected = {item.nodeid for item in items}
+ selected = {nodeid: exception for nodeid, exception in failures.items() if nodeid in collected}
+ reason = f"Known {promise.name} conformance failure recorded in {path.name}; see its tracking issue there"
+ for item in items:
+ if exception := selected.get(item.nodeid):
+ item.add_marker(pytest.mark.xfail(reason=reason, raises=exception, strict=True))
+ return KnownFailureTracker(selected, path, reason)
diff --git a/testing/known_failure_xfails/compile_conformance_torch2.14.txt b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
new file mode 100644
index 000000000..7f8274cae
--- /dev/null
+++ b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
@@ -0,0 +1,40 @@
+# Strict known-failure baseline of tests/test_inductor_conformance.py on torch 2.14.0 (CPU float32, Python 3.11):
+# promised operators that do not compile with torch.compile(fullgraph=True) and the inductor backend, or whose
+# compiled result differs from eager (#5819).
+# Remove an entry when its case passes (a strict XPASS fails the run). A new failure of a promised operator is a
+# regression to fix; add it only with a comment naming its own tracking issue.
+# Entries of packages a run does not select are not checked; every node ID must name a promised case.
+# Format: <exact exception type>\t<pytest node ID>. The type names the kind of failure (testing.conformance
+# STATUS_EXCEPTIONS): AssertionError a wrong result, RuntimeError a failed compile, ValueError a failed eager run.
+# #5037: a data-dependent check or a host-side route guarded by is_exporting(), which is False under torch.compile
+# on torch 2.14 (True on 2.9.1), so Dynamo traces it and fullgraph fails; the call sites want is_compiling().
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[LongestMaxSize]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[SmallestMaxSize]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[LongestMaxSize[const-size]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[SmallestMaxSize[const-size]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[transform.center_crop3d]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[transform.crop_and_resize3d]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.bbox_to_mask3d]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.infer_bbox_shape3d]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xyxy]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xywh]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.from_tensor[xyxy_plus]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes.to_mask]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.from_tensor[xyzxyz]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.from_tensor[xyzwhd]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[boxes.Boxes3D.to_mask]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.reproject_disparity_to_3D]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.Q]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.liegroup.So2.from_matrix]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.liegroup.Se2.from_matrix]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[geometry.camera.StereoCamera.reproject_disparity_to_3D[baked-cams]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable[batch]]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[enhance.JPEGCodecDifferentiable[custom_qt]]
+# #6194: the survey recorded these as compiling without a graph break, but Dynamo cannot
+# capture them in one graph on any measured torch (a loop over a data-dependent count, a host read of tensor values).
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.nms]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[image.draw_rectangle]
+# pytorch/pytorch#198270 (fixed in torch 2.15; documented on PatchSequential, #6195): inductor computes a
+# different image than eager for PatchSequential with patchwise_apply=False.
+AssertionError tests/test_inductor_conformance.py::test_inductor_matches_eager[PatchSequential[not-patchwise]]
diff --git a/testing/known_failure_xfails/compile_conformance_torch2.9.txt b/testing/known_failure_xfails/compile_conformance_torch2.9.txt
new file mode 100644
index 000000000..3a366949f
--- /dev/null
+++ b/testing/known_failure_xfails/compile_conformance_torch2.9.txt
@@ -0,0 +1,16 @@
+# Strict known-failure baseline of tests/test_inductor_conformance.py on torch 2.9.1 (CPU float32, Python 3.11):
+# promised operators that do not compile with torch.compile(fullgraph=True) and the inductor backend, or whose
+# compiled result differs from eager (#5819).
+# Remove an entry when its case passes (a strict XPASS fails the run). A new failure of a promised operator is a
+# regression to fix; add it only with a comment naming its own tracking issue.
+# Entries of packages a run does not select are not checked; every node ID must name a promised case.
+# Format: <exact exception type>\t<pytest node ID>. The type names the kind of failure (testing.conformance
+# STATUS_EXCEPTIONS): AssertionError a wrong result, RuntimeError a failed compile, ValueError a failed eager run.
+# #6194: the survey recorded these as compiling without a graph break, but Dynamo cannot
+# capture them in one graph on any measured torch (a loop over a data-dependent count, a host read of tensor values).
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[bbox.nms]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[image.draw_rectangle]
+RuntimeError tests/test_inductor_conformance.py::test_inductor_matches_eager[image.draw_rectangle[fill]]
+# pytorch/pytorch#198270 (fixed in torch 2.15; documented on PatchSequential, #6195): inductor computes a
+# different image than eager for PatchSequential with patchwise_apply=False.
+AssertionError tests/test_inductor_conformance.py::test_inductor_matches_eager[PatchSequential[not-patchwise]]
diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.14.txt b/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
index 0f6cde870..e6c37100f 100644
--- a/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
+++ b/testing/known_failure_xfails/onnx_conformance_torch2.14.txt
@@ -4,4 +4,6 @@
# Remove an entry when its case passes (a strict XPASS fails the run). A new failure of a promised operator is a
# regression to fix; add it only with a comment naming its own tracking issue.
# Entries of packages a run does not select are not checked; every node ID must name a promised case.
-# Format: <exact exception type>\t<pytest node ID>
+# Format: <exact exception type>\t<pytest node ID>. The type names the kind of failure (testing.conformance
+# STATUS_EXCEPTIONS): AssertionError a wrong result, RuntimeError a failed export, checker or onnxruntime run,
+# ValueError a failed eager run.
diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
index 976ab76ff..6cc938c09 100644
--- a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
+++ b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt
@@ -4,4 +4,6 @@
# Remove an entry when its case passes (a strict XPASS fails the run). A new failure of a promised operator is a
# regression to fix; add it only with a comment naming its own tracking issue.
# Entries of packages a run does not select are not checked; every node ID must name a promised case.
-# Format: <exact exception type>\t<pytest node ID>
+# Format: <exact exception type>\t<pytest node ID>. The type names the kind of failure (testing.conformance
+# STATUS_EXCEPTIONS): AssertionError a wrong result, RuntimeError a failed export, checker or onnxruntime run,
+# ValueError a failed eager run.
diff --git a/testing/known_failures.py b/testing/known_failures.py
index 263a18e21..da436e271 100644
--- a/testing/known_failures.py
+++ b/testing/known_failures.py
@@ -28,6 +28,7 @@ _EXCEPTION_TYPES: dict[str, type[BaseException]] = {
"NotImplementedError": NotImplementedError,
"RuntimeError": RuntimeError,
"TypeError": TypeError,
+ "ValueError": ValueError,
"pytest.fail.Exception": pytest.fail.Exception,
}
diff --git a/testing/onnx_conformance.py b/testing/onnx_conformance.py
deleted file mode 100644
index fd29769cc..000000000
--- a/testing/onnx_conformance.py
+++ /dev/null
@@ -1,344 +0,0 @@
-# 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.
-#
-
-"""Support for ``tests/onnx/test_conformance.py``: the ONNX promise of #5819, checked with the survey's own cases.
-
-The promised cases are the records of the committed survey snapshot (``docs/source/_data/export_support.json``)
-whose ONNX status is ``ok`` and whose package is in the stable core of ``docs/source/get-started/stability.rst``,
-minus everything built with pretrained weights (registry tag ``pretrained``): the stable core holds only the
-classical, non-pretrained parts of ``kornia.feature``. Each is run through ``docs/export_support/harness.py`` -- the
-code the survey runs -- by case name, so the test and the survey page cannot drift apart.
-
-The run is opt-in: ``--onnx-conformance=<package>[,<package>...]`` or ``all`` (env
-``KORNIA_TEST_ONNX_CONFORMANCE``); without it the root ``conftest.py`` deselects every test marked
-``onnx_conformance``. Known failures are strict xfails listed per torch release in
-``testing/known_failure_xfails/onnx_conformance_torch<major>.<minor>.txt``.
-"""
-
-from __future__ import annotations
-
-import ast
-import contextlib
-import functools
-import hashlib
-import importlib
-import io
-import json
-import re
-import sys
-from pathlib import Path
-from types import ModuleType
-from typing import Any, Iterable, Iterator, Sequence
-
-import pytest
-import torch
-
-from testing.known_failures import _EXCEPTION_TYPES, KnownFailureTracker
-
-REPO = Path(__file__).resolve().parents[1]
-EXPORT_SUPPORT = REPO / "docs" / "export_support"
-SNAPSHOT = REPO / "docs" / "source" / "_data" / "export_support.json"
-MANIFEST_DIR = Path(__file__).with_name("known_failure_xfails")
-TEST_FILE = "tests/onnx/test_conformance.py"
-CASE_TESTS = ("test_export_matches_eager", "test_legacy_export_is_not_wrong")
-MARKER = "onnx_conformance"
-OPTION = "--onnx-conformance"
-ENV_VAR = "KORNIA_TEST_ONNX_CONFORMANCE"
-
-# The stable core of docs/source/get-started/stability.rst, as the ``kornia.<package>`` names the snapshot records.
-# tests/scripts/test_onnx_conformance_packages.py checks it against that page and against the CI path mapping.
-STABLE_CORE = (
- "geometry",
- "augmentation",
- "color",
- "filters",
- "enhance",
- "losses",
- "metrics",
- "morphology",
- "io",
- "image",
- "core",
- "feature",
-)
-
-# The registries that hold each package's promised cases. ``cases_models.py`` is never imported: it builds the
-# pretrained models of ``kornia.models``, none of which is promised, and downloads their weights on a cold cache.
-# A promised case outside its package's registries fails test_promised_cases_are_registered.
-REGISTRIES_OF = {
- "geometry": ("cases_geomA", "cases_geomB"),
- "augmentation": ("cases_aug",),
- "color": ("cases_misc",),
- "filters": ("cases_misc",),
- "enhance": ("cases_misc",),
- "losses": ("cases_misc",),
- "metrics": ("cases_misc",),
- "morphology": ("cases_misc",),
- "io": (),
- "image": ("cases_misc",),
- "core": (),
- "feature": ("cases_feature",),
-}
-REGISTRIES = ("cases_aug", "cases_feature", "cases_geomA", "cases_geomB", "cases_misc")
-
-# Legacy (TorchScript) export statuses that pass: the export worked and matched, or it failed loudly.
-LEGACY_PASSES = ("ok", "export-fail", "checker-fail", "ort-load-fail", "ort-run-fail")
-
-# torch's process-wide module hooks that a failed or (on torch 2.5) a successful non-strict ``torch.export`` trace can
-# leave registered; a later ``torch.compile`` of a module with buffers then fails. ``run_case`` removes what it added.
-REGISTRATION_HOOKS = (
- "_global_buffer_registration_hooks",
- "_global_module_registration_hooks",
- "_global_parameter_registration_hooks",
-)
-
-
-def parse_selection(value: str | None) -> tuple[str, ...]:
- """Return the packages an ``--onnx-conformance`` value selects; ``()`` when it is unset (``None`` or ``""``).
-
- Args:
- value: ``all``, or comma-separated package names with or without the ``kornia.`` prefix.
-
- Returns:
- The selected packages, in ``STABLE_CORE`` order.
-
- Raises:
- ValueError: when a name is empty (a blank value, a stray comma) or not a stable-core package.
- """
- if value is None or value == "":
- return ()
- names = [v.strip().removeprefix("kornia.") for v in value.split(",")]
- if not all(names):
- raise ValueError(f"{OPTION}: empty package name in {value!r}; give packages or all")
- unknown = sorted(set(names) - set(STABLE_CORE) - {"all"})
- if unknown:
- raise ValueError(f"{OPTION}: unknown package(s) {unknown}; choose from {', '.join(STABLE_CORE)} or all")
- if "all" in names:
- return STABLE_CORE
- return tuple(p for p in STABLE_CORE if p in names)
-
-
-def pretrained_cases() -> frozenset[str]:
- """Names of the registry cases tagged ``pretrained``, read from the registry sources without importing them."""
- names: set[str] = set()
- for registry in REGISTRIES:
- path = EXPORT_SUPPORT / f"{registry}.py"
- for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))):
- if not isinstance(node, ast.Call):
- continue
- tags = next((kw.value for kw in node.keywords if kw.arg == "tags"), None)
- if not isinstance(tags, (ast.Tuple, ast.List)):
- continue
- if not any(isinstance(tag, ast.Constant) and tag.value == "pretrained" for tag in tags.elts):
- continue
- first = node.args[0] if node.args else None
- if not (isinstance(first, ast.Constant) and isinstance(first.value, str)):
- raise ValueError(f"{path}:{node.lineno}: a case tagged pretrained needs a literal name")
- names.add(first.value)
- return frozenset(names)
-
-
-def promised_cases() -> dict[str, str]:
- """Map every promised case name to its package (``geometry``, ``color``, ...), in snapshot order."""
- pretrained = pretrained_cases()
- promised: dict[str, str] = {}
- for record in json.loads(SNAPSHOT.read_text(encoding="utf-8"))["cases"]:
- package = record["package"].removeprefix("kornia.")
- if record["onnx"] != "ok" or package not in STABLE_CORE or record["name"] in pretrained:
- continue
- if package == "feature" and record["section"] == "models":
- continue
- promised[record["name"]] = package
- return promised
-
-
-def promised_digest(names: Iterable[str]) -> str:
- """SHA-256 of the sorted names, one per line: what ``test_promised_set_is_pinned`` compares."""
- return hashlib.sha256("\n".join(sorted(names)).encode()).hexdigest()
-
-
-def selected_cases(packages: Sequence[str]) -> list[str]:
- """Return the promised case names of ``packages``, in snapshot order."""
- return [name for name, package in promised_cases().items() if package in packages]
-
-
-def _no_downloads() -> Iterator[None]:
- """Make a weights download raise instead: no case the registries build may reach the network here."""
- from testing.doctest_downloads import install_download_guard
-
- undo: list[tuple[Any, str, Any]] = []
-
- def set_attribute(obj: Any, name: str, value: Any) -> None:
- undo.append((obj, name, getattr(obj, name)))
- setattr(obj, name, value)
-
- def refuse(url: str) -> None:
- raise RuntimeError(f"weights are not in the cache (the conformance test does not download): {url}")
-
- try:
- install_download_guard(set_attribute, refuse)
- yield
- finally:
- for obj, name, value in reversed(undo):
- setattr(obj, name, value)
-
-
-def import_survey_module(name: str) -> ModuleType:
- """Import ``docs/export_support/<name>.py`` without letting the import touch the process.
-
- The registries seed the global RNG and build their inputs (and the pretrained models of cases that are not
- promised) at import, and print the traceback of a model they cannot build: the RNG state is restored, downloads
- refused and the output dropped.
- """
- path = str(EXPORT_SUPPORT)
- sys.path.insert(0, path)
- try:
- sink = io.StringIO()
- with (
- torch.random.fork_rng(devices=[]),
- _no_downloads(),
- contextlib.redirect_stdout(sink),
- contextlib.redirect_stderr(sink),
- ):
- return importlib.import_module(name)
- finally:
- sys.path.remove(path)
-
-
-def registries_of(packages: Sequence[str]) -> tuple[str, ...]:
- """The registries holding the promised cases of ``packages``, in ``REGISTRIES`` order."""
- needed = {registry for package in packages for registry in REGISTRIES_OF[package]}
- return tuple(registry for registry in REGISTRIES if registry in needed)
-
-
-def registry_cases(registries: tuple[str, ...] = REGISTRIES) -> dict[str, dict[str, Any]]:
- """Every case of ``registries`` by name; a name registered twice is an error."""
- cases: dict[str, dict[str, Any]] = {}
- for registry in registries:
- for case in import_survey_module(registry).CASES:
- if case["name"] in cases:
- raise ValueError(f"case {case['name']!r} is registered twice ({registry})")
- cases[case["name"]] = case
- return cases
-
-
-def registration_hooks() -> dict[str, frozenset[Any]]:
- """The handles registered in each of torch's process-wide module registration hooks that this torch has."""
- from torch.nn.modules import module
-
- return {
- name: frozenset(hooks) for name in REGISTRATION_HOOKS if isinstance(hooks := getattr(module, name, None), dict)
- }
-
-
-def _restore_registration_hooks() -> Iterator[None]:
- from torch.nn.modules import module
-
- before = registration_hooks()
- try:
- yield
- finally:
- for name, handles in before.items():
- hooks = getattr(module, name)
- for handle in [handle for handle in hooks if handle not in handles]:
- del hooks[handle]
-
-
-def run_case(case: dict[str, Any], dynamo: bool) -> dict[str, Any]:
- """Run one case through the survey harness, leaving the global RNG and torch's module hooks as they were."""
- harness = import_survey_module("harness")
- with torch.random.fork_rng(devices=[]), _restore_registration_hooks():
- return harness.run_case(case, dynamo=dynamo)
-
-
-def describe(record: dict[str, Any]) -> str:
- """A failure message naming the status, the error and the kornia frames involved."""
- lines = [f"{record['status']}: {record.get('error', '')}"]
- lines += [f" at {frame}" for frame in record.get("where") or ()]
- if record.get("error_full"):
- lines.append(record["error_full"][-1500:])
- return "\n".join(lines)
-
-
-def manifest_path(version: str | None = None) -> Path:
- """The known-failure manifest of a torch release (default: the running one), e.g. ``..._torch2.14.txt``."""
- major, minor = (version or torch.__version__).split("+")[0].split(".")[:2]
- return MANIFEST_DIR / f"onnx_conformance_torch{major}.{minor}.txt"
-
-
-_NODE = re.compile(rf"^{re.escape(TEST_FILE)}::(?P<test>\w+)\[(?P<case>.+)\]$")
-
-
-def load_known_failures(path: Path) -> dict[str, type[BaseException]]:
- """Read ``<exception type>\\t<node ID>`` lines; every node ID must name a per-case test of a promised case."""
- failures: dict[str, type[BaseException]] = {}
- for 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}:{number}: expected '<exception>\\t<node ID>'") from error
- if exception_name not in _EXCEPTION_TYPES:
- raise ValueError(f"{path}:{number}: unknown exception type: {exception_name}")
- match = _NODE.match(nodeid)
- if match is None or match["test"] not in CASE_TESTS:
- raise ValueError(f"{path}:{number}: not a per-case node of {TEST_FILE}: {nodeid}")
- if match["case"] not in promised_cases():
- raise ValueError(f"{path}:{number}: {match['case']!r} is not a promised case (renamed or dropped?)")
- if nodeid in failures:
- raise ValueError(f"{path}:{number}: duplicate node ID: {nodeid}")
- failures[nodeid] = _EXCEPTION_TYPES[exception_name]
- return failures
-
-
-class KnownFailurePlugin:
- """Apply the running torch's manifest to the final selection, after ``-k`` / ``-m`` / ``--deselect``."""
-
- @pytest.hookimpl(trylast=True)
- def pytest_collection_modifyitems(self, config: pytest.Config, items: list[Any]) -> None:
- try:
- tracker = mark_known_failures(items)
- except (OSError, ValueError) as error:
- raise pytest.UsageError(str(error)) from error
- if tracker is not None:
- config.pluginmanager.register(tracker, "onnx-conformance-known-failure-tracker")
-
-
-def mark_known_failures(items: Sequence[Any], path: Path | None = None) -> KnownFailureTracker | None:
- """Strictly xfail the collected entries of the running torch's manifest; ``None`` when it has none.
-
- Entries of packages the run did not select are not collected and not checked. A collected entry that passes
- (strict XPASS), skips, or fails with another exception type fails the session through the tracker.
- """
- path = path or manifest_path()
- if not path.exists():
- return None
- failures = load_known_failures(path)
- collected = {item.nodeid for item in items}
- selected = {nodeid: exception for nodeid, exception in failures.items() if nodeid in collected}
- reason = f"Known ONNX conformance failure recorded in {path.name}; see its tracking issue there"
- for item in items:
- if exception := selected.get(item.nodeid):
- item.add_marker(pytest.mark.xfail(reason=reason, raises=exception, strict=True))
- return KnownFailureTracker(selected, path, reason)
diff --git a/tests/enhance/test_threshold.py b/tests/enhance/test_threshold.py
index 0537fedf2..21bfb954f 100644
--- a/tests/enhance/test_threshold.py
+++ b/tests/enhance/test_threshold.py
@@ -17,9 +17,12 @@
import pytest
import torch
+from torch._dynamo.testing import CompileCounter
from kornia.enhance.threshold import ThresholdType, threshold
+from testing.base import DYNAMO_UNAVAILABLE_REASON, dynamo_is_available
+
class TestThreshold:
@pytest.mark.parametrize(
@@ -76,6 +79,17 @@ class TestThreshold:
with pytest.raises(NotImplementedError):
threshold(x, thresh=0.0, maxval=1.0, type=ThresholdType.THRESH_OTSU)
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("ttype", [ThresholdType.THRESH_BINARY, ThresholdType.THRESH_TOZERO_INV])
+ def test_traces_in_one_graph_like_eager(self, ttype, device, dtype):
+ # The supported-type check must not iterate the enum class while tracing: torch 2.9's Dynamo cannot (#5819).
+ x = torch.rand(2, 3, 5, 7, device=device, dtype=dtype)
+ counter = CompileCounter()
+ torch._dynamo.reset()
+ traced = torch.compile(threshold, backend=counter, fullgraph=True)
+ torch.testing.assert_close(traced(x, 0.5, 1.0, ttype), threshold(x, 0.5, 1.0, ttype), rtol=0, atol=0)
+ assert counter.frame_count == 1
+
@pytest.mark.parametrize(
"image_dtype, values, thresh, ttype, expected",
[
diff --git a/tests/onnx/test_conformance.py b/tests/onnx/test_conformance.py
index b2c9319a0..f2cdbfebe 100644
--- a/tests/onnx/test_conformance.py
+++ b/tests/onnx/test_conformance.py
@@ -17,41 +17,42 @@
"""ONNX conformance of the promised operators (#5819).
-Every promised case (see ``testing/onnx_conformance.py``) must export with the ``torch.export``-based exporter
+Every promised case (see ``testing/conformance.py``) must export with the ``torch.export``-based exporter
(``torch.onnx.export(..., dynamo=True)``) and match eager execution in onnxruntime: the same dtype, and values within
the case's tolerance. A legacy (TorchScript) export that succeeds must match too; one that fails loudly passes.
Selected with ``--onnx-conformance=<package>[,<package>...]`` or ``all`` (env ``KORNIA_TEST_ONNX_CONFORMANCE``);
deselected otherwise. Known failures are strict xfails in
-``testing/known_failure_xfails/onnx_conformance_torch<major>.<minor>.txt``: delete an entry when its case passes.
+``testing/known_failure_xfails/onnx_conformance_torch<major>.<minor>.txt``: delete an entry when its case passes. A
+case that does not pass raises the exception ``testing.conformance.STATUS_EXCEPTIONS`` maps its status to, which its
+manifest entry names.
"""
from __future__ import annotations
-import logging
-import warnings
-
import pytest
-import torch
-from testing.onnx_conformance import (
+from testing.conformance import (
+ ENFORCED_TORCH_RELEASES,
LEGACY_PASSES,
- OPTION,
- describe,
+ ONNX,
import_survey_module,
- parse_selection,
- pretrained_cases,
+ load_known_failures,
+ manifest_path,
+ parametrize_cases,
+ pin_problems,
+ process_state,
+ promised_case,
promised_cases,
- promised_digest,
- registration_hooks,
- registries_of,
- registry_cases,
- run_case,
- selected_cases,
+ raise_for_status,
+ registration_problems,
+ run_onnx_case,
+ selection,
+ state_changes,
)
# Every case runs on CPU tensors and is compared in onnxruntime as numpy, whatever ``--device`` says. The registries
-# and the harness call torch.manual_seed, which seeds CUDA and MPS too; testing.onnx_conformance forks only the CPU
+# and the harness call torch.manual_seed, which seeds CUDA and MPS too; testing.conformance forks only the CPU
# generator, so restore_torch_rng puts the accelerator generators back.
pytestmark = [pytest.mark.device_agnostic, pytest.mark.usefixtures("restore_torch_rng")]
@@ -68,106 +69,57 @@ PROMISED_COUNT = 848
PROMISED_DIGEST = "7b8f869f2d8812be750269f7bed6d0b2db499f915c8ddf5c34fb76deb785912d"
-def _selection(config: pytest.Config) -> tuple[str, ...]:
- return parse_selection(config.getoption(OPTION))
-
-
def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
- if "case_name" not in metafunc.fixturenames:
- return
- names = selected_cases(_selection(metafunc.config))
- # Without a selection the root conftest deselects the placeholder; with one that has no promised case it skips.
- metafunc.parametrize("case_name", names or [pytest.param(None, id="unselected")])
-
-
-def _promised_case(case_name: str | None) -> dict:
- if case_name is None:
- pytest.skip("the selected packages have no promised case")
- case = registry_cases(registries_of([promised_cases()[case_name]])).get(case_name)
- if case is None or case["skip"] or not case["check"]:
- pytest.fail(f"{case_name!r} is promised but no registry case runs it; see test_promised_cases_are_registered")
- return case
+ parametrize_cases(metafunc, ONNX)
@pytest.mark.onnx_conformance
@quiet
def test_export_matches_eager(case_name: str | None) -> None:
- record = run_case(_promised_case(case_name), dynamo=True)
- assert record["status"] == "ok", describe(record)
+ raise_for_status(run_onnx_case(promised_case(ONNX, case_name), dynamo=True), ("ok",))
@pytest.mark.onnx_conformance
@quiet
def test_legacy_export_is_not_wrong(case_name: str | None) -> None:
- record = run_case(_promised_case(case_name), dynamo=False)
- assert record["status"] in LEGACY_PASSES, describe(record)
+ raise_for_status(run_onnx_case(promised_case(ONNX, case_name), dynamo=False), LEGACY_PASSES)
@pytest.mark.onnx_conformance
@quiet
def test_promised_cases_are_registered(request: pytest.FixtureRequest) -> None:
"""Every promised case of the selected packages has a registry case that runs and is compared with eager."""
- packages = _selection(request.config)
- registries = registries_of(packages)
- cases = registry_cases(registries)
- problems = []
- for name in selected_cases(packages):
- case = cases.get(name)
- if case is None:
- problems.append(f"{name}: no case of that name in {', '.join(registries) or 'no registry'}")
- elif case["skip"]:
- problems.append(f"{name}: skipped ({case['skip']})")
- elif not case["check"]:
- problems.append(f"{name}: check=False, the output is not compared with eager")
- # The promise leaves out pretrained cases by reading the registry sources; the imported registries must agree.
- tagged = {name for name, case in cases.items() if "pretrained" in case["tags"]}
- if disagree := tagged ^ (pretrained_cases() & cases.keys()):
- problems.append(f"registry tags and the static pretrained scan disagree on {sorted(disagree)}")
+ problems = registration_problems(ONNX, selection(request.config, ONNX))
assert not problems, "promised cases the registries no longer run:\n" + "\n".join(problems)
def test_promised_set_is_pinned() -> None:
- # The promise is read from the snapshot, so a regeneration that measured a case as failing would quietly drop it.
- # Pinning the names makes a change of the promised set a reviewed change of these two constants.
- promised = promised_cases()
- assert (len(promised), promised_digest(promised)) == (PROMISED_COUNT, PROMISED_DIGEST), (
- "the promised set changed; review the snapshot diff, then update PROMISED_COUNT and PROMISED_DIGEST"
- )
- assert not any(name.startswith(("models.", "contrib.")) for name in promised)
- assert not promised.keys() & pretrained_cases()
- # The root conftest deselects or skips tests whose id contains these words, which would drop the case silently.
- assert not [name for name in promised if any(word in name.lower() for word in ("dynamo", "compile", "autocast"))]
+ problems = pin_problems(ONNX, PROMISED_COUNT, PROMISED_DIGEST)
+ assert not problems, "\n".join(problems)
-def _process_state() -> dict:
- return {
- "threads": torch.get_num_threads(),
- "logging": logging.root.manager.disable,
- "filters": list(warnings.filters),
- "rng": torch.random.get_rng_state(),
- "hooks": registration_hooks(),
- }
[email protected]("version", ENFORCED_TORCH_RELEASES)
+def test_known_failure_manifest_names_promised_cases(version: str) -> None:
+ """The manifest of every enforced torch release parses, not only the running torch's, which the run reads."""
+ load_known_failures(ONNX, manifest_path(ONNX, version))
def test_survey_harness_leaves_process_state_alone() -> None:
"""Importing the harness and a registry changes nothing; running a case leaves only torch's own warning filters."""
- before = _process_state()
+ before = process_state()
import_survey_module("harness")
misc = import_survey_module("cases_misc")
- after_import = _process_state()
- assert torch.equal(after_import.pop("rng"), before["rng"])
- assert after_import == {key: value for key, value in before.items() if key != "rng"}
+ after_import = process_state()
+ assert not state_changes(before, after_import), (
+ f"importing the survey changed {state_changes(before, after_import)}"
+ )
+ assert after_import["filters"] == before["filters"]
- case = next(c for c in misc.CASES if c["name"] in promised_cases())
- records = [run_case(case, dynamo=dynamo) for dynamo in (True, False)]
- after = _process_state()
+ case = next(c for c in misc.CASES if c["name"] in promised_cases(ONNX))
+ records = [run_onnx_case(case, dynamo=dynamo) for dynamo in (True, False)]
assert all(record["status"] not in ("eager-fail", "skipped") for record in records), records
# A canary for the legacy test, which passes any export failure: this case exports with the legacy exporter on
# every supported torch, so an error of the harness itself (a renamed torch constant, say) cannot pass silently.
assert records[1]["status"] == "ok", records[1]
- assert torch.equal(after.pop("rng"), before["rng"])
- # A torch.export trace may add torch's own filters (torch 2.5 adds one for module "torch.distributed"); the
- # harness used to add a blanket "ignore everything" one. Anything new must name a torch module.
- added = [f for f in after.pop("filters") if f not in before["filters"]]
- assert all(f[3] is not None and f[3].pattern.startswith("torch") for f in added), added
- assert after == {key: value for key, value in before.items() if key not in ("rng", "filters")}
+ changes = state_changes(before, process_state())
+ assert not changes, f"running a case changed {changes}"
diff --git a/tests/scripts/test_onnx_conformance_packages.py b/tests/scripts/test_conformance_packages.py
similarity index 60%
rename from tests/scripts/test_onnx_conformance_packages.py
rename to tests/scripts/test_conformance_packages.py
index 16c627096..b20588339 100644
--- a/tests/scripts/test_onnx_conformance_packages.py
+++ b/tests/scripts/test_conformance_packages.py
@@ -22,22 +22,22 @@ from pathlib import Path
import pytest
-from testing import onnx_conformance
+from testing import conformance
# `.github/scripts/` is neither a package nor on the path; see tests/scripts/test_check_torch_env.py for why this
# stays a per-module insert.
sys.path.insert(0, str(Path(__file__).parent.parent.parent / ".github" / "scripts"))
-from onnx_conformance_packages import STABLE_CORE, select
+from conformance_packages import STABLE_CORE, TEST_FILES, select
REPO = Path(__file__).parent.parent.parent
-SCRIPT = REPO / ".github" / "scripts" / "onnx_conformance_packages.py"
+SCRIPT = REPO / ".github" / "scripts" / "conformance_packages.py"
pytestmark = pytest.mark.device_agnostic
-def _selected(paths):
- result = select(paths)
+def _selected(paths, promise="onnx"):
+ result = select(paths, promise=promise)
return set(result.split(",")) if result else set()
@@ -52,8 +52,9 @@ def _selected(paths):
["docs/export_support/cases_misc.py"],
["docs/source/_data/export_support.json"],
["docs/source/get-started/stability.rst"],
- ["testing/known_failure_xfails/onnx_conformance_torch2.14.txt"],
- ["tests/onnx/test_conformance.py"],
+ ["testing/known_failure_xfails/mps_float32.txt"],
+ ["testing/conformance.py"],
+ [".github/scripts/conformance_packages.py"],
[".github/workflows/pr_test_cpu.yml"],
["uv.lock"],
["pixi.toml"],
@@ -61,8 +62,30 @@ def _selected(paths):
["conftest.py"],
],
)
-def test_select_all(changed):
- assert select(changed) == "all"
[email protected]("promise", ["onnx", "compile"], ids=["onnx", "inductor"])
+def test_select_all(changed, promise):
+ assert select(changed, promise=promise) == "all"
+
+
+ ("changed", "promise"),
+ [
+ ("tests/onnx/test_conformance.py", "onnx"),
+ ("testing/known_failure_xfails/onnx_conformance_torch2.14.txt", "onnx"),
+ ("testing/known_failure_xfails/onnx_conformance_torch2.9.txt", "onnx"),
+ ("tests/test_inductor_conformance.py", "compile"),
+ ("testing/known_failure_xfails/compile_conformance_torch2.14.txt", "compile"),
+ ("testing/known_failure_xfails/compile_conformance_torch2.9.txt", "compile"),
+ ],
+ ids=["onnx-test", "onnx-current", "onnx-previous", "inductor-test", "inductor-current", "inductor-previous"],
+)
+def test_select_all_for_the_promise_of_a_changed_test_or_manifest(changed, promise):
+ # A promise's own test or manifest selects all of its cases, and nothing of the other promise.
+ other = "compile" if promise == "onnx" else "onnx"
+ assert select([changed], promise=promise) == "all"
+ assert select([changed], promise=other) == ""
+ # ... while a module changed with it still selects its packages for the other one
+ assert _selected([changed, "kornia/morphology/morphology.py"], other) == {"morphology"}
@pytest.mark.parametrize(
@@ -75,18 +98,20 @@ def test_select_all(changed):
[],
],
)
-def test_select_nothing(changed):
- assert select(changed) == ""
[email protected]("promise", ["onnx", "compile"], ids=["onnx", "inductor"])
+def test_select_nothing(changed, promise):
+ assert select(changed, promise=promise) == ""
-def test_select_follows_importers_in_the_repository():
[email protected]("promise", ["onnx", "compile"], ids=["onnx", "inductor"])
+def test_select_follows_importers_in_the_repository(promise):
# The PSNR losses call kornia.metrics.psnr: a fix there must run the losses' known failures too (#6165).
- assert _selected(["kornia/metrics/psnr.py"]) >= {"metrics", "losses"}
- assert "metrics" not in _selected(["kornia/losses/psnr.py"])
- assert _selected(["kornia/geometry/transform/imgwarp.py"]) >= {"geometry", "augmentation", "feature"}
+ assert _selected(["kornia/metrics/psnr.py"], promise) >= {"metrics", "losses"}
+ assert "metrics" not in _selected(["kornia/losses/psnr.py"], promise)
+ assert _selected(["kornia/geometry/transform/imgwarp.py"], promise) >= {"geometry", "augmentation", "feature"}
# PatchSequential crops with kornia.contrib.extract_patches; the DexiNed filter re-exports kornia.models.dexined.
- assert _selected(["kornia/contrib/extract_patches.py"]) >= {"augmentation"}
- assert _selected(["kornia/models/dexined.py"]) >= {"filters"}
+ assert _selected(["kornia/contrib/extract_patches.py"], promise) >= {"augmentation"}
+ assert _selected(["kornia/models/dexined.py"], promise) >= {"filters"}
def _write(root, files):
@@ -122,12 +147,14 @@ def test_select_resolves_each_import_form(tmp_path):
"kornia/filters/d.py": "from kornia.models.dex import N\n", # a name from a module
},
)
- assert select(["kornia/metrics/psnr.py"], tmp_path) == "losses,metrics"
- assert select(["kornia/color/hsv.py"], tmp_path) == "augmentation,color"
- assert select(["kornia/geometry/y.py"], tmp_path) == "geometry,feature"
- assert select(["kornia/models/dex.py"], tmp_path) == "filters"
- assert select(["kornia/contrib/c.py", "kornia/models/sam.py"], tmp_path) == ""
- assert select(["kornia/color/removed.py"], tmp_path) == "color" # a deleted module stands for its package
+ assert select(["kornia/metrics/psnr.py"], tmp_path, promise="onnx") == "losses,metrics"
+ assert select(["kornia/color/hsv.py"], tmp_path, promise="onnx") == "augmentation,color"
+ assert select(["kornia/geometry/y.py"], tmp_path, promise="onnx") == "geometry,feature"
+ assert select(["kornia/models/dex.py"], tmp_path, promise="onnx") == "filters"
+ assert select(["kornia/contrib/c.py", "kornia/models/sam.py"], tmp_path, promise="onnx") == ""
+ assert (
+ select(["kornia/color/removed.py"], tmp_path, promise="onnx") == "color"
+ ) # a deleted module stands for its package
def test_select_follows_importers_of_a_deleted_nested_module(tmp_path):
@@ -144,7 +171,7 @@ def test_select_follows_importers_of_a_deleted_nested_module(tmp_path):
"kornia/feature/uses.py": "from kornia.geometry.transform.removed import warp\n",
},
)
- assert select(["kornia/geometry/transform/removed.py"], tmp_path) == "geometry,feature"
+ assert select(["kornia/geometry/transform/removed.py"], tmp_path, promise="onnx") == "geometry,feature"
@pytest.mark.parametrize(
@@ -156,7 +183,7 @@ def test_select_follows_importers_of_a_deleted_nested_module(tmp_path):
)
def test_cli_reads_stdin(stdin):
result = subprocess.run( # noqa: S603 -- the current test interpreter on the script under test.
- [sys.executable, str(SCRIPT)],
+ [sys.executable, str(SCRIPT), "onnx"],
input=stdin,
capture_output=True,
text=True,
@@ -168,7 +195,7 @@ def test_cli_reads_stdin(stdin):
def test_cli_reads_whitespace_separated_paths():
# One echo line with several paths must select what the paths select one per line.
result = subprocess.run( # noqa: S603 -- the current test interpreter on the script under test.
- [sys.executable, str(SCRIPT)],
+ [sys.executable, str(SCRIPT), "compile"],
input="kornia/morphology/morphology.py kornia/core/check.py\n",
capture_output=True,
text=True,
@@ -177,9 +204,22 @@ def test_cli_reads_whitespace_separated_paths():
assert result.stdout == "all\n"
+def test_cli_requires_a_promise():
+ result = subprocess.run( # noqa: S603 -- the current test interpreter on the script under test.
+ [sys.executable, str(SCRIPT)],
+ input="kornia/morphology/morphology.py\n",
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 2
+ assert "promise" in result.stderr
+
+
def test_stable_core_matches_the_test_and_the_stability_page():
- assert STABLE_CORE == onnx_conformance.STABLE_CORE
- assert set(onnx_conformance.REGISTRIES_OF) == set(STABLE_CORE)
+ assert STABLE_CORE == conformance.STABLE_CORE
+ assert set(conformance.REGISTRIES_OF) == set(STABLE_CORE)
+ assert TEST_FILES == {promise.field: promise.test_file for promise in conformance.PROMISES}
page = (REPO / "docs" / "source" / "get-started" / "stability.rst").read_text(encoding="utf-8")
paragraph = page.split("**Stable core**", 1)[1].split("\n\n", 1)[0]
assert set(re.findall(r"``kornia\.(\w+)``", paragraph)) == set(STABLE_CORE)
diff --git a/tests/test_inductor_conformance.py b/tests/test_inductor_conformance.py
new file mode 100644
index 000000000..eda78785a
--- /dev/null
+++ b/tests/test_inductor_conformance.py
@@ -0,0 +1,179 @@
+# 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.
+#
+
+"""torch.compile conformance of the promised operators (#5819).
+
+Every promised case (see ``testing/conformance.py``) must compile with ``torch.compile(..., fullgraph=True)`` and the
+default inductor backend -- no graph break -- and match eager execution: the same dtype, and values within the case's
+tolerance. One call per case, at the registry's input shapes, as the survey measures; a recompile at another shape is
+not part of the promise.
+
+Selected with ``--compile-conformance=<package>[,<package>...]`` or ``all`` (env ``KORNIA_TEST_COMPILE_CONFORMANCE``);
+deselected otherwise. Known failures are strict xfails in
+``testing/known_failure_xfails/compile_conformance_torch<major>.<minor>.txt``: delete an entry when its case passes. A
+case that does not pass raises the exception ``testing.conformance.STATUS_EXCEPTIONS`` maps its status to
+(``AssertionError`` for a wrong result, ``RuntimeError`` for a failed compile, ``ValueError`` for a failed eager
+reference), which its manifest entry names. The test needs neither onnx nor onnxruntime.
+
+The root conftest drops a test whose name or id contains "compile" or "dynamo" unless ``KORNIA_TEST_OPTIMIZER`` is
+set, so the tests here are named after inductor; this test does not use ``KORNIA_TEST_OPTIMIZER``.
+"""
+
+from __future__ import annotations
+
+import pytest
+import torch
+
+from testing.conformance import (
+ COMPILE,
+ ENFORCED_TORCH_RELEASES,
+ describe,
+ import_survey_module,
+ load_known_failures,
+ manifest_path,
+ parametrize_cases,
+ pin_problems,
+ process_state,
+ promised_case,
+ promised_cases,
+ raise_for_status,
+ registration_problems,
+ run_compile_case,
+ selection,
+ state_changes,
+)
+
+# Every case runs on CPU tensors, whatever ``--device`` says. The registries and the probe call torch.manual_seed,
+# which seeds CUDA and MPS too; testing.conformance forks only the CPU generator, so restore_torch_rng puts the
+# accelerator generators back.
+pytestmark = [pytest.mark.device_agnostic, pytest.mark.usefixtures("restore_torch_rng")]
+
+# Dynamo and inductor warn about graphs they handle; the per-case tests keep the session output readable. Not
+# module-wide: the process-state tests must see a filter the probe would add.
+quiet = pytest.mark.filterwarnings("ignore")
+
+# The compile promise of the 2026-09-02 snapshot: 832 cases of 637 operators.
+PROMISED_COUNT = 832
+PROMISED_DIGEST = "8461e5c612ed2c8aa696633f3dc9f4154bfcb8c1cc01f19a2ddb29610e9b188d"
+
+
+def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
+ parametrize_cases(metafunc, COMPILE)
+
+
[email protected]_conformance
+@quiet
+def test_inductor_matches_eager(case_name: str | None) -> None:
+ raise_for_status(run_compile_case(promised_case(COMPILE, case_name)), ("ok",), "compile")
+
+
[email protected]_conformance
+@quiet
+def test_promised_cases_are_registered(request: pytest.FixtureRequest) -> None:
+ """Every promised case of the selected packages has a registry case that runs and is compared with eager."""
+ problems = registration_problems(COMPILE, selection(request.config, COMPILE))
+ assert not problems, "promised cases the registries no longer run:\n" + "\n".join(problems)
+
+
+def test_promised_set_is_pinned() -> None:
+ problems = pin_problems(COMPILE, PROMISED_COUNT, PROMISED_DIGEST)
+ assert not problems, "\n".join(problems)
+
+
[email protected]("version", ENFORCED_TORCH_RELEASES)
+def test_known_failure_manifest_names_promised_cases(version: str) -> None:
+ """The manifest of every enforced torch release parses, not only the running torch's, which the run reads."""
+ load_known_failures(COMPILE, manifest_path(COMPILE, version))
+
+
+def test_survey_probe_import_leaves_process_state_alone() -> None:
+ """Importing the compile probe (and with it the harness) and a registry changes nothing."""
+ before = process_state()
+ import_survey_module("probe_compile")
+ import_survey_module("cases_misc")
+ after = process_state()
+ assert not state_changes(before, after), f"importing the survey changed {state_changes(before, after)}"
+ assert after["filters"] == before["filters"]
+
+
+def test_survey_probe_records_failures_and_lets_test_outcomes_through(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A failed export or compile is recorded; a test's own outcome, such as pytest-timeout's expiry, ends the test.
+
+ Recorded, a timeout would become a ``fail`` record, which a known-failure entry of the same type absorbs.
+ """
+ probe = import_survey_module("probe_compile")
+ harness = import_survey_module("harness")
+ case = harness.case("neg", "test", torch.neg, [torch.ones(2)])
+ wrap, inputs, ref = probe._reference(case)
+
+ def raising(error: BaseException):
+ def refuse(*args, **kwargs):
+ raise error
+
+ return refuse
+
+ monkeypatch.setattr(torch, "compile", raising(probe.Timeout("case exceeded 420s")))
+ record = probe.compile_step(case, wrap, inputs, ref, fullgraph=True)
+ assert record["compile"] == "fail", record
+ assert "Timeout" in record["compile_error"], record
+ monkeypatch.setattr(torch, "compile", raising(pytest.fail.Exception("Timeout (>600.0s) from pytest-timeout.")))
+ with pytest.raises(pytest.fail.Exception, match="pytest-timeout"):
+ probe.compile_step(case, wrap, inputs, ref, fullgraph=True)
+ monkeypatch.setattr(
+ torch.export, "export", raising(pytest.fail.Exception("Timeout (>600.0s) from pytest-timeout."))
+ )
+ with pytest.raises(pytest.fail.Exception, match="pytest-timeout"):
+ probe.export_step(wrap, inputs)
+
+
[email protected]_conformance
+def test_survey_probe_leaves_process_state_alone() -> None:
+ """Compiling a case leaves the RNG, torch's hooks and the dynamo and inductor configs; it adds only torch filters.
+
+ Marked like the per-case tests: it needs inductor's C++ toolchain, which the conformance jobs have and not every
+ leg of the ordinary suite does.
+ """
+ before = process_state()
+ misc = import_survey_module("cases_misc")
+ case = next(c for c in misc.CASES if c["name"] in promised_cases(COMPILE))
+ record = run_compile_case(case)
+ # A canary: this case compiles on every enforced torch, so an error of the probe itself cannot pass silently.
+ assert record["compile"] == "ok", describe(record, "compile")
+ changes = state_changes(before, process_state())
+ assert not changes, f"compiling a case changed {changes}"
+
+
[email protected]_conformance
+@quiet
+def test_survey_probe_rejects_conjugated_output(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A real compiled promised case must fail conformance if its imaginary component is corrupted."""
+ case = promised_case(COMPILE, "geometry.liegroup.So2.exp.z")
+ original_compile = torch.compile
+
+ def conjugating_compile(*args, **kwargs):
+ compiled = original_compile(*args, **kwargs)
+
+ def conjugated(*inputs):
+ return tuple(output.conj().resolve_conj() for output in compiled(*inputs))
+
+ return conjugated
+
+ monkeypatch.setattr(torch, "compile", conjugating_compile)
+ record = run_compile_case(case)
+ assert record["graph_breaks"] == 0, record
+ assert record["compile"] == "mismatch", describe(record, "compile")
+ assert "max abs diff" in record["compile_error"], record
diff --git a/tests/test_survey_harness.py b/tests/test_survey_harness.py
new file mode 100644
index 000000000..acfdf617f
--- /dev/null
+++ b/tests/test_survey_harness.py
@@ -0,0 +1,70 @@
+# 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.
+#
+
+"""Numerical comparisons shared by the export and inductor conformance probes."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+
+from testing.conformance import import_survey_module
+
+pytestmark = pytest.mark.device_agnostic
+
+
[email protected]("dtype", [np.complex64, np.complex128], ids=["single", "double"])
[email protected]("as_tensor", [False, True], ids=["numpy", "torch"])
+ ("reference", "candidate", "expected"),
+ [
+ (1 + 2j, 1 + 2j, True),
+ (1 + 2j, 1 + 2.000001j, True),
+ (1 + 2j, 1 - 20j, False),
+ (1 + 2j, 10 + 2j, False),
+ (complex(np.nan, 2), complex(np.nan, 2), True),
+ (complex(1, np.nan), complex(1, np.nan), True),
+ (complex(np.nan, 2), complex(np.nan, 20), False),
+ (complex(1, np.nan), complex(10, np.nan), False),
+ (complex(np.nan, 2), complex(1, np.nan), False),
+ (complex(1, np.nan), complex(1, 2), False),
+ (complex(np.inf, 2), complex(np.inf, 2), True),
+ (complex(np.inf, 2), complex(np.inf, 20), False),
+ ],
+ ids=[
+ "equal",
+ "within-tolerance",
+ "imaginary-mismatch",
+ "real-mismatch",
+ "real-nan-equal",
+ "imaginary-nan-equal",
+ "real-nan-imaginary-mismatch",
+ "imaginary-nan-real-mismatch",
+ "nan-components-differ",
+ "nan-pattern-differs",
+ "infinity-equal",
+ "infinity-imaginary-mismatch",
+ ],
+)
+def test_close_complex(reference, candidate, expected, dtype, as_tensor):
+ a, b = np.array([reference], dtype=dtype), np.array([candidate], dtype=dtype)
+ if as_tensor:
+ a, b = torch.from_numpy(a), torch.from_numpy(b)
+ ok, reason = import_survey_module("harness").close(a, b, atol=1e-5, rtol=1e-5)
+ assert ok is expected, reason
+ assert bool(reason) is not expected