Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs: the ONNX and torch.compile support statement, rendered from the conformance tests (#5819); nms and draw_rectangle leave the compile promise (#6194) (#6233)

Dmytro Mishkin6bb63bac1b48
diff --git a/.github/scripts/conformance_packages.py b/.github/scripts/conformance_packages.py
index badba565c..b83f04095 100755
--- a/.github/scripts/conformance_packages.py
+++ b/.github/scripts/conformance_packages.py
@@ -54,7 +54,7 @@ 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/conformance.py, which
+# The stable core of docs/source/get-started/stability.rst; the same tuple as testing/conformance_promise.py, which
# tests/scripts/test_conformance_packages.py checks.
STABLE_CORE = (
"geometry",
@@ -90,7 +90,7 @@ ALL_FILES = (
"pyproject.toml",
"uv.lock",
)
-# Each promise's own test, by the snapshot field it promises (testing/conformance.py PROMISES).
+# Each promise's own test, by the snapshot field it promises (testing/conformance_promise.py PROMISES).
TEST_FILES = {
"onnx": "tests/onnx/test_conformance.py",
"compile": "tests/test_inductor_conformance.py",
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index a46423f68..72fb692d4 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -5,6 +5,9 @@ on:
- 'docs/**'
- '*.rst'
- '.github/workflows/docs.yml'
+ # the support statement of the export-support page is rendered from the conformance promise and its manifests
+ - 'testing/conformance_promise.py'
+ - 'testing/known_failure_xfails/*_conformance_*.txt'
workflow_call:
inputs:
python-version:
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index 5f6effef4..2237e80b4 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -47,7 +47,16 @@ jobs:
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
+ # The export survey, its snapshot, the support-statement generator and the stability page live under docs/,
+ # but tests/test_generate_export_support.py in the ordinary test suite checks them against the promise (#5819).
+ promise_docs='^(docs/export_support/|docs/generate_export_support\.py$|'
+ promise_docs+='docs/source/_data/export_support\.json$|docs/source/get-started/stability\.rst$)'
+ promise_status=0
+ grep -Eq "$promise_docs" <<< "$changed" || promise_status=$?
+ if [[ "$promise_status" -gt 1 ]]; then
+ exit "$promise_status"
+ fi
+ if [[ "$promise_status" -eq 0 ]] || grep -Eqv '^(docs/|.*\.md$|LICENSE$|COPYRIGHT$)' <<< "$changed"; then
echo "run-tests=true" >> "$GITHUB_OUTPUT"
else
# Must stay the first command here: it captures the `if` condition's
diff --git a/.github/workflows/scheduled_test_cpu.yml b/.github/workflows/scheduled_test_cpu.yml
index 8ce79694a..88d3cfca0 100644
--- a/.github/workflows/scheduled_test_cpu.yml
+++ b/.github/workflows/scheduled_test_cpu.yml
@@ -100,10 +100,12 @@ jobs:
CHANGED_FILES=$(git diff --name-only "$PREV_SHA" HEAD)
# 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).
+ # live under docs/ but define what the ONNX and compile conformance jobs check (#5819), and the
+ # support-statement generator renders the promise that tests/test_generate_export_support.py checks.
SHOULD_SKIP="true"
for file in $CHANGED_FILES; do
if [[ "$file" =~ ^docs/export_support/ ]] || \
+ [[ "$file" == "docs/generate_export_support.py" ]] || \
[[ "$file" == "docs/source/_data/export_support.json" ]] || \
[[ "$file" == "docs/source/get-started/stability.rst" ]]; then
SHOULD_SKIP="false"
diff --git a/AGENTS.md b/AGENTS.md
index 83d57108d..5342a6767 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -59,7 +59,7 @@ Supported fixtures include CPU, CUDA, MPS, and TPU when available, and `float16`
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.
+The stable-core operators the survey records as compiling in one graph and matching eager, less the exclusions in `testing/conformance_promise.py`, 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
diff --git a/TESTING.md b/TESTING.md
index 4e9d920be..8ee7b9376 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -79,12 +79,17 @@ The `device` and `dtype` fixtures are injected automatically from the CLI option
`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.
+or listed in `EXCLUDED` -- 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 or an exclusion leaves nothing out.
+
+The promise itself -- the promised cases, `EXCLUDED` with the reason for each exclusion, `ENFORCED_TORCH_RELEASES` and
+the reading of the manifests -- is `testing/conformance_promise.py`, which imports no pytest: the docs build renders
+the support statement of the export-support page ("What Kornia promises") from it, and `testing/conformance.py` runs
+it as tests.
```bash
pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=all
@@ -100,22 +105,28 @@ 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. 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.
+a comment that opens with its tracking issue (`# #NNNN: why`, or `# owner/repo#NNNN ...` upstream; a comment naming no
+issue after an entry or a blank line starts a block without one); loading a manifest rejects an entry without one, and
+the support statement lists each entry with that 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`.
+with compile status `ok` in a stable-core package, without anything built from pretrained weights or listed in
+`EXCLUDED`, 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). The survey records `ok` only for a case that
+`fullgraph=True` compiles and that matches eager (#6194). `EXCLUDED` lists the snapshot's `ok` cases the promise leaves
+out, each with its reason; an exclusion must name a case the promise would cover without it, so a snapshot
+regeneration that drops one fails `test_promised_set_is_pinned` until its entry is deleted. 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.
```bash
pixi run test-module tests/test_inductor_conformance.py --compile-conformance=all
diff --git a/changelog.d/6233.added.md b/changelog.d/6233.added.md
new file mode 100644
index 000000000..976d04bad
--- /dev/null
+++ b/changelog.d/6233.added.md
@@ -0,0 +1,6 @@
+The ONNX, torch.compile and torch.export page now opens with "What Kornia promises": the stable-core configurations
+that export with the dynamo ONNX exporter at opset 18 and match eager in onnxruntime, and the ones that compile with
+`torch.compile(..., fullgraph=True)` and match eager, for inference at static shapes, checked in CI on torch 2.9 and
+2.14, with the configurations left out, the known failures and their tracking issues; the survey tables mark every
+promised configuration. `nms` and `draw_rectangle` document how `torch.compile` handles them, and are left out of the
+compile promise (#6194).
diff --git a/conftest.py b/conftest.py
index 47d9c3c45..86ab5e673 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 conformance
+from testing import conformance, conformance_promise
from testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reason
from testing.half_precision_ci import (
FailureRecorder,
@@ -289,7 +289,7 @@ 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."""
config._conformance = {}
- for promise in conformance.PROMISES:
+ for promise in conformance_promise.PROMISES:
try:
config._conformance[promise.marker] = conformance.selection(config, promise)
except ValueError as error:
@@ -438,7 +438,7 @@ def pytest_collection_modifyitems(config, items):
# 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:
+ for promise in conformance_promise.PROMISES:
if config._conformance[promise.marker]:
continue
conformance_items = [item for item in items if item.get_closest_marker(promise.marker) is not None]
@@ -599,7 +599,7 @@ def pytest_addoption(parser):
"(env: KORNIA_TEST_RUN_MPS_PROCESS_ABORT)"
),
)
- for promise in conformance.PROMISES:
+ for promise in conformance_promise.PROMISES:
parser.addoption(
promise.option,
action="store",
diff --git a/docs/export_support/README.md b/docs/export_support/README.md
index ea9b05dee..e476b865a 100644
--- a/docs/export_support/README.md
+++ b/docs/export_support/README.md
@@ -1,9 +1,11 @@
-# Graph-capture survey behind the survey page
+# Graph-capture survey behind the support page
-The [ONNX, torch.compile and torch.export survey](../source/get-started/index.rst) page of the
-documentation is rendered from `docs/source/_data/export_support.json`, a committed snapshot of
-what this directory measures. The page itself is generated at docs build time by
-`docs/generate_export_support.py`; nothing here runs during a docs build.
+The survey of the [ONNX, torch.compile and torch.export support](../source/get-started/index.rst) page
+of the documentation is rendered from `docs/source/_data/export_support.json`, a committed snapshot of
+what this directory measures; the page's support statement ("What Kornia promises") is rendered from
+`testing/conformance_promise.py`, the promise the conformance tests check. The page itself is
+generated at docs build time by `docs/generate_export_support.py`; nothing here runs during a docs
+build.
## What is measured
@@ -24,22 +26,27 @@ For each case:
- **ONNX** (`harness.py`): `torch.onnx.export(dynamo=True, opset_version=18)`, `onnx.checker`,
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. 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`.
+ `torch.compile(..., fullgraph=True)` compared against eager: `ok` means one graph that matches.
+ A case `fullgraph=True` refuses gets `torch._dynamo.explain`'s graph-break count and a default
+ `torch.compile` run compared against eager (`ok-breaks` when it matches). An explain count of 0 is
+ no proof of a single graph (Dynamo can run part or all of a frame eagerly without recording a
+ break; #6194), so such a case is `ok-breaks` with no break counted and the refusal as its reason.
+ 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.
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 right shape. Under `torch.compile` that does not mean one graph: a random case `fullgraph=True`
+refuses is compiled like the rest, with graph breaks, and nothing promises an *ok-unverified* case.
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`,
+in a stable-core package, not tagged `pretrained` and not excluded (`EXCLUDED` in
+`testing/conformance_promise.py`, with the reason), 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
+that import them. Renaming, skipping or dropping a promised case therefore fails those tests, and so
+does an exclusion whose case a regenerated snapshot no longer records as "ok" (delete the entry). 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.
diff --git a/docs/export_support/merge.py b/docs/export_support/merge.py
index bce8b7a1f..6e8e8c596 100644
--- a/docs/export_support/merge.py
+++ b/docs/export_support/merge.py
@@ -181,7 +181,9 @@ def _norm_compile(c: dict | None) -> tuple[str, int, str]:
why = ""
if reasons:
why = _reason("", str(reasons[0])) or str(reasons[0]).split("\n")[0]
- return "ok-breaks", breaks, f"{breaks} graph break{'s' if breaks != 1 else ''}: {why}".rstrip(": ")
+ # 0 breaks: explain records none, but torch.compile(..., fullgraph=True) refused the case (#6194)
+ lead = f"{breaks} graph break{'s' if breaks != 1 else ''}" if breaks else "not captured in one graph"
+ return "ok-breaks", breaks, f"{lead}: {why}".rstrip(": ")
if s == "ok-unverified":
return (
"ok-unverified",
diff --git a/docs/export_support/probe_compile.py b/docs/export_support/probe_compile.py
index 43862c510..78622c0f6 100644
--- a/docs/export_support/probe_compile.py
+++ b/docs/export_support/probe_compile.py
@@ -22,7 +22,8 @@ Usage: python probe_compile.py <cases_module> <out.json> [names...]
Per case records:
export: ok | fail | eager-fail | skipped (torch.export.export, non-strict default)
compile: ok | ok-breaks:N | ok-unverified | mismatch | fail | eager-fail | skipped
- (torch.compile default inductor backend, fullgraph=False; N = dynamo graph breaks)
+ (torch.compile, default inductor backend: ok only for one graph, fullgraph=True; a case fullgraph=True
+ refuses is compiled with fullgraph=False, N = the graph breaks torch._dynamo.explain counts)
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)``,
@@ -142,39 +143,58 @@ def export_step(wrap: nn.Module, inputs: list[torch.Tensor]) -> dict[str, Any]:
return rec
+def _compiled_outputs(wrap: nn.Module, inputs: list[torch.Tensor], fullgraph: bool) -> list[torch.Tensor]:
+ compiled = torch.compile(copy.deepcopy(wrap), fullgraph=fullgraph)
+ torch.manual_seed(SEED)
+ with torch.no_grad():
+ return list(compiled(*copy.deepcopy(inputs)))
+
+
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.
- 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.
+ A case is ``ok`` only when ``torch.compile(..., fullgraph=True)`` captures it in one graph and the result matches
+ eager: ``torch._dynamo.explain`` can count no graph break for a call Dynamo runs partly or wholly in Python (#6194).
+ With ``fullgraph=True`` (the conformance test) that compile is the whole step, and a graph break fails the case.
+ The survey (``fullgraph=False``) goes on for a case ``fullgraph=True`` refuses: explain counts its graph breaks
+ and a default ``torch.compile`` is compared with eager, ``ok-breaks:N`` when it matches (``N`` may be 0, the
+ refusal then being the recorded break reason). Dynamo is reset before and after each compile.
"""
- rec: dict[str, Any] = {}
+ rec: dict[str, Any] = {"graph_breaks": 0}
t1 = time.time()
_set_alarm(TIMEOUT)
try:
torch._dynamo.reset()
- breaks = 0
- if not fullgraph:
+ refusal: Exception | None = None
+ try:
+ out = _compiled_outputs(wrap, inputs, fullgraph=True)
+ except Timeout:
+ raise
+ except Exception as e: # not BaseException: a test's outcome (pytest-timeout) ends the run
+ if fullgraph:
+ raise
+ refusal = e
+ # outside the except block, so that a failure below is not reported as the refusal it would be chained to
+ if refusal is not None:
+ torch._dynamo.reset()
torch.manual_seed(SEED)
with torch.no_grad():
ex = torch._dynamo.explain(copy.deepcopy(wrap))(*copy.deepcopy(inputs))
- breaks = int(ex.graph_break_count)
+ # explain counts -1 when Dynamo captures no graph at all and runs the whole call in Python
+ rec["graph_breaks"] = max(int(ex.graph_break_count), 0)
+ reasons = sorted({str(r.reason)[:160] for r in ex.break_reasons})[:5]
+ rec["break_reasons"] = reasons or [f"fullgraph=True: {err_str(refusal)}"[:160]]
torch._dynamo.reset()
- rec["graph_breaks"] = breaks
- if breaks:
- rec["break_reasons"] = sorted({str(r.reason)[:160] for r in ex.break_reasons})[:5]
- compiled = torch.compile(copy.deepcopy(wrap), fullgraph=fullgraph)
- torch.manual_seed(SEED)
- with torch.no_grad():
- out = list(compiled(*copy.deepcopy(inputs)))
+ out = _compiled_outputs(wrap, inputs, fullgraph=False)
if not c["check"]:
why = shape_and_finite(ref, out)
rec["compile"] = "ok-unverified" if why is None else "mismatch"
else:
why = _compare(ref, out, c)
- rec["compile"] = ("ok" if breaks == 0 else f"ok-breaks:{breaks}") if why is None else "mismatch"
+ ok = "ok" if refusal is None else f"ok-breaks:{rec['graph_breaks']}"
+ rec["compile"] = ok if why is None else "mismatch"
if why:
rec["compile_error"] = why
except Exception as e: # the survey's own Timeout is one; a pytest outcome or KeyboardInterrupt is not
diff --git a/docs/generate_export_support.py b/docs/generate_export_support.py
index e1ce24bd8..07bebdeb0 100644
--- a/docs/generate_export_support.py
+++ b/docs/generate_export_support.py
@@ -15,25 +15,36 @@
# limitations under the License.
#
-"""Render docs/source/get-started/export-support.rst from docs/source/_data/export_support.json.
+"""Render docs/source/get-started/export-support.rst: kornia's ONNX and torch.compile promise, then the survey.
-The JSON is a committed snapshot of the graph-capture survey in ``docs/export_support/``: every public
-operator, model and augmentation probed with the dynamo ONNX exporter, ``torch.export`` and
-``torch.compile``. Refresh it with ``python docs/export_support/run.py`` (see that package's README)
-and commit the result; this module turns it into the survey page at docs-build time, the same way
+The promise (#5819) comes from ``testing/conformance_promise.py``, the same computation the conformance tests check:
+the promised configurations, the ones left out and why, the enforced torch releases and the known failures of each.
+
+The survey comes from ``docs/source/_data/export_support.json``, a committed snapshot of the graph-capture survey in
+``docs/export_support/``: every public operator, model and augmentation probed with the dynamo ONNX exporter,
+``torch.export`` and ``torch.compile``. Refresh it with ``python docs/export_support/run.py`` (see that package's
+README) and commit the result; this module turns both into the page at docs-build time, the same way
``generate_adoption.py`` renders the Adoption page.
"""
from __future__ import annotations
+import importlib.util
import json
+import re
+import sys
from collections import Counter, defaultdict
from pathlib import Path
+from types import ModuleType
REPO = Path(__file__).resolve().parents[1]
DATA = REPO / "docs" / "source" / "_data" / "export_support.json"
OUT = REPO / "docs" / "source" / "get-started" / "export-support.rst"
+# A one-time measurement, not re-checked by CI (#5819): the ONNX configurations promised that day, exported with the
+# dynamo exporter on torch 2.5.1, where to_onnx keeps the legacy exporter by default.
+TORCH_25_DYNAMO_ONNX = {"date": "2026-10-20", "torch": "2.5.1", "passed": 801, "promised": 848}
+
# Display order of the major packages; anything else follows alphabetically.
PACKAGE_ORDER = [
"kornia.color",
@@ -104,12 +115,15 @@ STATUS = {
"ok-breaks": (
"compat-ok-breaks",
"yes, graph breaks",
- "compiles and matches eager, but dynamo falls back to Python at one or more graph breaks",
+ "compiles and matches eager, but not in one graph: Dynamo falls back to Python at graph breaks",
),
"ok-unverified": (
"compat-ok-random",
"yes (random)",
- "captured and ran; a random operator, so only output shape and finiteness are compared",
+ (
+ "ran: the exported graph in onnxruntime, or the compiled call, which may have graph breaks; a random"
+ " operator, so only output shape and finiteness are compared"
+ ),
),
"mismatch": ("compat-mismatch", "mismatch", "captured and ran, but the result differs from eager execution"),
"fail": ("compat-fail", "no", "capture or conversion failed; the Details column says why"),
@@ -122,6 +136,46 @@ STATUS = {
SUPPORTED = {"ok", "ok-breaks", "ok-unverified"}
+# The marker of a promised configuration in the survey tables.
+PROMISED_ROLE = "kornia-promised"
+
+
+def promise_module() -> ModuleType:
+ """``testing/conformance_promise.py`` of this checkout: the promise the conformance tests check.
+
+ Loaded from its file rather than imported: ``testing`` is not part of the installed package, ``conf.py`` runs this
+ generator before it puts the repository root on ``sys.path``, and an editable install can put another checkout's
+ ``testing`` there first. ``testing.conformance`` itself needs pytest, which the Read the Docs build does not
+ install; this module does not.
+ """
+ name = "_kornia_conformance_promise"
+ if name not in sys.modules:
+ spec = importlib.util.spec_from_file_location(name, REPO / "testing" / "conformance_promise.py")
+ if spec is None or spec.loader is None:
+ raise ImportError(f"cannot load {REPO / 'testing' / 'conformance_promise.py'}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module # dataclasses look their module up there
+ spec.loader.exec_module(module)
+ return sys.modules[name]
+
+
+def _issue_links(text: str) -> str:
+ """Turn ``#NNNN`` and ``owner/repo#NNNN`` into links to the GitHub issue."""
+
+ def link(match: re.Match[str]) -> str:
+ repo = match["repo"] or "kornia/kornia"
+ return f"`{match[0]} <https://github.com/{repo}/issues/{match['number']}>`__"
+
+ return re.sub(r"(?<![\w/])(?:(?P<repo>[\w.-]+/[\w.-]+))?#(?P<number>\d+)\b", link, text)
+
+
+def _release_key(release: str) -> tuple[int, ...]:
+ return tuple(int(part) for part in release.split("."))
+
+
+def _and(items: list[str]) -> str:
+ return items[0] if len(items) == 1 else f"{', '.join(items[:-1])} and {items[-1]}"
+
def _applicable(case: dict) -> bool:
"""False for the registry entries that are not tensor graphs at all (file I/O, enums, Python containers)."""
@@ -161,7 +215,7 @@ def _operator_cell(case: dict) -> str:
return label
-def _details(case: dict) -> str:
+def _details(case: dict, excluded: dict[str, dict[str, str]]) -> str:
# columns that share one cause are named together: "ONNX, export, compile: ..."
by_detail: dict[str, list[str]] = {}
for column, key in (("ONNX", "onnx"), ("export", "export"), ("compile", "compile")):
@@ -169,12 +223,22 @@ def _details(case: dict) -> str:
if detail:
by_detail.setdefault(detail, []).append(column)
parts = [f"**{', '.join(columns)}:** {_escape(detail)}" for detail, columns in by_detail.items()]
+ parts += [
+ f"**{column}:** not promised: {_issue_links(_escape(reason))}"
+ for column, key in (("ONNX", "onnx"), ("compile", "compile"))
+ if (reason := excluded[key].get(case["name"]))
+ ]
if case.get("where"):
parts.append(f"``{case['where']}``")
return " Β· ".join(parts)
-def _table(cases: list[dict]) -> str:
+def _status_cell(case: dict, key: str, promised: dict[str, set[str]]) -> str:
+ cell = _cell(case[key], case.get("graph_breaks", 0) if key == "compile" else 0)
+ return f"{cell} :{PROMISED_ROLE}:`promised`" if case["name"] in promised.get(key, ()) else cell
+
+
+def _table(cases: list[dict], promised: dict[str, set[str]], excluded: dict[str, dict[str, str]]) -> str:
rows = [
" * - Operator",
" - ONNX",
@@ -186,10 +250,10 @@ def _table(cases: list[dict]) -> str:
for c in cases:
rows += [
f" * - {_operator_cell(c)}",
- f" - {_cell(c['onnx'])}",
+ f" - {_status_cell(c, 'onnx', promised)}",
f" - {_cell(c['export'])}",
- f" - {_cell(c['compile'], c.get('graph_breaks', 0))}",
- f" - {_details(c) or ' '}",
+ f" - {_status_cell(c, 'compile', promised)}",
+ f" - {_details(c, excluded) or ' '}",
]
return "\n".join(rows)
@@ -266,9 +330,173 @@ def _legend(cases: list[dict]) -> str:
for status, (role, text, meaning) in STATUS.items():
if status in used:
rows += [f" * - :{role}:`{text}`", f" - {meaning}"]
+ rows += [
+ f" * - :{PROMISED_ROLE}:`promised`",
+ " - part of the promise above, checked by Kornia's continuous integration",
+ ]
+ return "\n".join(rows)
+
+
+def _promise_tables(data: dict, promise: ModuleType, packages: list[str]) -> str:
+ """Per package, the promised operators and configurations of each promise."""
+ records = {c["name"]: c for c in data["cases"]}
+ promises = promise.PROMISES
+ counts: dict[str, dict[str, tuple[int, int]]] = {}
+ for p in promises:
+ by_package: dict[str, list[dict]] = defaultdict(list)
+ for name in promise.promised_cases(p):
+ by_package[records[name]["package"]].append(records[name])
+ counts[p.field] = {pkg: (len({c["operator"] for c in cs}), len(cs)) for pkg, cs in by_package.items()}
+ rows = [" * - Package"] + [f" - {p.name}: operators (configurations)" for p in promises]
+ for pkg in [pkg for pkg in packages if any(pkg in counts[p.field] for p in promises)]:
+ rows.append(f" * - :ref:`{pkg} <export-support-{_slug(pkg)}>`")
+ for p in promises:
+ ops, configurations = counts[p.field].get(pkg, (0, 0))
+ rows.append(f" - {ops} ({configurations})" if configurations else " - β€”")
return "\n".join(rows)
+def _exclusions(data: dict, promise: ModuleType) -> str:
+ """The configurations each promise leaves out although the survey marks them as passing, with the reason."""
+ records = {c["name"]: c for c in data["cases"]}
+ blocks = []
+ for p in promise.PROMISES:
+ excluded = promise.EXCLUDED[p.field]
+ if not excluded:
+ continue
+ items = [f"- {_operator_cell(records[name])}: {_issue_links(reason)}." for name, reason in excluded.items()]
+ blocks.append(
+ f"**Left out of the {p.name} promise.** The survey marks these configurations as passing, but they are not"
+ " promised:\n\n" + "\n".join(items)
+ )
+ return "\n\n".join(blocks)
+
+
+def _failure_counts(promise: ModuleType, p: object, tests: tuple[str, ...]) -> dict[str, int]:
+ """Per enforced torch release, the manifest entries of ``p`` for the per-case ``tests``."""
+ counts = {}
+ for release in sorted(promise.ENFORCED_TORCH_RELEASES, key=_release_key):
+ path = promise.manifest_path(p, release)
+ entries = promise.known_failures(p, path) if path.exists() else []
+ counts[release] = sum(entry.test in tests for entry in entries)
+ return counts
+
+
+def _except_known(counts: dict[str, int]) -> str:
+ """``except the known failures listed below (1 on torch 2.9, none on torch 2.14)``."""
+ per_release = ", ".join(f"{n or 'none'} on torch {release}" for release, n in counts.items())
+ return f"except the known failures listed below ({per_release})"
+
+
+def _os_name(os: str) -> str:
+ if os.startswith("ubuntu"):
+ return "Linux"
+ raise ValueError(f"no display name for the CI runner {os!r}")
+
+
+def _known_failures(data: dict, promise: ModuleType) -> str:
+ """The manifest entries of every enforced torch release: per tracking issue and check, the releases and cases."""
+ records = {c["name"]: c for c in data["cases"]}
+ releases = sorted(promise.ENFORCED_TORCH_RELEASES, key=_release_key)
+ failing: dict[tuple[str, str], dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
+ for p in promise.PROMISES:
+ for release in releases:
+ path = promise.manifest_path(p, release)
+ if path.exists():
+ for entry in promise.known_failures(p, path):
+ failing[(entry.case, entry.test)][entry.issue].append(release)
+ if not failing:
+ return (
+ "**Known failures.** None: every promised configuration passes on every enforced torch release, and CI"
+ " fails as soon as one does not."
+ )
+ groups: dict[tuple[str, str, tuple[str, ...]], list[str]] = defaultdict(list)
+ for (case, test), issues in failing.items():
+ for issue, on in issues.items():
+ groups[(issue, test, tuple(on))].append(case)
+ rows = [" * - Tracked in", " - Check", " - Fails on torch", " - Configurations"]
+ for (issue, test, on), cases in sorted(groups.items(), key=lambda group: group[0]):
+ rows += [
+ f" * - {_issue_links(issue)}",
+ f" - {promise.CASE_TEST_CHECKS[test]}",
+ f" - {', '.join(on)}",
+ f" - {', '.join(_operator_cell(records[case]) for case in cases)}",
+ ]
+ return f"""\
+**Known failures.** Promised configurations that fail on an enforced torch release. CI expects each of these
+failures and fails once one of them passes, so the list stays current.
+
+.. list-table::
+ :header-rows: 1
+ :widths: auto
+
+{chr(10).join(rows)}"""
+
+
+def _statement(data: dict, packages: list[str]) -> str:
+ """The "What Kornia promises" section, from the promise the conformance tests check."""
+ promise = promise_module()
+ records = {c["name"]: c for c in data["cases"]}
+ totals = {}
+ for p in promise.PROMISES:
+ names = promise.promised_cases(p)
+ totals[p.field] = (len(names), len({(records[n]["package"], records[n]["operator"]) for n in names}))
+ releases = sorted(promise.ENFORCED_TORCH_RELEASES, key=_release_key)
+ onnx_except = _except_known(_failure_counts(promise, promise.ONNX, ("test_export_matches_eager",)))
+ legacy_except = _except_known(_failure_counts(promise, promise.ONNX, ("test_legacy_export_is_not_wrong",)))
+ compile_except = _except_known(_failure_counts(promise, promise.COMPILE, promise.COMPILE.case_tests))
+ per_day = {1: "once a day", 2: "twice a day"}[promise.CI_RUNS_PER_DAY]
+ m = TORCH_25_DYNAMO_ONNX
+ return f"""\
+.. _export-support-promise:
+
+What Kornia promises
+--------------------
+
+Kornia's continuous integration checks the promises of this section. They cover *configurations* of the
+survey below, each one operator with one concrete set of inputs and keyword arguments, and they hold for
+inference: modules in eval mode, under ``torch.no_grad()``, as CI runs them.
+
+**ONNX export.** The {totals["onnx"][0]} promised configurations ({totals["onnx"][1]} operators) export with
+the ``torch.export``-based exporter, ``torch.onnx.export(..., dynamo=True)`` at opset {promise.ONNX_OPSET} (the
+opset ``to_onnx`` requests) and the survey's static input shapes, and onnxruntime matches eager execution: the
+same dtype, and values within the configuration's tolerance, on torch {releases[0]} and later, {onnx_except}. On
+torch {_and(releases)}, a legacy (TorchScript) export of a promised configuration is never silently wrong: it
+either matches eager or fails loudly, {legacy_except}.
+
+On torch 2.5 to 2.8 the ``to_onnx`` method of Kornia's exportable modules keeps torch's default exporter, which
+there is the legacy one: pass ``dynamo=True`` for the promised exporter. A one-time measurement on torch
+{m["torch"]} ({m["date"]}, not re-checked by CI): {m["passed"]} of the {m["promised"]} configurations promised
+then pass with the dynamo exporter.
+
+**torch.compile.** The {totals["compile"][0]} promised configurations ({totals["compile"][1]} operators) compile
+with ``torch.compile(..., fullgraph=True)`` and the default inductor backend at the survey's static input shapes,
+and match eager execution: the same dtype, and values within the configuration's tolerance, {compile_except}.
+
+**Where it is checked.** On CPU in {promise.CI_DTYPE}, on {_os_name(promise.CI_OS)} with Python
+{promise.CI_PYTHON}: torch {_and(list(promise.CI_TORCH_SCHEDULED))} {per_day} on ``main``, and torch
+{_and(list(promise.CI_TORCH_PULL_REQUEST))} on every pull request, for the packages it touches. Not promised:
+CUDA, MPS, ``float16`` and ``bfloat16``, dynamic shapes (under ONNX export or ``torch.compile``), training mode
+and autograd through a compiled graph (inputs that require grad, a backward pass), ``kornia.models``,
+``kornia.contrib``, anything built with pretrained weights, operators outside the :doc:`stable core
+<stability>`, and operators not listed here.
+
+The survey tables mark each promised configuration with :{PROMISED_ROLE}:`promised` under its ONNX or
+torch.compile result. By package:
+
+.. list-table::
+ :header-rows: 1
+ :widths: auto
+ :class: kornia-compat-summary
+
+{_promise_tables(data, promise, packages)}
+
+{_exclusions(data, promise)}
+
+{_known_failures(data, promise)}
+"""
+
+
def render_page(data: dict) -> str:
cases = data["cases"]
by_package: dict[str, list[dict]] = defaultdict(list)
@@ -276,15 +504,19 @@ def render_page(data: dict) -> str:
by_package[c["package"]].append(c)
packages = [p for p in PACKAGE_ORDER if p in by_package] + sorted(p for p in by_package if p not in PACKAGE_ORDER)
total = _counts(cases)
- roles = "\n".join(f".. role:: {role}" for role, _, _ in STATUS.values())
+ roles = "\n".join(f".. role:: {role}" for role in [*(role for role, _, _ in STATUS.values()), PROMISED_ROLE])
n_ok_all = sum(
1 for c in cases if c["onnx"] in SUPPORTED and c["export"] in SUPPORTED and c["compile"] in SUPPORTED
)
ops = _operator_counts(cases)
+ promise = promise_module()
+ promised = {p.field: set(promise.promised_cases(p)) for p in promise.PROMISES}
+ excluded = promise.EXCLUDED
description = (
- f"A dated survey of which Kornia operators exported to ONNX, captured with torch.export and ran under "
- f"torch.compile: {len(cases)} probed configurations across {len(packages)} packages, with the reason for "
- f"every failure. A measurement, not a support guarantee."
+ f"What Kornia promises for ONNX export and torch.compile, checked in CI for {len(promised['onnx'])} and "
+ f"{len(promised['compile'])} stable-core configurations, and a dated survey of which operators exported to "
+ f"ONNX, captured with torch.export and ran under torch.compile: {len(cases)} probed configurations across "
+ f"{len(packages)} packages, with the reason for every failure."
)
sections = []
@@ -311,36 +543,40 @@ def render_page(data: dict) -> str:
" :widths: auto",
" :class: kornia-compat-table",
"",
- _table(section_cases),
+ _table(section_cases, promised, excluded),
"",
]
sections.append("\n".join(block))
return f"""\
-.. This page is generated at build time by docs/generate_export_support.py from
- docs/source/_data/export_support.json. Edit those, not this file.
+.. This page is generated at build time by docs/generate_export_support.py: the promise from
+ testing/conformance_promise.py and the conformance manifests in testing/known_failure_xfails/, the
+ survey from docs/source/_data/export_support.json. Edit those, not this file.
{roles}
.. _export-support:
-ONNX, torch.compile and torch.export survey
-===========================================
+ONNX, torch.compile and torch.export support
+============================================
.. meta::
:description: {description}
-Every public operator, model and augmentation in kornia was run through the three graph-capture
-paths PyTorch offers, and this page lists the result for each one, package by package, with the
-cause of every failure. Use the search box to find an operator, or the summary table to jump to a
-package.
+This page states what Kornia promises for ONNX export and ``torch.compile``, then lists a survey
+that ran every public operator, model and augmentation in kornia through the three graph-capture
+paths PyTorch offers: the result for each one, package by package, with the cause of every failure.
+Use the search box to find an operator, or the summary table to jump to a package.
+
+{_statement(data, packages)}
+The survey
+----------
.. note::
- This page records one measurement, not a support guarantee. It was taken on {data.get("generated_at", "")}
- with torch {data.get("torch", "")}, and Kornia's test suite checks only part of what it lists as working, so
- an entry may no longer hold for the current release. Export or compile your own pipeline and compare it with
- eager before relying on it.
+ The survey records one measurement, taken on {data.get("generated_at", "")} with torch {data.get("torch", "")}.
+ Kornia promises only the configurations marked *promised*; any other entry may no longer hold for the current
+ release, so export or compile your own pipeline and compare it with eager before relying on it.
.. grid:: 1 3 3 3
:gutter: 3
@@ -391,7 +627,7 @@ in brackets after the operator. Augmentations are probed twice: with their sampl
in as graph inputs (a deterministic graph) and with the sampling inside the graph (``[random]``).
Registry entries that are not tensor graphs at all (file I/O, enums, Python containers, stubs) are
not listed.
-The survey lives in ``docs/export_support/`` and this page is rendered from its committed result;
+The survey lives in ``docs/export_support/`` and its tables are rendered from its committed result;
nothing refreshes that result automatically.
Legend
@@ -404,12 +640,13 @@ Legend
{_legend(cases)}
-Every entry on this page, a pass as much as a failure, is a fact about a specific torch, exporter and
-kornia version, not a promise: most *no* entries are missing ONNX lowerings upstream (``torch.linalg.svd``, ``solve``,
-``lu_factor``, ``eigh``, ``qr``, ``histc``), data-dependent output sizes (matchers that return a
-variable number of pairs, detectors that keep the top-k responses above a threshold, NMS), or
-Python control flow that reads tensor values. See :doc:`onnx` for how to chain exported graphs and
-:doc:`gpu-acceleration` for ``torch.compile`` in practice.
+Every survey entry, a pass as much as a failure, is a fact about a specific torch, exporter and
+kornia version; what Kornia promises is the section above. Most *no* entries are missing ONNX
+lowerings upstream (``torch.linalg.svd``, ``solve``, ``lu_factor``, ``eigh``, ``qr``, ``histc``),
+data-dependent output sizes (matchers that return a variable number of pairs, detectors that keep
+the top-k responses above a threshold, NMS), or Python control flow that reads tensor values. See
+:doc:`onnx` for how to chain exported graphs and :doc:`gpu-acceleration` for ``torch.compile`` in
+practice.
.. raw:: html
diff --git a/docs/source/_static/css/pydata.css b/docs/source/_static/css/pydata.css
index 997f996cd..ecec1abf1 100644
--- a/docs/source/_static/css/pydata.css
+++ b/docs/source/_static/css/pydata.css
@@ -1091,6 +1091,27 @@ html[data-theme="dark"] .compat-fail {
border-color: rgba(248, 113, 113, 0.35);
}
+/* The "promised" marker of a configuration the CI-checked promise covers; in a survey table it sits under the status
+ pill, so it does not widen the column. The class has no "compat-" in it: custom.js reads a cell's status from the
+ first class that does. */
+.kornia-promised {
+ display: inline-block;
+ padding: 0 0.4rem;
+ border-radius: 999px;
+ font-size: 0.7rem;
+ font-weight: 600;
+ line-height: 1.5;
+ white-space: nowrap;
+ color: var(--pst-color-primary);
+ border: 1px solid var(--pst-color-primary);
+}
+
+.kornia-compat-table .kornia-promised {
+ display: block;
+ width: fit-content;
+ margin-top: 0.25rem;
+}
+
/* Search box and status filter; ``hidden`` until custom.js wires them up. */
.kornia-compat-controls {
position: sticky;
diff --git a/docs/source/conf.py b/docs/source/conf.py
index e01f968bc..4e6529bb9 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -110,7 +110,8 @@ spec = importlib.util.spec_from_file_location("generate_export_support", "../gen
generate_export_support = importlib.util.module_from_spec(spec)
spec.loader.exec_module(generate_export_support)
-# Pre-generate the ONNX / torch.compile / torch.export survey page from the committed snapshot
+# Pre-generate the ONNX / torch.compile / torch.export support page: the promise from testing/conformance_promise.py
+# and the conformance manifests, the survey from the committed snapshot
generate_export_support.main()
diff --git a/docs/source/get-started/index.rst b/docs/source/get-started/index.rst
index 61e9a626f..5f3ce4b5e 100644
--- a/docs/source/get-started/index.rst
+++ b/docs/source/get-started/index.rst
@@ -71,4 +71,4 @@ Looking for a specific function instead? The :doc:`API reference </api>` documen
:hidden:
Tutorials <https://www.kornia.org/tutorials/>
- ONNX, torch.compile & torch.export survey <export-support>
+ ONNX, torch.compile & torch.export support <export-support>
diff --git a/docs/source/get-started/onnx.rst b/docs/source/get-started/onnx.rst
index abdc0c339..ec2e0d272 100644
--- a/docs/source/get-started/onnx.rst
+++ b/docs/source/get-started/onnx.rst
@@ -16,10 +16,10 @@ runs it with ONNX Runtime. It is useful when you have pre-exported operators or
- **Execution providers**: run on CPU, CUDA, TensorRT or OpenVINO through ONNX Runtime, with control over the
session options.
-The :ref:`ONNX, torch.compile and torch.export survey <export-support>` records whether each operator, model
-and augmentation exported in one dated measurement, with the cause of each failure. It is a snapshot, not a
-support guarantee, and Kornia's tests check only part of it: export your own pipeline and compare it with eager
-before relying on it.
+Which operators Kornia promises to export, and how continuous integration checks it, is stated in
+:ref:`What Kornia promises <export-support-promise>`. The survey on the same page records whether each operator, model
+and augmentation exported in one dated measurement, with the cause of each failure: for anything the promise does not
+cover, export your own pipeline and compare it with eager before relying on it.
Quickstart
----------
@@ -36,8 +36,8 @@ Quickstart
``torch.onnx.export`` turns it into an ONNX file that :class:`~kornia.onnx.sequential.ONNXSequential`
can load, chain and re-export. Use the ``torch.export``-based exporter (``dynamo=True``). It is the
default of ``torch.onnx.export`` from PyTorch 2.9, which deprecates the TorchScript-based one, and it is
- the exporter the :ref:`export survey <export-support>` measures. Passing ``dynamo=True`` explicitly makes
- the same call work on PyTorch 2.5 to 2.8, where the TorchScript-based exporter is still the default:
+ the exporter :ref:`Kornia's ONNX promise <export-support-promise>` covers. Passing ``dynamo=True`` explicitly
+ makes the same call work on PyTorch 2.5 to 2.8, where the TorchScript-based exporter is still the default:
.. code-block:: python
@@ -194,9 +194,10 @@ Yes. Pass them as ``session_options=`` to the constructor of
the object on the one it already has.
**Which operators export?**
-The :ref:`ONNX, torch.compile and torch.export survey <export-support>` lists every surveyed operator with
-its ONNX export, ``torch.export`` and ``torch.compile`` outcome in one dated measurement, searchable by name and
-filterable by result. Treat an entry as a starting point, not a guarantee.
+The promised ones: :ref:`What Kornia promises <export-support-promise>` counts them per package, and the survey on the
+same page marks them *promised*. The survey lists every surveyed operator with its ONNX export, ``torch.export`` and
+``torch.compile`` outcome in one dated measurement, searchable by name and filterable by result; treat an entry that is
+not promised as a starting point, not a guarantee.
**Where are the pre-exported Kornia operators?**
In the `kornia/ONNX_models <https://huggingface.co/kornia/ONNX_models>`_ Hugging Face repository; load them with
diff --git a/docs/source/get-started/stability.rst b/docs/source/get-started/stability.rst
index 4d7aff955..bf56eccd6 100644
--- a/docs/source/get-started/stability.rst
+++ b/docs/source/get-started/stability.rst
@@ -86,6 +86,9 @@ The promises (stable core)
order, angle units, homography conventions) are part of the API surface
and covered by the same rules.
+What the stable core promises for ONNX export and ``torch.compile``, and where
+CI checks it, is stated on the :ref:`support page <export-support-promise>`.
+
Versioning caveat
-----------------
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 6ca99d32f..16d761293 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -703,6 +703,11 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
squares exceed the ``float16`` maximum of 65504, and two 32768-pixel squares exceed ``int32``.
``bfloat16`` does not overflow, but its rounding can move an IoU across ``iou_threshold``.
+ Note:
+ For one box or more, ``torch.compile`` cannot capture ``nms`` in one graph: the number of loop iterations and
+ the size of the output depend on the box values. ``fullgraph=True`` raises, and a default ``torch.compile``
+ runs it eagerly, so it is outside the :ref:`torch.compile promise <export-support-promise>`.
+
.. warning::
This differs from the inclusive coordinate arithmetic used by several other
:mod:`kornia.geometry.bbox` operations and is documented in
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index 5fc7e2710..fc87bcc1c 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -294,6 +294,11 @@ def draw_rectangle(
This operation modifies image inplace but also returns the drawn tensor for
convenience, with the shape of the input :math:`(B, C, H, W)`.
+ Note:
+ The rectangle coordinates are read back to the host once, and ``torch.compile`` breaks the graph there: a
+ default ``torch.compile`` compiles the code on either side of that read and matches eager. It is outside the
+ :ref:`torch.compile promise <export-support-promise>`.
+
Example:
>>> img = torch.rand(2, 3, 10, 12)
>>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 11, 9]]])
diff --git a/testing/conformance.py b/testing/conformance.py
index 50a2042ca..83276ed38 100644
--- a/testing/conformance.py
+++ b/testing/conformance.py
@@ -18,12 +18,12 @@
"""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:
+Two promises share this machinery, ``ONNX`` and ``COMPILE``, defined in ``testing/conformance_promise.py``: 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``) and the promise's listed exclusions. 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``
@@ -37,83 +37,37 @@ in ``testing/known_failure_xfails/<onnx|compile>_conformance_torch<major>.<minor
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
+from typing import Any, 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 promise itself (what is promised, left out, known to fail) is testing/conformance_promise.py, which the docs build
+# imports without pytest; this module runs it as pytest tests.
+from testing.conformance_promise import (
+ EXPORT_SUPPORT,
+ REGISTRIES,
+ STABLE_CORE,
+ Promise,
+ exclusion_problems,
+ known_failures,
+ manifest_path,
+ pretrained_cases,
+ promised_cases,
+ promised_digest,
)
+from testing.known_failures import _EXCEPTION_TYPES, KnownFailureTracker
# 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.
@@ -132,7 +86,6 @@ REGISTRIES_OF = {
"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")
@@ -194,47 +147,6 @@ def selection(config: pytest.Config, promise: Promise) -> tuple[str, ...]:
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]
@@ -343,7 +255,7 @@ def registration_problems(promise: Promise, packages: Sequence[str]) -> list[str
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."""
+ """How the promised set differs from its pin (``count``, ``digest``), keeps a stale exclusion, or breaks a rule."""
# 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)
@@ -353,6 +265,7 @@ def pin_problems(promise: Promise, count: int, digest: str) -> list[str]:
"the promised set changed; review the snapshot diff, then update PROMISED_COUNT and PROMISED_DIGEST"
f" (now {len(promised)}, {promised_digest(promised)})"
)
+ problems += exclusion_problems(promise)
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()):
@@ -521,36 +434,13 @@ def state_changes(before: dict[str, Any], after: dict[str, Any]) -> list[str]:
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>.+)\]$")
+ """Read a promise's manifest (``conformance_promise.known_failures``): node ID -> the exception type it names."""
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]
+ for entry in known_failures(promise, path):
+ if entry.exception not in _EXCEPTION_TYPES:
+ raise ValueError(f"{path}:{entry.line}: unknown exception type: {entry.exception}")
+ failures[entry.nodeid] = _EXCEPTION_TYPES[entry.exception]
return failures
diff --git a/testing/conformance_promise.py b/testing/conformance_promise.py
new file mode 100644
index 000000000..8aff1853b
--- /dev/null
+++ b/testing/conformance_promise.py
@@ -0,0 +1,286 @@
+# 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.
+#
+
+"""kornia's ONNX and torch.compile promises (#5819): which survey cases are promised, which are left out and why, and
+which are known to fail on each enforced torch release.
+
+The conformance tests (``testing/conformance.py``) check exactly this, and the docs build renders the support
+statement of ``docs/source/get-started/export-support.rst`` from it (``docs/generate_export_support.py``), so the two
+cannot drift apart. It imports neither pytest nor the survey's cases: the docs environment has no pytest.
+"""
+
+from __future__ import annotations
+
+import ast
+import functools
+import hashlib
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Iterable, Mapping
+
+import torch
+
+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)
+# What each per-case test checks, as the support statement names it.
+CASE_TEST_CHECKS = {
+ "test_export_matches_eager": "ONNX export (dynamo exporter)",
+ "test_legacy_export_is_not_wrong": "ONNX export (legacy exporter)",
+ "test_inductor_matches_eager": "torch.compile",
+}
+# Where CI checks the promises: the onnx-conformance and compile-conformance jobs of scheduled_test_cpu.yml (on main,
+# CI_RUNS_PER_DAY times a day) and of pr_test_cpu.yml (pull requests). tests/test_generate_export_support.py checks
+# these against the workflows, and the support statement renders them.
+CI_TORCH_SCHEDULED = ("2.9.1", "2.14.0")
+CI_TORCH_PULL_REQUEST = ("2.14.0",)
+CI_RUNS_PER_DAY = 2
+CI_PYTHON = "3.11"
+CI_OS = "ubuntu-latest"
+CI_DTYPE = "float32"
+# The ONNX opset the conformance harness exports at: the one ``ONNXExportMixin.to_onnx`` requests (checked against
+# both by tests/test_generate_export_support.py).
+ONNX_OPSET = 18
+
+
+def release(version: str) -> str:
+ """The ``<major>.<minor>`` release of a torch version: ``"2.14.0+cpu"`` -> ``"2.14"``."""
+ return ".".join(version.split("+", maxsplit=1)[0].split(".")[:2])
+
+
+# The torch releases whose manifests the scheduled conformance jobs enforce.
+ENFORCED_TORCH_RELEASES = tuple(release(version) for version in CI_TORCH_SCHEDULED)
+
+# 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 survey's case registries (``docs/export_support/cases_*.py``) that may hold promised cases. ``cases_models.py``
+# builds the pretrained models of ``kornia.models``, none of which is promised.
+REGISTRIES = ("cases_aug", "cases_feature", "cases_geomA", "cases_geomB", "cases_misc")
+
+# Snapshot records a promise leaves out although they meet its filter, with the reason the support statement shows.
+# Each must still meet the filter (exclusion_problems): delete an entry once a regenerated snapshot no longer does.
+EXCLUDED: dict[str, dict[str, str]] = {
+ "onnx": {},
+ "compile": {
+ # #6194: the survey marked these "ok" by torch._dynamo.explain's break count, but they read tensor values on
+ # the host (a loop count, slice bounds), which torch.compile(..., fullgraph=True) cannot be relied on to
+ # capture.
+ "bbox.nms": (
+ "for one box or more, the number of loop iterations and the output size depend on the box values, so"
+ " torch.compile cannot capture it in one graph; a default torch.compile runs it eagerly (#6194)"
+ ),
+ "image.draw_rectangle": (
+ "reads the rectangle coordinates back to the host, where a default torch.compile breaks the graph, and"
+ " fullgraph=True fails on most inputs (#6194)"
+ ),
+ "image.draw_rectangle[fill]": (
+ "reads the rectangle coordinates back to the host, where a default torch.compile breaks the graph, and"
+ " fullgraph=True fails on most inputs (#6194)"
+ ),
+ },
+}
+
+# A manifest comment that opens with an issue reference ("#5037: ...", "pytorch/pytorch#198270 (...): ...") names the
+# tracking issue of the entries below it.
+_CITATION = re.compile(r"^# (?P<issue>(?:[\w.-]+/[\w.-]+)?#\d+)\b")
+
+
+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 snapshot() -> dict[str, Any]:
+ """The committed survey snapshot."""
+ return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
+
+
+def candidate_cases(promise: Promise) -> dict[str, str]:
+ """Map every case that meets ``promise``'s filter to its package, in snapshot order, exclusions included.
+
+ The filter: status ``ok`` in the snapshot field of the promise, a stable-core package, and nothing built with
+ pretrained weights (registry tag ``pretrained``; the stable core holds only the classical parts of
+ ``kornia.feature``).
+ """
+ pretrained = pretrained_cases()
+ candidates: dict[str, str] = {}
+ for record in snapshot()["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
+ candidates[record["name"]] = package
+ return candidates
+
+
+def promised_cases(promise: Promise) -> dict[str, str]:
+ """Map every case ``promise`` covers to its package (``geometry``, ``color``, ...), in snapshot order."""
+ excluded = EXCLUDED[promise.field]
+ return {name: package for name, package in candidate_cases(promise).items() if name not in excluded}
+
+
+def exclusion_problems(promise: Promise, excluded: Mapping[str, str] | None = None) -> list[str]:
+ """The exclusions of ``promise`` (default: its ``EXCLUDED`` entry) that leave nothing out any more.
+
+ An excluded name must be a case the promise would cover without the exclusion. A regenerated snapshot that no
+ longer marks it ``ok`` drops it by itself, and the stale entry would then hide it if it ever passed again.
+ """
+ excluded = EXCLUDED[promise.field] if excluded is None else excluded
+ candidates = candidate_cases(promise)
+ return [
+ f"{name}: the snapshot no longer records it as {promise.field} 'ok' in a stable-core package; delete its"
+ f" entry from EXCLUDED[{promise.field!r}] in testing/conformance_promise.py"
+ for name in excluded
+ if name not in candidates
+ ]
+
+
+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 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``.
+ """
+ return MANIFEST_DIR / f"{promise.marker}_torch{release(version or torch.__version__)}.txt"
+
+
+@dataclass(frozen=True)
+class KnownFailure:
+ """One entry of a known-failure manifest."""
+
+ line: int
+ exception: str # the exception type's name as the manifest spells it
+ nodeid: str
+ test: str # the per-case test
+ case: str # the promised case
+ issue: str # the reference that opens the comment above the entry: "#5037", "pytorch/pytorch#198270"
+
+
+def known_failures(promise: Promise, path: Path) -> list[KnownFailure]:
+ """Read ``<exception type>\\t<node ID>`` lines; every node ID must name a per-case test of a promised case.
+
+ Every entry must sit under a comment that opens with its tracking issue (``# #NNNN: ...``); the comment lines
+ right below it continue it, and a comment that names no issue after an entry or a blank line starts a block
+ without one. The exception name is checked by ``testing.conformance.load_known_failures``, which maps it to a type.
+ """
+ node = re.compile(rf"^{re.escape(promise.test_file)}::(?P<test>\w+)\[(?P<case>.+)\]$")
+ promised = promised_cases(promise)
+ entries: list[KnownFailure] = []
+ seen: set[str] = set()
+ issue = ""
+ block_ended = False # an entry or a blank line since the last comment line
+ for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
+ if not line:
+ block_ended = True
+ continue
+ if line.startswith("#"):
+ if citation := _CITATION.match(line):
+ issue = citation["issue"]
+ elif block_ended: # a comment block of its own that names no issue
+ issue = ""
+ block_ended = False
+ continue
+ block_ended = True
+ try:
+ exception, nodeid = line.split("\t", maxsplit=1)
+ except ValueError as error:
+ raise ValueError(f"{path}:{number}: expected '<exception>\\t<node ID>'") from error
+ 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:
+ raise ValueError(f"{path}:{number}: {match['case']!r} is not a promised case (renamed or dropped?)")
+ if nodeid in seen:
+ raise ValueError(f"{path}:{number}: duplicate node ID: {nodeid}")
+ if not issue:
+ raise ValueError(f"{path}:{number}: no tracking issue; put the entry under a '# #NNNN: why' comment")
+ seen.add(nodeid)
+ entries.append(KnownFailure(number, exception, nodeid, match["test"], match["case"], issue))
+ return entries
diff --git a/testing/known_failure_xfails/compile_conformance_torch2.14.txt b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
index f3474ad01..152d96bd8 100644
--- a/testing/known_failure_xfails/compile_conformance_torch2.14.txt
+++ b/testing/known_failure_xfails/compile_conformance_torch2.14.txt
@@ -6,10 +6,6 @@
# 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]
# 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
index 3a366949f..6d2c39b75 100644
--- a/testing/known_failure_xfails/compile_conformance_torch2.9.txt
+++ b/testing/known_failure_xfails/compile_conformance_torch2.9.txt
@@ -6,11 +6,6 @@
# 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/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index 34394a1d5..08db94043 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -921,6 +921,17 @@ class TestNMS(BaseTester):
actual = nms(boxes, scores, iou_threshold=0.3)
self.assert_close(actual, torch.tensor([1, 0], device=device, dtype=torch.long), atol=0.0, rtol=0.0)
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ # A default torch.compile cannot capture the data-dependent loop in one graph and runs nms eagerly: the same
+ # indices, which keep the descending-score order.
+ boxes = torch.tensor(
+ [[10, 10, 20, 20], [15, 5, 15, 25], [100, 100, 150, 150], [100, 100, 150, 150]], device=device, dtype=dtype
+ )
+ scores = torch.tensor([0.9, 0.8, 0.7, 0.95], device=device, dtype=dtype)
+ expected = torch.tensor([3, 0, 1], device=device, dtype=torch.long)
+ self.assert_close(nms(boxes, scores, 0.5), expected, atol=0, rtol=0)
+ self.assert_close(torch_optimizer(nms)(boxes, scores, 0.5), expected, atol=0, rtol=0)
+
def test_empty(self, device):
boxes = torch.empty((0, 4), device=device)
scores = torch.empty((0,), device=device)
diff --git a/tests/onnx/test_conformance.py b/tests/onnx/test_conformance.py
index f2cdbfebe..815feb20a 100644
--- a/tests/onnx/test_conformance.py
+++ b/tests/onnx/test_conformance.py
@@ -33,23 +33,20 @@ from __future__ import annotations
import pytest
from testing.conformance import (
- ENFORCED_TORCH_RELEASES,
LEGACY_PASSES,
- ONNX,
import_survey_module,
load_known_failures,
- manifest_path,
parametrize_cases,
pin_problems,
process_state,
promised_case,
- promised_cases,
raise_for_status,
registration_problems,
run_onnx_case,
selection,
state_changes,
)
+from testing.conformance_promise import ENFORCED_TORCH_RELEASES, ONNX, manifest_path, promised_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.conformance forks only the CPU
diff --git a/tests/scripts/test_conformance_packages.py b/tests/scripts/test_conformance_packages.py
index b20588339..e12dcb69b 100644
--- a/tests/scripts/test_conformance_packages.py
+++ b/tests/scripts/test_conformance_packages.py
@@ -22,7 +22,7 @@ from pathlib import Path
import pytest
-from testing import conformance
+from testing import conformance, conformance_promise
# `.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.
@@ -217,9 +217,9 @@ def test_cli_requires_a_promise():
def test_stable_core_matches_the_test_and_the_stability_page():
- assert STABLE_CORE == conformance.STABLE_CORE
+ assert STABLE_CORE == conformance_promise.STABLE_CORE
assert set(conformance.REGISTRIES_OF) == set(STABLE_CORE)
- assert TEST_FILES == {promise.field: promise.test_file for promise in conformance.PROMISES}
+ assert TEST_FILES == {promise.field: promise.test_file for promise in conformance_promise.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_generate_export_support.py b/tests/test_generate_export_support.py
new file mode 100644
index 000000000..d9e4b4ac1
--- /dev/null
+++ b/tests/test_generate_export_support.py
@@ -0,0 +1,134 @@
+# 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.
+#
+
+"""The support statement of the export-support page is the promise the conformance tests check (#5819)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+from testing.conformance import import_survey_module
+from testing.conformance_promise import (
+ CI_DTYPE,
+ CI_OS,
+ CI_PYTHON,
+ CI_RUNS_PER_DAY,
+ CI_TORCH_PULL_REQUEST,
+ CI_TORCH_SCHEDULED,
+ COMPILE,
+ ENFORCED_TORCH_RELEASES,
+ EXCLUDED,
+ ONNX,
+ ONNX_OPSET,
+ PROMISES,
+ known_failures,
+ manifest_path,
+ promised_cases,
+ release,
+)
+
+REPO = Path(__file__).parents[1]
+
+_spec = importlib.util.spec_from_file_location("generate_export_support", REPO / "docs" / "generate_export_support.py")
+generate_export_support = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(generate_export_support)
+
+
+def _statement() -> tuple[str, str]:
+ """The rendered page, and its statement section with the line breaks of the source joined."""
+ page = generate_export_support.render_page(generate_export_support.load_data())
+ statement = page.split(".. _export-support-promise:", 1)[1].split("\nThe survey\n----------\n", 1)[0]
+ return page, " ".join(statement.split())
+
+
+def _except_known(promise, tests: tuple[str, ...]) -> str:
+ counts = []
+ for enforced in sorted(ENFORCED_TORCH_RELEASES, key=lambda r: tuple(map(int, r.split(".")))):
+ n = sum(entry.test in tests for entry in known_failures(promise, manifest_path(promise, enforced)))
+ counts.append(f"{n or 'none'} on torch {enforced}")
+ return f"except the known failures listed below ({', '.join(counts)})"
+
+
+def test_statement_renders_the_promise_the_tests_check() -> None:
+ # The generator loads testing/conformance_promise.py from its own checkout: the same file as this import.
+ loaded = Path(generate_export_support.promise_module().__file__).resolve()
+ assert loaded == REPO / "testing" / "conformance_promise.py"
+ page, statement = _statement()
+ for promise in PROMISES:
+ assert f"The {len(promised_cases(promise))} promised configurations" in statement
+ # every headline sentence names the known failures of each enforced release, counted from the manifests
+ assert f"on torch 2.9 and later, {_except_known(ONNX, ('test_export_matches_eager',))}." in statement
+ assert f"fails loudly, {_except_known(ONNX, ('test_legacy_export_is_not_wrong',))}." in statement
+ assert f"tolerance, {_except_known(COMPILE, COMPILE.case_tests)}." in statement
+ assert f"at opset {ONNX_OPSET} " in statement
+ for promise in PROMISES:
+ for reason in EXCLUDED[promise.field].values():
+ assert " ".join(generate_export_support._issue_links(reason).split()) in statement
+ issues = {
+ entry.issue
+ for promise in PROMISES
+ for enforced in ENFORCED_TORCH_RELEASES
+ for entry in known_failures(promise, manifest_path(promise, enforced))
+ }
+ for issue in issues:
+ assert generate_export_support._issue_links(issue) in statement
+ # one marker per promised configuration of the survey tables, plus the statement's own and the legend's
+ marker = ":kornia-promised:`promised`"
+ assert page.count(marker) == sum(len(promised_cases(promise)) for promise in PROMISES) + 2
+
+
+def test_statement_states_where_ci_checks_it() -> None:
+ _, statement = _statement()
+ times = {1: "once a day", 2: "twice a day"}[CI_RUNS_PER_DAY]
+ assert (
+ f"On CPU in {CI_DTYPE}, on Linux with Python {CI_PYTHON}: torch {' and '.join(CI_TORCH_SCHEDULED)} {times} on"
+ f" ``main``, and torch {' and '.join(CI_TORCH_PULL_REQUEST)} on every pull request"
+ ) in statement
+ assert ENFORCED_TORCH_RELEASES == tuple(release(version) for version in CI_TORCH_SCHEDULED)
+
+
+ ("workflow", "torch_versions"),
+ [("scheduled_test_cpu.yml", CI_TORCH_SCHEDULED), ("pr_test_cpu.yml", CI_TORCH_PULL_REQUEST)],
+ ids=["scheduled", "pull-request"],
+)
+def test_ci_facts_match_the_conformance_jobs(workflow: str, torch_versions: tuple[str, ...]) -> None:
+ """The page's CI facts are those of the workflows' onnx-conformance and compile-conformance jobs."""
+ import yaml
+
+ config = yaml.safe_load((REPO / ".github" / "workflows" / workflow).read_text(encoding="utf-8"))
+ for promise in PROMISES:
+ job = config["jobs"][f"{promise.field}-conformance"]["with"]
+ assert job["test-path"] == promise.test_file
+ assert json.loads(job["pytorch-version"]) == list(torch_versions)
+ assert json.loads(job["python-version"]) == [CI_PYTHON]
+ assert job["os"] == CI_OS
+ assert job["pytorch-dtype"] == CI_DTYPE
+ if workflow == "scheduled_test_cpu.yml":
+ triggers = config.get("on", config.get(True)) # YAML 1.1 reads the key `on` as True
+ daily = [entry["cron"] for entry in triggers["schedule"] if entry["cron"].split()[2:] == ["*", "*", "*"]]
+ assert len(daily) == CI_RUNS_PER_DAY, daily
+
+
+def test_onnx_opset_is_the_one_ci_and_to_onnx_use() -> None:
+ from kornia.core.mixin.onnx import _ONNX_EXPORT_OPSET
+
+ assert import_survey_module("harness").OPSET == ONNX_OPSET == _ONNX_EXPORT_OPSET
diff --git a/tests/test_inductor_conformance.py b/tests/test_inductor_conformance.py
index eda78785a..605162ab4 100644
--- a/tests/test_inductor_conformance.py
+++ b/tests/test_inductor_conformance.py
@@ -35,27 +35,35 @@ set, so the tests here are named after inductor; this test does not use ``KORNIA
from __future__ import annotations
+import types
+from pathlib import Path
+
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,
)
+from testing.conformance_promise import (
+ COMPILE,
+ ENFORCED_TORCH_RELEASES,
+ EXCLUDED,
+ exclusion_problems,
+ known_failures,
+ manifest_path,
+ promised_cases,
+)
# 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
@@ -66,9 +74,9 @@ pytestmark = [pytest.mark.device_agnostic, pytest.mark.usefixtures("restore_torc
# 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"
+# The compile promise of the 2026-09-02 snapshot, less its exclusions: 829 cases of 635 operators.
+PROMISED_COUNT = 829
+PROMISED_DIGEST = "de2f308f80fad99ac1fccf38efaeb07088fe23b2c8dde9e21070e3c0a4e9c263"
def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
@@ -94,12 +102,65 @@ def test_promised_set_is_pinned() -> None:
assert not problems, "\n".join(problems)
+def test_stale_exclusion_is_reported(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An exclusion must leave out a case the promise would cover without it; one that leaves nothing out is reported.
+
+ A regenerated snapshot that stops marking an excluded case ``ok`` drops it from the promise by itself (#6194).
+ """
+ assert not exclusion_problems(COMPILE)
+ stale = {
+ "transform.crop_by_boxes": "recorded with graph breaks",
+ "utils.create_meshgrid": "not a stable-core package",
+ "feature.OriNet": "built with pretrained weights",
+ "no.such.case": "not in the snapshot",
+ }
+ problems = exclusion_problems(COMPILE, {**EXCLUDED["compile"], **stale})
+ assert [problem.split(": ")[0] for problem in problems] == list(stale), problems
+ assert all("delete its entry from EXCLUDED['compile']" in problem for problem in problems), problems
+ # the pin test runs the guard on the real exclusions; none of these names is promised, so the pin itself holds
+ monkeypatch.setitem(EXCLUDED["compile"], "transform.crop_by_boxes", "recorded with graph breaks")
+ assert pin_problems(COMPILE, PROMISED_COUNT, PROMISED_DIGEST) == [problems[0]]
+
+
@pytest.mark.parametrize("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_known_failure_needs_its_tracking_issue(tmp_path: Path) -> None:
+ """Every manifest entry sits under a comment that opens with its tracking issue, which the support page cites."""
+ entry = "RuntimeError\ttests/test_inductor_conformance.py::test_inductor_matches_eager[{}]"
+ path = tmp_path / "manifest.txt"
+ path.write_text(f"# header\n{entry.format('LongestMaxSize')}\n", encoding="utf-8")
+ with pytest.raises(ValueError, match="no tracking issue"):
+ load_known_failures(COMPILE, path)
+ # a comment block of its own after an entry does not inherit the issue above it
+ path.write_text(
+ f"# #5037: why\n# more of why\n{entry.format('LongestMaxSize')}\n# a note\n{entry.format('SmallestMaxSize')}\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match=r"manifest\.txt:5: no tracking issue"):
+ load_known_failures(COMPILE, path)
+ # nor does one after a blank line, before any entry
+ path.write_text(f"# #5037: why\n\n# an unrelated note\n{entry.format('LongestMaxSize')}\n", encoding="utf-8")
+ with pytest.raises(ValueError, match=r"manifest\.txt:4: no tracking issue"):
+ load_known_failures(COMPILE, path)
+ path.write_text(
+ f"# #5037: why\n{entry.format('LongestMaxSize')}\n# pytorch/pytorch#1 (fixed upstream): why\n"
+ f"{entry.format('SmallestMaxSize')}\n",
+ encoding="utf-8",
+ )
+ assert [(e.case, e.issue) for e in known_failures(COMPILE, path)] == [
+ ("LongestMaxSize", "#5037"),
+ ("SmallestMaxSize", "pytorch/pytorch#1"),
+ ]
+ # an excluded case is not promised, so no manifest may name it
+ path.write_text(f"# #6194: why\n{entry.format('bbox.nms')}\n", encoding="utf-8")
+ with pytest.raises(ValueError, match=r"'bbox\.nms' is not a promised case"):
+ load_known_failures(COMPILE, path)
+
+
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()
@@ -140,6 +201,54 @@ def test_survey_probe_records_failures_and_lets_test_outcomes_through(monkeypatc
probe.export_step(wrap, inputs)
+ ("explained_breaks", "explained_reasons", "status", "reason"),
+ [
+ (0, [], "ok-breaks:0", "fullgraph=True: RuntimeError"),
+ (-1, [], "ok-breaks:0", "fullgraph=True: RuntimeError"),
+ (3, ["generic_jump TensorVariable()"], "ok-breaks:3", "generic_jump TensorVariable()"),
+ ],
+ ids=["no-break", "no-graph", "breaks"],
+)
+def test_survey_probe_reports_ok_only_for_one_graph(
+ monkeypatch: pytest.MonkeyPatch, explained_breaks: int, explained_reasons: list[str], status: str, reason: str
+) -> None:
+ """The survey's compile ``ok`` means ``torch.compile(..., fullgraph=True)`` captured the case (#6194).
+
+ A case ``fullgraph=True`` refuses gets ``torch._dynamo.explain``'s break count and reasons. Explain can count no
+ graph break for a call Dynamo runs in Python: 0, or -1 when it captures no graph at all, as for ``bbox.nms``; the
+ survey records such a case as ``ok-breaks:0``, with the refusal as its break reason. The conformance test
+ (``fullgraph=True`` alone) records every refused case as ``fail``.
+ """
+ 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 compile_without_one_graph(model, fullgraph=False, **kwargs):
+ def refuse(*args):
+ raise RuntimeError("Data dependent operator")
+
+ return refuse if fullgraph else model
+
+ def explain(model):
+ reasons = [types.SimpleNamespace(reason=text) for text in explained_reasons]
+ return lambda *args: types.SimpleNamespace(graph_break_count=explained_breaks, break_reasons=reasons)
+
+ monkeypatch.setattr(torch, "compile", compile_without_one_graph)
+ monkeypatch.setattr(torch._dynamo, "explain", explain)
+ record = probe.compile_step(case, wrap, inputs, ref)
+ assert (record["compile"], record["graph_breaks"]) == (status, max(explained_breaks, 0)), record
+ [recorded] = record["break_reasons"]
+ assert recorded.startswith(reason), record
+ assert ("Data dependent operator" in recorded) == (not explained_reasons), record
+ assert probe.compile_step(case, wrap, inputs, ref, fullgraph=True)["compile"] == "fail"
+ # a case fullgraph=True captures is ok in both
+ monkeypatch.setattr(torch, "compile", lambda model, fullgraph=False, **kwargs: model)
+ assert probe.compile_step(case, wrap, inputs, ref)["compile"] == "ok"
+ assert probe.compile_step(case, wrap, inputs, ref, fullgraph=True)["compile"] == "ok"
+
+
@pytest.mark.compile_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.