π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
test(onnx): conformance test for the promised ONNX operators (#5819), with scheduled and PR CI jobs (#6171)
Dmytro Mishkin8e9baa00327e
diff --git a/.github/scripts/onnx_conformance_packages.py b/.github/scripts/onnx_conformance_packages.pynew file mode 100755index 000000000..c4416b1f6--- /dev/null+++ b/.github/scripts/onnx_conformance_packages.py@@ -0,0 +1,230 @@+#!/usr/bin/env python3++# 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.+#+"""Map a pull request's changed paths to the ``--onnx-conformance`` selection of its CI run (#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).++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``:+``import kornia.x.y``, ``from kornia.x import y``, relative imports, and ``kornia.x.y`` attribute chains after a bare+``import kornia``, at module granularity (importing ``kornia.x.y`` depends on ``kornia/x/y.py`` or on the package+``kornia/x/y/__init__.py``, which depends on what it imports in turn). So a change to ``kornia/metrics/psnr.py`` also+selects ``losses``, whose PSNR losses call it, while a ``kornia/contrib`` module no stable-core module reaches selects+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.++Standard library only: the ``changes`` job runs it before any environment is installed.+"""++from __future__ import annotations++import ast+import functools+import sys+from collections import defaultdict+from collections.abc import Iterable+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.+STABLE_CORE = (+ "geometry",+ "augmentation",+ "color",+ "filters",+ "enhance",+ "losses",+ "metrics",+ "morphology",+ "io",+ "image",+ "core",+ "feature",+)++# Code every package runs, or the promise and the machinery that checks it.+ALL_PREFIXES = (+ "kornia/core/",+ "kornia/utils/",+ "kornia/onnx/",+ "docs/export_support/",+ "testing/",+)+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/workflows/tests.yml",+ ".github/workflows/pr_test_cpu.yml",+ ".github/workflows/scheduled_test_cpu.yml",+ "conftest.py",+ "pyproject.toml",+ "uv.lock",+)+++def module_index(root: Path) -> dict[str, Path]:+ """Map every module under ``root/kornia`` to its file: ``kornia.x.y`` for ``x/y.py`` or ``x/y/__init__.py``."""+ index: dict[str, Path] = {}+ for path in sorted((root / "kornia").rglob("*.py")):+ parts = path.relative_to(root).with_suffix("").parts+ if parts[-1] == "__init__":+ parts = parts[:-1]+ index[".".join(parts)] = path+ return index+++def _resolve(name: str, index: dict[str, Path]) -> str | None:+ """The longest prefix of the dotted ``name`` that is a kornia module other than the root package."""+ parts = name.split(".")+ for end in range(len(parts), 1, -1):+ candidate = ".".join(parts[:end])+ if candidate in index:+ return candidate+ return None+++def _attribute_chain(node: ast.Attribute) -> list[str] | None:+ names: list[str] = []+ current: ast.expr = node+ while isinstance(current, ast.Attribute):+ names.append(current.attr)+ current = current.value+ if not isinstance(current, ast.Name):+ return None+ names.append(current.id)+ return names[::-1]+++def imported_modules(module: str, path: Path, index: dict[str, Path]) -> set[str]:+ """The kornia modules ``module`` imports anywhere in its body, function-local imports included."""+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ package = module if path.name == "__init__.py" else module.rpartition(".")[0]+ found: set[str] = set()+ root_aliases: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name == "kornia" or alias.name.startswith("kornia."):+ if alias.asname is None or alias.name == "kornia":+ root_aliases.add(alias.asname or "kornia")+ if (target := _resolve(alias.name, index)) is not None:+ found.add(target)+ elif isinstance(node, ast.ImportFrom):+ if node.level:+ anchor = package.split(".")+ anchor = anchor[: len(anchor) - (node.level - 1)]+ base = ".".join(anchor + ([node.module] if node.module else []))+ else:+ base = node.module or ""+ if base != "kornia" and not base.startswith("kornia."):+ continue+ for alias in node.names:+ # ``from kornia.x import y``: the submodule y when there is one, else the module that defines y+ full = f"{base}.{alias.name}"+ target = full if full in index else _resolve(base, index)+ if target is not None:+ found.add(target)+ # ``kornia.x.y.f(...)`` after a bare ``import kornia``: the deepest module of the chain, once per chain+ inner = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Attribute)}+ for node in ast.walk(tree):+ if isinstance(node, ast.Attribute) and id(node) not in inner:+ chain = _attribute_chain(node)+ if chain and chain[0] in root_aliases and (target := _resolve(".".join(["kornia", *chain[1:]]), index)):+ found.add(target)+ found.discard(module)+ return found+++def importers(index: dict[str, Path]) -> dict[str, set[str]]:+ """Reverse import graph: module -> the modules that import it."""+ reverse: dict[str, set[str]] = defaultdict(set)+ for module, path in index.items():+ if module == "kornia": # the root package only re-exports; nothing resolves to it+ continue+ for target in imported_modules(module, path, index):+ reverse[target].add(module)+ return reverse+++def _package(module: str) -> str:+ return module.split(".")[1]+++def _graph(root: Path) -> tuple[dict[str, str], dict[str, set[str]]]:+ index = module_index(root)+ 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."""+ 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."):+ return "all"+ parts = path.split("/")+ if parts[0] != "kornia":+ continue+ if len(parts) == 2: # kornia/__init__.py, kornia/constants.py, ...: imported by every package+ return "all"+ changed.add(path)+ if not changed:+ return ""+ by_path, reverse = _graph(root)+ index = {module: root / path for path, module in by_path.items()}+ affected: set[str] = set()+ for path in changed:+ if (module := by_path.get(path)) is not None:+ affected.add(module)+ continue+ # a deleted file, or data next to the code, stands for its package's ``__init__``; a deleted module also for+ # the nearest module that survives it, where the imports of its remaining importers now resolve+ affected.add(f"kornia.{path.split('/')[1]}")+ if path.endswith(".py") and (survivor := _resolve(path.removesuffix(".py").replace("/", "."), index)):+ affected.add(survivor)+ pending = list(affected)+ while pending:+ for importer in reverse.get(pending.pop(), set()) - affected:+ affected.add(importer)+ pending.append(importer)+ packages = {_package(module) for module in affected}+ 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()))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.ymlindex e9cbdad60..aa166b92b 100644--- a/.github/workflows/pr_test_cpu.yml+++ b/.github/workflows/pr_test_cpu.yml@@ -19,6 +19,7 @@ jobs:timeout-minutes: 10outputs:run-tests: ${{ steps.filter.outputs.run-tests }}+ onnx-conformance: ${{ steps.filter.outputs.onnx-conformance }}steps:- uses: actions/checkout@v7with:@@ -31,10 +32,16 @@ jobs:run: |if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; thenecho "run-tests=true" >> "$GITHUB_OUTPUT"+ echo "onnx-conformance=all" >> "$GITHUB_OUTPUT"exit 0fichanged=$(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")+ echo "onnx-conformance=$conformance" >> "$GITHUB_OUTPUT"+ echo "ONNX conformance selection: '${conformance}'"if grep -Eqv '^(docs/|.*\.md$|LICENSE$|COPYRIGHT$)' <<< "$changed"; thenecho "run-tests=true" >> "$GITHUB_OUTPUT"else@@ -235,6 +242,24 @@ jobs:model-weights-${{ needs.pre-tests.outputs.hash }}model-weights-+ # 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+ # (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:+ needs: [changes]+ if: needs.changes.outputs.onnx-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/onnx/test_conformance.py+ pytest-extra: --onnx-conformance=${{ needs.changes.outputs.onnx-conformance }}+typecheck:needs: [pre-tests]uses: ./.github/workflows/typecheck.yml@@ -243,7 +268,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, typecheck]+ needs: [changes, pre-tests, tests, tests-mps, half-precision, dynamo, onnx-conformance, typecheck]if: always()runs-on: ubuntu-latesttimeout-minutes: 5diff --git a/.github/workflows/scheduled_test_cpu.yml b/.github/workflows/scheduled_test_cpu.ymlindex b8e6e54c2..02c18b152 100644--- a/.github/workflows/scheduled_test_cpu.yml+++ b/.github/workflows/scheduled_test_cpu.yml@@ -99,9 +99,16 @@ jobs:CHANGED_FILES=$(git diff --name-only "$PREV_SHA" HEAD)- # Skip only if every changed file is documentation+ # 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).SHOULD_SKIP="true"for file in $CHANGED_FILES; do+ if [[ "$file" =~ ^docs/export_support/ ]] || \+ [[ "$file" == "docs/source/_data/export_support.json" ]] || \+ [[ "$file" == "docs/source/get-started/stability.rst" ]]; then+ SHOULD_SKIP="false"+ break+ fiif [[ ! "$file" =~ ^docs/ ]] && \[[ ! "$file" =~ \.md$ ]] && \[[ "$file" != "LICENSE" ]] && \@@ -191,6 +198,20 @@ jobs:model-weights-${{ needs.pre-tests.outputs.hash }}model-weights-+ # ONNX 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.+ onnx-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/onnx/test_conformance.py+ pytest-extra: --onnx-conformance=all+tests-cpu-windows:needs: [check-skip, pre-tests]if: needs.check-skip.outputs.should-skip == 'false'diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 24629b27b..cb23d17ad 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -33,6 +33,12 @@ on:required: falsetype: stringdefault: 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.+ required: false+ type: string+ default: ""pytest-extra:required: falsetype: string@@ -242,7 +248,12 @@ jobs:MKL_NUM_THREADS: "1"OMP_NUM_THREADS: "1"UV_NO_SYNC: "1"+ TEST_PATH: ${{ inputs.test-path }}run: |+ test_task=(test)+ if [[ -n "$TEST_PATH" ]]; then+ test_task=(test-module "$TEST_PATH")+ fiknown_failure_args=()candidate_path=""case "$KNOWN_FAILURE_MODE" in@@ -272,7 +283,7 @@ jobs:# must still fail the job. Explicit `shell: bash` enables pipefail, so suspend# errexit around the pipeline long enough to inspect pytest's own status.set +e- pixi run -e ${{ steps.pixi-env.outputs.name }} test \+ pixi run -e ${{ steps.pixi-env.outputs.name }} "${test_task[@]}" \$KORNIA_CI_PYTEST_VERBOSITY "${known_failure_args[@]}" ${{ inputs.pytest-extra }} | tee pytest-output.logpipeline_status=("${PIPESTATUS[@]}")test_status=${pipeline_status[0]}@@ -291,7 +302,7 @@ jobs:fiexit "$test_status"else- pixi run -e ${{ steps.pixi-env.outputs.name }} test \+ pixi run -e ${{ steps.pixi-env.outputs.name }} "${test_task[@]}" \$KORNIA_CI_PYTEST_VERBOSITY "${known_failure_args[@]}" ${{ inputs.pytest-extra }}fidiff --git a/AGENTS.md b/AGENTS.mdindex 5f9b0f83c..4943fe731 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -143,6 +143,8 @@ Follow the methodology contract and new-benchmark checklist in [benchmarks/READMONNX 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.+## Helping users diagnose problemsStart with a minimal reproduction and the narrowest relevant test. Do not claim a failure is pre-existing until you have compared against the relevant base revision safely.diff --git a/TESTING.md b/TESTING.mdindex 4aeefd17b..08cd4b250 100644--- a/TESTING.md+++ b/TESTING.md@@ -42,6 +42,7 @@ pixi run test-quick| `--record-known-failures=PATH` | none | unset | Record a complete profile to a guarded, untracked candidate path || `--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) |## Test Structure@@ -69,6 +70,36 @@ The `device` and `dtype` fixtures are injected automatically from the CLI option| `@pytest.mark.device_agnostic` | Test runs once in a CPU-containing matrix because its logic does not use the selected accelerator. An accelerator-only run deselects it and says so on a line of its own at the start of the run, because the deselected set includes the ONNX and `torch.export` suites; `--run-device-agnostic` forces it back on || `@pytest.mark.slow` | Long-running test; skipped unless `--runslow` is passed || `@pytest.mark.tf32` | Known to fail under TF32 (see section below); xfail unless `--tf32` |+| `@pytest.mark.onnx_conformance` | Part of the ONNX conformance test; deselected unless `--onnx-conformance` selects packages |++### ONNX conformance (#5819)++`tests/onnx/test_conformance.py` holds kornia's ONNX promise: every *promised* case -- a record of the survey+snapshot `docs/source/_data/export_support.json` with ONNX status `ok` in a stable-core package+(`docs/source/get-started/stability.rst`), without anything built from pretrained weights (registry tag `pretrained`)+-- must export with `torch.onnx.export(..., dynamo=True)` and match eager execution in onnxruntime (the same dtype,+values within the case's tolerance), and a legacy (TorchScript) export that succeeds must match as well; one that+fails loudly passes. The cases are the survey's own (`docs/export_support/cases_*.py`, joined by name;+`cases_models.py` is never imported) and run through `docs/export_support/harness.py`, so the test and the survey page+cannot drift apart: `test_promised_cases_are_registered` fails when a promised case is missing or skipped in its+registry, and `test_promised_set_is_pinned` when the promised names change.++```bash+pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=all+pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=geometry,color+```++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+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+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.---diff --git a/changelog.d/6171.fixed.md b/changelog.d/6171.fixed.mdnew file mode 100644index 000000000..46d4b56c8--- /dev/null+++ b/changelog.d/6171.fixed.md@@ -0,0 +1,3 @@+`rgb_to_yuv422` and `RgbToYuv422` export correctly with the legacy (TorchScript) ONNX exporter on torch 2.9.1 and+2.14. Before, the exported graph returned the UV planes with the window and window-count axes swapped, shape+`(*, 2, H, 2)` instead of `(*, 2, H, W/2)`. On torch 2.5.1 that export still raises, as it did before.diff --git a/conftest.py b/conftest.pyindex f6eb46fb4..e385dbbef 100644--- a/conftest.py+++ b/conftest.py@@ -34,6 +34,7 @@ from torch.distributions import Distributionimport korniafrom kornia.core.download import load_state_dict_from_url+from testing import onnx_conformancefrom testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reasonfrom testing.half_precision_ci import (FailureRecorder,@@ -287,6 +288,12 @@ 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")profile = _configure_known_failure_profile(config)config._known_failure_profile = profileif profile is None:@@ -425,6 +432,15 @@ def pytest_collection_modifyitems(config, items):# Filter out tests with "dynamo" or "compile" in their nameitems[:] = [item for item in items if "dynamo" not in item.name.lower() and "compile" not in item.name.lower()]+ # 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]+ if conformance_items:+ config.hook.pytest_deselected(items=conformance_items)+ conformance_ids = {id(item) for item in conformance_items}+ items[:] = [item for item in items if id(item) not in conformance_ids]+if config.getoption("--xfail-known-failures") and getattr(config, "_known_failure_profile", None) is None:devices = _parse_test_option(config, "--device", TEST_DEVICES)dtypes = _parse_test_option(config, "--dtype", TEST_DTYPES)@@ -577,6 +593,17 @@ 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})"+ ),+ )parser.addoption("--xfail-known-failures",action="store_true",diff --git a/docs/export_support/README.md b/docs/export_support/README.mdindex 607e9d3e4..812a1a2c9 100644--- a/docs/export_support/README.md+++ b/docs/export_support/README.md@@ -16,13 +16,13 @@ inputs, registered in one of the `cases_*.py` files:| `cases_feature.py` | `kornia.feature` (detectors, descriptors, matchers) || `cases_geomA.py` | `kornia.geometry` transforms, conversions, cameras, calibration || `cases_geomB.py` | the rest of `kornia.geometry` (epipolar, Lie groups, boxes, ...) |-| `cases_misc.py` | `kornia.filters`, `color`, `enhance`, `morphology`, `contrib`, `losses`, `metrics`, `utils`, `sensors`, `io`, `nerf`, `tracking`, `x` |-| `cases_models.py` | `kornia.models` (weights are downloaded when they are not cached) |+| `cases_misc.py` | `kornia.filters`, `color`, `enhance`, `morphology`, `image`, `losses`, `metrics`, `utils` |+| `cases_models.py` | `kornia.models`, `contrib`, `sensors`, `tracking`, `x` (weights are downloaded when they are not cached) |For each case:- **ONNX** (`harness.py`): `torch.onnx.export(dynamo=True, opset_version=18)`, `onnx.checker`,- then an `onnxruntime` run compared against eager.+ 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 againsteager.@@ -31,6 +31,15 @@ Random operators cannot be compared value-for-value (the RNG stream differs insithey are reported as *ok-unverified* when the captured program runs and returns finite outputs ofthe 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.+## Regenerating the snapshot```bashdiff --git a/docs/export_support/cases_aug.py b/docs/export_support/cases_aug.pyindex c77395073..52cd63ff3 100644--- a/docs/export_support/cases_aug.py+++ b/docs/export_support/cases_aug.py@@ -80,8 +80,8 @@ class Rand(nn.Module):def forward(self, *xs):return self.aug(*xs[: self.n_data])- def eval(self): # keep the augmentation in train mode (harness calls .eval())- return self+ def train(self, mode: bool = True): # keep the augmentation in train mode whatever eval() / train(False) ask+ return super().train(True)CASES: list = []diff --git a/docs/export_support/cases_feature.py b/docs/export_support/cases_feature.pyindex 6959548d0..e94e962f5 100644--- a/docs/export_support/cases_feature.py+++ b/docs/export_support/cases_feature.py@@ -24,7 +24,7 @@ import tracebackimport torchimport torch.nn.functional as F-from harness import case, run_cases+from harness import case, err_str, run_casesimport kornia.feature as KF@@ -125,7 +125,8 @@ def try_build(name: str, fn):return fn(), Noneexcept Exception as e:traceback.print_exc()- return None, f"could not build/download {name}: {type(e).__name__}: {str(e)[:120]}"+ # the root cause: a loader that tries several sources reports the last one's error only as its cause+ return None, f"could not build/download {name}: {err_str(e)}"def pcase(name, group, builder, inputs, kwargs=None, **kw):@@ -226,8 +227,21 @@ CASES += [{"PS": 16},note="PS baked",),- case("feature.laf_is_valid", L, KF.laf_is_valid, [LAF], note="bool (B,N) output"),- case("feature.laf_is_inside_image", L, KF.laf_is_inside_image, [LAF, IMG], {"border": 2}, note="bool output"),+ case(+ "feature.laf_is_valid",+ L,+ KF.laf_is_valid,+ [LAF * torch.tensor([1.0, 1.0, 0.0, 1.0, 0.0])[None, :, None, None]],+ note="bool (B,N) output; LAFs 2 and 4 zeroed, so invalid",+ ),+ case(+ "feature.laf_is_inside_image",+ L,+ KF.laf_is_inside_image,+ [torch.cat([LAF, LAF_BIG], 1), IMG],+ {"border": 2},+ note="bool output; the LAFs placed in 64x80 fall outside the 32x40 image",+ ),case("feature.laf_to_three_points", L, KF.laf_to_three_points, [LAF]),case("feature.laf_from_three_points", L, KF.laf_from_three_points, [KF.laf_to_three_points(LAF)]),case("feature.perspective_transform_lafs", L, KF.perspective_transform_lafs, [H_01, LAF]),diff --git a/docs/export_support/cases_geomA.py b/docs/export_support/cases_geomA.pyindex c0c254f09..ea419e5f0 100644--- a/docs/export_support/cases_geomA.py+++ b/docs/export_support/cases_geomA.py@@ -509,7 +509,10 @@ CASES = ["transform.HomographyWarper[pixel]",G,T.HomographyWarper(H, W, normalized_coordinates=False),- [img, homo33_pert],+ # The normal_transform_pixel factor works around #6170 (the pixel grid reaches grid_sample unnormalized, so+ # a pixel homography samples outside the image and the output is a constant zero); drop it when #6170 is fixed.+ [img, K.geometry.conversions.normal_transform_pixel(H, W) @ homo33_pert],+ note="homography includes normal_transform_pixel until #6170 is fixed",),case("transform.HomographyWarper[precomputed]",diff --git a/docs/export_support/cases_geomB.py b/docs/export_support/cases_geomB.pyindex b00e425d0..3190e11f3 100644--- a/docs/export_support/cases_geomB.py+++ b/docs/export_support/cases_geomB.py@@ -316,8 +316,8 @@ CASES = [_ch("sample_is_valid_for_homography",K.geometry.homography.sample_is_valid_for_homography,- [hp1_4, hp2_4],- note="returns bool (B,)",+ [hp1_4.repeat(2, 1, 1), torch.cat([hp2_4, hp2_4 * torch.tensor([-1.0, 1.0])])],+ note="returns bool (B,); the second sample is mirrored, so it is invalid",),_ch("normalize_points", K.geometry.homography.normalize_points, [hp1]),_ch("safe_inverse_with_mask", K.geometry.homography.safe_inverse_with_mask, [H_gt]),diff --git a/docs/export_support/cases_misc.py b/docs/export_support/cases_misc.pyindex f72833737..329fba29c 100644--- a/docs/export_support/cases_misc.py+++ b/docs/export_support/cases_misc.py@@ -15,7 +15,7 @@# limitations under the License.#-"""ONNX export survey β area `misc`: everything in color/enhance/filters/losses/metrics/utils/morphology+"""ONNX export survey β area `misc`: everything in color/enhance/filters/losses/metrics/utils/morphology/imagenot already covered by the first pass (survey.json)."""import sys@@ -31,6 +31,8 @@ import kornia.losses as KLimport kornia.metrics as KMfrom kornia.color import CFA, ColorMap, ColorMapTypefrom kornia.enhance import ThresholdType+from kornia.image import ChannelsOrder, Image, ImageLayout, ImageSize, PixelFormat+from kornia.image.base import ColorSpacefrom kornia.utils import torch_meshgrid as _torch_meshgridtorch.manual_seed(0)@@ -1267,5 +1269,95 @@ add()add("morphology.gradient[batch]", g, K.morphology.gradient, [IMGB, torch.ones(3, 3)], tags=("batch>1",))+# ------------------------------------------------------------------------------------------------ image+# kornia.image is stable core, so its cases live here rather than in cases_models.py, which the ONNX conformance+# test (tests/onnx/test_conformance.py) never imports.+g = "image"+++def _mk_image(t: torch.Tensor, cs: ColorSpace = ColorSpace.RGB) -> Image:+ layout = ImageLayout(ImageSize(t.shape[-2], t.shape[-1]), t.shape[-3], ChannelsOrder.CHANNELS_FIRST)+ return Image(t, PixelFormat(cs, 32), layout)+++add(+ "image.Image.to_gray",+ g,+ lambda t: _mk_image(t).to_gray().data,+ [torch.rand(3, 16, 24)],+ note="Image container (C,H,W) float32; RGB->gray",+)+add("image.Image.to_bgr", g, lambda t: _mk_image(t).to_bgr().data, [torch.rand(3, 16, 24)])+add(+ "image.Image.to_rgb[from bgr]",+ g,+ lambda t: _mk_image(t, ColorSpace.BGR).to_rgb().data,+ [torch.rand(3, 16, 24)],+)+add("image.Image.float", g, lambda t: _mk_image(t).float().data, [torch.rand(3, 16, 24)], note="dtype no-op")+add("image.Image.from_numpy/to_numpy/write/from_file", g, None, [], skip="numpy / file IO")+add("image.ImageSize/ImageLayout/PixelFormat/ChannelsOrder", g, None, [], skip="metadata dataclasses / enums")+add(+ "image.image_to_tensor/tensor_to_image/ImageToTensor/image_list_to_tensor",+ g,+ None,+ [],+ skip="numpy <-> tensor conversion utilities (numpy input)",+)+add("image.image_to_string/print_image", g, None, [], skip="return/print strings")+add("image.perform_keep_shape_image/video", g, None, [], skip="decorators")+add(+ "image.draw_line",+ g,+ K.image.draw_line,+ [torch.zeros(3, 16, 24), torch.tensor([2, 3]), torch.tensor([20, 12]), torch.tensor([1.0, 0.5, 0.2])],+ note="per-line pixels built on the device with nonzero; int(max) of the longest line reads a tensor value",+)+add(+ "image.draw_point2d",+ g,+ K.image.draw_point2d,+ [torch.zeros(3, 16, 24), torch.tensor([[2, 3], [10, 12], [20, 5]]), torch.tensor([1.0, 0.5, 0.2])],+ note="`zip(*points)` iterates tensor rows in Python",+)+add(+ "image.draw_rectangle",+ g,+ K.image.draw_rectangle,+ [+ torch.zeros(1, 3, 16, 24),+ torch.tensor([[[2.0, 3.0, 12.0, 10.0], [5.0, 1.0, 20.0, 14.0]]]),+ torch.tensor([1.0, 0.5, 0.2]),+ ],+ note="Python loop over batch and boxes with tensor-derived slicing",+)+add(+ "image.draw_rectangle[fill]",+ g,+ K.image.draw_rectangle,+ [torch.zeros(1, 3, 16, 24), torch.tensor([[[2.0, 3.0, 12.0, 10.0]]]), torch.tensor([1.0, 0.5, 0.2])],+ {"fill": True},+)+add(+ "image.draw_convex_polygon",+ g,+ K.image.draw_convex_polygon,+ [+ torch.zeros(1, 3, 16, 24),+ torch.tensor([[[2.0, 2.0], [20.0, 4.0], [18.0, 14.0], [4.0, 12.0]]]),+ torch.tensor([[1.0, 0.5, 0.2]]),+ ],+ note="polygon rasterisation via edge functions (vectorised)",+)+add(+ "image.make_grid",+ g,+ K.image.make_grid,+ [torch.rand(6, 3, 8, 12)],+ {"n_row": 3, "padding": 2},+ note="n_row, padding baked",+)++if __name__ == "__main__":run_cases(CASES, sys.argv[1], only=sys.argv[2:] or None)diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex 139826c7a..b26bd39ae 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -28,7 +28,6 @@ from harness import case, run_casesimport kornia as Ktorch.manual_seed(0)-torch.set_num_threads(4)# ----------------------------------------------------------------------------- helpers@@ -555,7 +554,8 @@ A("models.tiny_vit",None,[],- skip="eager RuntimeError (view '[1,8,8,64]' invalid) β TinyViT hard-codes H=W=img_size in its window attention",+ skip="eager ValueError (a 64x48 input gives an 8x6 token grid; the stages are built for the 8x8 grid) β "+ "TinyViT requires H=W=img_size",))A(case("contrib.TinyViT", "contrib", None, [], skip="alias of kornia.models.tiny_vit.TinyViT (covered)"))@@ -576,7 +576,7 @@ A("models.vit",None,[],- skip="eager RuntimeError (pos-embed 17 vs 25 tokens) β VisionTransformer requires "+ skip="eager ValueError (input image shape must be Bx3x32x32) β VisionTransformer requires ""H=W=image_size (fixed pos_embed)",))@@ -773,8 +773,8 @@ A("models.vlm",None,[],- skip="eager RuntimeError (pos-embed 4 vs 6 patches) β vision tower requires H=W=image_size "- "(no pos-embed interpolation)",+ skip="eager ValueError (input images must be 32x32: the position embeddings cover that size only) β "+ "vision tower requires H=W=image_size (no pos-embed interpolation)",))A(@@ -1414,112 +1414,6 @@ A()A(case("sensors.camera.CameraModelBase/CameraModelType", "sensors.camera", None, [], skip="base class / enum"))-# ============================================================================= kornia.image-from kornia.image import ChannelsOrder, Image, ImageLayout, PixelFormat # noqa: E402-from kornia.image.base import ColorSpace # noqa: E402---def _mk_image(t: torch.Tensor, cs: ColorSpace = ColorSpace.RGB) -> Image:- layout = ImageLayout(ImageSize(t.shape[-2], t.shape[-1]), t.shape[-3], ChannelsOrder.CHANNELS_FIRST)- return Image(t, PixelFormat(cs, 32), layout)---A(- case(- "image.Image.to_gray",- "image",- lambda t: _mk_image(t).to_gray().data,- [torch.rand(3, 16, 24)],- note="Image container (C,H,W) float32; RGB->gray",- )-)-A(case("image.Image.to_bgr", "image", lambda t: _mk_image(t).to_bgr().data, [torch.rand(3, 16, 24)]))-A(- case(- "image.Image.to_rgb[from bgr]",- "image",- lambda t: _mk_image(t, ColorSpace.BGR).to_rgb().data,- [torch.rand(3, 16, 24)],- )-)-A(case("image.Image.float", "image", lambda t: _mk_image(t).float().data, [torch.rand(3, 16, 24)], note="dtype no-op"))-A(case("image.Image.from_numpy/to_numpy/write/from_file", "image", None, [], skip="numpy / file IO"))-A(case("image.ImageSize/ImageLayout/PixelFormat/ChannelsOrder", "image", None, [], skip="metadata dataclasses / enums"))-A(- case(- "image.image_to_tensor/tensor_to_image/ImageToTensor/image_list_to_tensor",- "image",- None,- [],- skip="numpy <-> tensor conversion utilities (numpy input)",- )-)-A(case("image.image_to_string/print_image", "image", None, [], skip="return/print strings"))-A(case("image.perform_keep_shape_image/video", "image", None, [], skip="decorators"))-A(- case(- "image.draw_line",- "image",- K.image.draw_line,- [torch.zeros(3, 16, 24), torch.tensor([2, 3]), torch.tensor([20, 12]), torch.tensor([1.0, 0.5, 0.2])],- note="per-line pixels built on the device with nonzero; int(max) of the longest line reads a tensor value",- )-)-A(- case(- "image.draw_point2d",- "image",- K.image.draw_point2d,- [torch.zeros(3, 16, 24), torch.tensor([[2, 3], [10, 12], [20, 5]]), torch.tensor([1.0, 0.5, 0.2])],- note="`zip(*points)` iterates tensor rows in Python",- )-)-A(- case(- "image.draw_rectangle",- "image",- K.image.draw_rectangle,- [- torch.zeros(1, 3, 16, 24),- torch.tensor([[[2.0, 3.0, 12.0, 10.0], [5.0, 1.0, 20.0, 14.0]]]),- torch.tensor([1.0, 0.5, 0.2]),- ],- note="Python loop over batch and boxes with tensor-derived slicing",- )-)-A(- case(- "image.draw_rectangle[fill]",- "image",- K.image.draw_rectangle,- [torch.zeros(1, 3, 16, 24), torch.tensor([[[2.0, 3.0, 12.0, 10.0]]]), torch.tensor([1.0, 0.5, 0.2])],- {"fill": True},- )-)-A(- case(- "image.draw_convex_polygon",- "image",- K.image.draw_convex_polygon,- [- torch.zeros(1, 3, 16, 24),- torch.tensor([[[2.0, 2.0], [20.0, 4.0], [18.0, 14.0], [4.0, 12.0]]]),- torch.tensor([[1.0, 0.5, 0.2]]),- ],- note="polygon rasterisation via edge functions (vectorised)",- )-)-A(- case(- "image.make_grid",- "image",- K.image.make_grid,- [torch.rand(6, 3, 8, 12)],- {"n_row": 3, "padding": 2},- note="n_row, padding baked",- )-)-# ============================================================================= heavy SAM encoders lastA(case(diff --git a/docs/export_support/harness.py b/docs/export_support/harness.pyindex 72f6eacb6..1968240e2 100644--- a/docs/export_support/harness.py+++ b/docs/export_support/harness.py@@ -23,11 +23,17 @@ tensor inputs. Every tensor input becomes an ONNX graph input; Python-only kwargthe graph. The harness:1. runs the target eagerly (reference),- 2. exports with ``torch.onnx.export(dynamo=True, opset_version=18)``,+ 2. exports with ``torch.onnx.export(dynamo=True, opset_version=18)`` (or, with ``dynamo=False``, the legacy+ TorchScript exporter at its highest opset up to 18),3. runs ``onnx.checker.check_model`` (full check),- 4. runs the graph in onnxruntime (CPU) and compares every tensor output against the reference,+ 4. runs the graph in onnxruntime (CPU) and compares every tensor output against the reference: the same dtype,+ and the values within the case's ``atol`` / ``rtol``,5. records op types, size, wall time and (on failure) the root-cause error.+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.+Usage from a registry file::from harness import case, run_cases@@ -35,13 +41,15 @@ Usage from a registry file::if __name__ == "__main__":run_cases(CASES, sys.argv[1], only=sys.argv[2:] or None)-Statuses: ok | ok-unverified (check=False, nondeterministic op) | eager-fail | export-fail |-checker-fail | ort-load-fail | ort-run-fail | mismatch | no-tensor-output | skipped.+Statuses: ok | ok-unverified (check=False, nondeterministic op: output count, shapes and finiteness checked) |+eager-fail | export-fail | checker-fail | ort-load-fail | ort-run-fail | mismatch | no-tensor-output | skipped."""from __future__ import annotations+import contextlibimport copy+import inspectimport ioimport jsonimport logging@@ -59,12 +67,16 @@ import torchfrom torch import nnfrom torch.utils._pytree import tree_flatten-logging.disable(logging.CRITICAL)-warnings.filterwarnings("ignore")-ort.set_default_logger_severity(3)-torch.set_num_threads(4)-SEED = 1234+OPSET = 18 # the opset the dynamo export requests, and the ceiling of the legacy one+++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)+ torch.set_num_threads(4)def case(@@ -162,7 +174,8 @@ def make_wrapper(target: Any, kwargs: dict[str, Any], n_inputs: int, method: strreturn tuple(outs)Wrap.forward = ns["forward"]- return Wrap()+ # in eval mode: the legacy exporter puts the wrapper back into the mode it found, children included+ return Wrap().eval()# ----------------------------------------------------------------------------- utilities@@ -176,9 +189,12 @@ def to_np(x: torch.Tensor) -> np.ndarray: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)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 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"@@ -198,6 +214,22 @@ def close(a: np.ndarray, b: np.ndarray, atol: float, rtol: float) -> tuple[bool,)+def shape_and_finite(ref: list[torch.Tensor], out: list[Any]) -> str | None:+ """Why ``out`` cannot stand in for ``ref``: another output count or shape, or a non-finite value; else None.++ The check of a random operator, whose values cannot be compared with an eager run.+ """+ if len(out) != len(ref):+ return f"{len(out)} outputs vs {len(ref)}"+ for i, (a, b) in enumerate(zip(ref, out)):+ b = to_np(b) if isinstance(b, torch.Tensor) else np.asarray(b)+ if tuple(a.shape) != tuple(b.shape):+ return f"out{i}: shape {tuple(b.shape)} vs {tuple(a.shape)}"+ if np.issubdtype(b.dtype, np.floating) and not np.isfinite(b).all():+ return f"out{i}: non-finite values"+ return None++def op_types(model: onnx.ModelProto) -> list[str]:s: set[str] = set()@@ -254,29 +286,48 @@ def _kornia_frames(e: BaseException) -> list[str]:return res[-6:]-def export(m: nn.Module, inputs: list[torch.Tensor]) -> onnx.ModelProto:- import contextlib+def legacy_opset() -> int:+ """The opset a legacy (TorchScript) export requests: the highest that exporter has on this torch, at most OPSET."""+ from torch.onnx import _constants++ return min(OPSET, getattr(_constants, "ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET", _constants.ONNX_MAX_OPSET))++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."""buf = io.BytesIO()+ if dynamo:+ kwargs: dict[str, Any] = {+ "dynamo": True,+ "opset_version": OPSET,+ "verbose": False,+ "report": False,+ "optimize": os.environ.get("KORNIA_SURVEY_OPTIMIZE", "1") == "1",+ }+ else:+ kwargs = {+ "dynamo": False,+ "opset_version": legacy_opset(),+ "verbose": False,+ "input_names": [f"in{i}" for i in range(len(inputs))],+ }+ # an older torch.onnx.export lacks some of these keywords (``optimize`` arrived in torch 2.6)+ accepted = inspect.signature(torch.onnx.export).parameters+ kwargs = {k: v for k, v in kwargs.items() if k in accepted}# dynamo prints the whole FX graph on data-dependent failures; keep the survey log readablewith torch.no_grad(), open(os.devnull, "w") as dn, contextlib.redirect_stdout(dn), contextlib.redirect_stderr(dn):- prog = torch.onnx.export(- m,- tuple(inputs),- dynamo=True,- opset_version=18,- verbose=False,- report=False,- optimize=os.environ.get("KORNIA_SURVEY_OPTIMIZE", "1") == "1",- )- prog.save(buf)+ if dynamo:+ torch.onnx.export(m, tuple(inputs), **kwargs).save(buf)+ else:+ torch.onnx.export(m, tuple(inputs), buf, **kwargs)return onnx.load_from_string(buf.getvalue())# ----------------------------------------------------------------------------- runner-def run_case(c: dict[str, Any]) -> dict[str, Any]:+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."""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"]]@@ -302,7 +353,9 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:return rectry:torch.manual_seed(SEED)- model = export(wrap, inputs)+ # 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)except Exception as e:rec.update(status="export-fail",@@ -353,7 +406,11 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:rec.update(status="ort-run-fail", error=err_str(e), error_full=err_full(e))return recif not c["check"]:- rec["status"] = "ok-unverified"+ why = shape_and_finite(list(ref), outs)+ if why is None:+ rec["status"] = "ok-unverified"+ else:+ rec.update(status="mismatch", error=why)return recif len(outs) != len(ref):rec.update(status="mismatch", error=f"{len(outs)} ORT outputs vs {len(ref)} torch outputs")@@ -423,6 +480,7 @@ def prepare_resume(cases: list[dict[str, Any]], out_json: str) -> dict[str, dictdef run_cases(cases: list[dict[str, Any]], out_json: str, only: list[str] | None = None, resume: bool = True) -> None:+ configure_survey_process()names = [c["name"] for c in cases]dup = {n for n in names if names.count(n) > 1}if dup:diff --git a/docs/export_support/probe_compile.py b/docs/export_support/probe_compile.pyindex b1a8a0418..f7666c8cc 100644--- a/docs/export_support/probe_compile.py+++ b/docs/export_support/probe_compile.py@@ -38,12 +38,19 @@ from typing import Anyimport torchimport torch._dynamo-from harness import SEED, _kornia_frames, close, err_str, make_wrapper, prepare_resume, to_np+from harness import (+ SEED,+ _kornia_frames,+ close,+ configure_survey_process,+ err_str,+ make_wrapper,+ prepare_resume,+ shape_and_finite,+ to_np,+)from torch import nn-torch.set_num_threads(4)-torch._dynamo.config.cache_size_limit = 64-torch._dynamo.config.suppress_errors = FalseTIMEOUT = 420@@ -96,17 +103,6 @@ def _compare(ref: list[torch.Tensor], out: list[torch.Tensor], c: dict[str, Any]return "; ".join(bad)[:400] if bad else None-def _finite(out: list[torch.Tensor], ref: list[torch.Tensor]) -> str | None:- if len(out) != len(ref):- return f"{len(out)} outputs vs {len(ref)}"- for i, (a, b) in enumerate(zip(ref, out)):- if tuple(a.shape) != tuple(b.shape):- return f"out{i}: shape {tuple(b.shape)} vs {tuple(a.shape)}"- if b.is_floating_point() and not torch.isfinite(b).all():- return f"out{i}: non-finite values"- return None--def run_case(c: dict[str, Any]) -> dict[str, Any]:rec: dict[str, Any] = {"name": c["name"],@@ -168,7 +164,7 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:with torch.no_grad():out = list(compiled(*copy.deepcopy(inputs)))if not c["check"]:- why = _finite(out, ref)+ why = shape_and_finite(ref, out)rec["compile"] = "ok-unverified" if why is None else "mismatch"else:why = _compare(ref, out, c)@@ -187,6 +183,9 @@ def run_case(c: dict[str, Any]) -> dict[str, Any]:def main() -> None:+ configure_survey_process()+ torch._dynamo.config.cache_size_limit = 64+ torch._dynamo.config.suppress_errors = Falsemod = importlib.import_module(sys.argv[1])out_json = sys.argv[2]only = sys.argv[3:] or Nonediff --git a/docs/export_support/run.py b/docs/export_support/run.pyindex 95ee50327..ee5b774c6 100644--- a/docs/export_support/run.py+++ b/docs/export_support/run.py@@ -37,6 +37,7 @@ committed and rendered by ``docs/generate_export_support.py`` at docs build timefrom __future__ import annotations+import argparseimport subprocessimport sysfrom concurrent.futures import ThreadPoolExecutor@@ -76,12 +77,16 @@ def _worker(label: str, cmd: list[str]) -> tuple[str, int]:def main(argv: list[str]) -> int:- merge_only = "--merge-only" in argv- force = "--force" in argv- groups = [a for a in argv if not a.startswith("--")] or GROUPS- unknown = sorted(set(groups) - set(GROUPS))+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("groups", nargs="*", metavar="group", help=f"case groups to probe (default: all of {GROUPS})")+ parser.add_argument("--merge-only", action="store_true", help="re-merge existing results into the JSON")+ parser.add_argument("--force", action="store_true", help="merge even if the results are incomplete")+ args = parser.parse_args(argv)+ unknown = sorted(set(args.groups) - set(GROUPS))if unknown:- sys.exit(f"unknown case group(s) {unknown}; choose from {GROUPS}")+ parser.error(f"unknown case group(s) {unknown}; choose from {GROUPS}")+ merge_only, force = args.merge_only, args.force+ groups = args.groups or GROUPSRESULTS.mkdir(exist_ok=True)if not merge_only:diff --git a/kornia/color/yuv.py b/kornia/color/yuv.pyindex 825b05f8e..ca0b81de9 100644--- a/kornia/color/yuv.py+++ b/kornia/color/yuv.py@@ -160,8 +160,11 @@ def rgb_to_yuv422(image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:raise ShapeError(f"Input W must be evenly divisible by 2. Got {image.shape}")yuvimage = rgb_to_yuv(image)+ uv = yuvimage[..., 1:3, :, :]- return (yuvimage[..., :1, :, :], yuvimage[..., 1:3, :, :].unfold(-1, 2, 2).mean(-1))+ # The width axis by its positive index: the legacy (TorchScript) ONNX exporter lowers ``unfold(-1, ...)`` with+ # the window and the window-count axes swapped, which gives UV planes of shape (*, 2, H, 2).+ return (yuvimage[..., :1, :, :], uv.unfold(uv.dim() - 1, 2, 2).mean(-1))def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:diff --git a/pyproject.toml b/pyproject.tomlindex 66ef2a4a2..56aac8944 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -174,6 +174,7 @@ filterwarnings = [markers = ["device_agnostic: run CPU-only test logic once in a CPU-containing device matrix","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","tf32: mark a test as sensitive to TF32 (TensorFloat-32) CUDA matmul precision; xfail by default, run with --tf32 to activate",]diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.14.txt b/testing/known_failure_xfails/onnx_conformance_torch2.14.txtnew file mode 100644index 000000000..0f3da54df--- /dev/null+++ b/testing/known_failure_xfails/onnx_conformance_torch2.14.txt@@ -0,0 +1,16 @@+# Strict known-failure baseline of tests/onnx/test_conformance.py on torch 2.14.0 (CPU float32, Python 3.11, the+# locked onnx / onnxruntime / onnxscript): promised operators that do not export with the dynamo exporter and match+# eager, or whose legacy export succeeds with a wrong result (#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>+# #6164: the legacy exporter traces the CPU loop of Boxes.to_mask / Boxes3D.to_mask and writes a+# constant all-zero mask with no graph input.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes.to_mask]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes3D.to_mask]+# #6165: the legacy exporter gives torch.log10 of a 0-d tensor the shape (1,), so the PSNR graphs+# return (1,) instead of a scalar.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.PSNRLoss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.psnr_loss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[metrics.psnr]diff --git a/testing/known_failure_xfails/onnx_conformance_torch2.9.txt b/testing/known_failure_xfails/onnx_conformance_torch2.9.txtnew file mode 100644index 000000000..2154779f6--- /dev/null+++ b/testing/known_failure_xfails/onnx_conformance_torch2.9.txt@@ -0,0 +1,24 @@+# Strict known-failure baseline of tests/onnx/test_conformance.py on torch 2.9.1 (CPU float32, Python 3.11, the+# locked onnx / onnxruntime / onnxscript): promised operators that do not export with the dynamo exporter and match+# eager, or whose legacy export succeeds with a wrong result (#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>+# #6166: since #5416 the annotation handlers of a container recompute the child's+# matrix from the replayed params under export, and torch 2.9.1's exporter rejects the graph ("Key '..._lifted_tensor_N'+# does not match the name of the value 'copy_M'"); torch 2.14 exports them.+AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[AugmentationSequential[bbox_xyxy]]+AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[AugmentationSequential[keypoints]]+AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[AugmentationSequential[mask]]+AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[ManyToManyAugmentationDispather]+AssertionError tests/onnx/test_conformance.py::test_export_matches_eager[ManyToOneAugmentationDispather]+# #6164: the legacy exporter traces the CPU loop of Boxes.to_mask / Boxes3D.to_mask and writes a+# constant all-zero mask with no graph input.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes.to_mask]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[boxes.Boxes3D.to_mask]+# #6165: the legacy exporter gives torch.log10 of a 0-d tensor the shape (1,), so the PSNR graphs+# return (1,) instead of a scalar.+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.PSNRLoss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[losses.psnr_loss]+AssertionError tests/onnx/test_conformance.py::test_legacy_export_is_not_wrong[metrics.psnr]diff --git a/testing/onnx_conformance.py b/testing/onnx_conformance.pynew file mode 100644index 000000000..fd29769cc--- /dev/null+++ b/testing/onnx_conformance.py@@ -0,0 +1,344 @@+# 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/onnx/test_conformance.py b/tests/onnx/test_conformance.pynew file mode 100644index 000000000..b2c9319a0--- /dev/null+++ b/tests/onnx/test_conformance.py@@ -0,0 +1,173 @@+# 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.+#++"""ONNX conformance of the promised operators (#5819).++Every promised case (see ``testing/onnx_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.+"""++from __future__ import annotations++import logging+import warnings++import pytest+import torch++from testing.onnx_conformance import (+ LEGACY_PASSES,+ OPTION,+ describe,+ import_survey_module,+ parse_selection,+ pretrained_cases,+ promised_cases,+ promised_digest,+ registration_hooks,+ registries_of,+ registry_cases,+ run_case,+ selected_cases,+)++# 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+# generator, so restore_torch_rng puts the accelerator generators back.+pytestmark = [pytest.mark.device_agnostic, pytest.mark.usefixtures("restore_torch_rng")]++# The exporters warn at length about every graph; the per-case tests keep the session output readable. Not module-wide:+# test_survey_harness_leaves_process_state_alone must see a filter the harness would add.+quiet = pytest.mark.filterwarnings("ignore")++pytest.importorskip("onnx")+pytest.importorskip("onnxruntime")+pytest.importorskip("onnxscript") # the dynamo exporter hard-requires it++# The promised set of the 2026-09-02 snapshot: 848 cases of 643 operators.+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++[email protected]_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)++[email protected]_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)++[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."""+ 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)}")+ 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"))]+++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(),+ }+++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()+ 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"}++ 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()+ 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")}diff --git a/tests/scripts/test_onnx_conformance_packages.py b/tests/scripts/test_onnx_conformance_packages.pynew file mode 100644index 000000000..16c627096--- /dev/null+++ b/tests/scripts/test_onnx_conformance_packages.py@@ -0,0 +1,185 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import re+import subprocess+import sys+from pathlib import Path++import pytest++from testing import onnx_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++REPO = Path(__file__).parent.parent.parent+SCRIPT = REPO / ".github" / "scripts" / "onnx_conformance_packages.py"++pytestmark = pytest.mark.device_agnostic+++def _selected(paths):+ result = select(paths)+ return set(result.split(",")) if result else set()+++ "changed",+ [+ ["kornia/core/check.py"],+ ["kornia/utils/helpers.py"],+ ["kornia/onnx/sequential.py"],+ ["kornia/__init__.py"],+ ["kornia/constants.py"],+ ["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"],+ [".github/workflows/pr_test_cpu.yml"],+ ["uv.lock"],+ ["pixi.toml"],+ ["pyproject.toml"],+ ["conftest.py"],+ ],+)+def test_select_all(changed):+ assert select(changed) == "all"+++ "changed",+ [+ ["docs/source/get-started/onnx.rst", "README.md"],+ ["tests/geometry/test_homography.py"],+ ["kornia/contrib/face_detection.py", "kornia/models/sam/model.py"],+ ["kornia/x/trainer.py"],+ [],+ ],+)+def test_select_nothing(changed):+ assert select(changed) == ""+++def test_select_follows_importers_in_the_repository():+ # 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"}+ # 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"}+++def _write(root, files):+ for path, text in files.items():+ target = root / path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(text)+++def test_select_resolves_each_import_form(tmp_path):+ _write(+ tmp_path,+ {+ "kornia/__init__.py": "from . import augmentation, color, contrib, feature, filters, geometry, losses\n",+ "kornia/metrics/__init__.py": "from .psnr import psnr\n",+ "kornia/metrics/psnr.py": "def psnr(): ...\n",+ "kornia/losses/__init__.py": "",+ "kornia/losses/psnr.py": "from kornia import metrics\n", # a submodule imported from its package+ "kornia/color/__init__.py": "",+ "kornia/color/hsv.py": "def rgb_to_hsv(): ...\n",+ "kornia/augmentation/__init__.py": "",+ "kornia/augmentation/aug.py": "import kornia\n\nf = kornia.color.hsv.rgb_to_hsv\n", # attribute chain+ "kornia/geometry/__init__.py": "",+ "kornia/geometry/y.py": "def g(): ...\n",+ "kornia/feature/__init__.py": "",+ "kornia/feature/x.py": "def f():\n from ..geometry.y import g\n", # relative, function-local+ "kornia/contrib/__init__.py": "",+ "kornia/contrib/c.py": "",+ "kornia/models/__init__.py": "",+ "kornia/models/dex.py": "class N: ...\n",+ "kornia/models/sam.py": "",+ "kornia/filters/__init__.py": "",+ "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+++def test_select_follows_importers_of_a_deleted_nested_module(tmp_path):+ # The importers of a deleted module still import it; their imports resolve to the nearest module that survives,+ # not to the package's ``__init__``.+ _write(+ tmp_path,+ {+ "kornia/__init__.py": "",+ "kornia/geometry/__init__.py": "",+ "kornia/geometry/transform/__init__.py": "",+ "kornia/geometry/transform/kept.py": "",+ "kornia/feature/__init__.py": "",+ "kornia/feature/uses.py": "from kornia.geometry.transform.removed import warp\n",+ },+ )+ assert select(["kornia/geometry/transform/removed.py"], tmp_path) == "geometry,feature"+++ "stdin",+ [+ "kornia/morphology/morphology.py\nkornia/x/trainer.py\n", # git diff --name-only+ "kornia/morphology/morphology.py kornia/x/trainer.py\n", # echo a b+ ],+)+def test_cli_reads_stdin(stdin):+ result = subprocess.run( # noqa: S603 -- the current test interpreter on the script under test.+ [sys.executable, str(SCRIPT)],+ input=stdin,+ capture_output=True,+ text=True,+ check=True,+ )+ assert result.stdout == "morphology\n"+++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)],+ input="kornia/morphology/morphology.py kornia/core/check.py\n",+ capture_output=True,+ text=True,+ check=True,+ )+ assert result.stdout == "all\n"+++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)+ 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)