🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs: consolidate correctness policy and contribution guides (#6611)
Dmytro Mishkinaa3326c3c008
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.ymlindex d86a66474..d81c1acce 100644--- a/.github/workflows/stale.yml+++ b/.github/workflows/stale.yml@@ -17,11 +17,10 @@ jobs:steps:- uses: actions/stale@v11with:- stale-pr-message: "This pull request has been quiet for 15 days, so we're marking it stale to keep the queue readable. **Nothing happens automatically — kornia does not close pull requests for inactivity.** The label is a triage signal, and it clears itself as soon as you comment or push. Maintainers can add the `pinned` label to exempt a pull request from the sweep entirely."+ stale-pr-message: "This pull request has been quiet for 15 days, so we're marking it stale to keep the queue readable. **There is no automatic closure for inactivity.** Maintainers may close quiet pull requests at their discretion. The label is a triage signal, and it clears itself as soon as you comment or push. Maintainers can add the `pinned` label to exempt a pull request from the sweep entirely."days-before-pr-stale: 15- # Never close a pull request for inactivity. A quiet pull request is a pull request- # waiting on us at least as often as one waiting on its author, and closing it loses the- # review history that made it cheap to pick back up. -1 disables closing entirely.+ # Never close automatically for inactivity: a quiet PR may be waiting on us.+ # Maintainers retain discretion to close it. -1 disables the bot's closing action.days-before-pr-close: -1stale-pr-label: "stale"exempt-pr-labels: "pinned"diff --git a/AGENTS.md b/AGENTS.mdindex 7edf2d906..5d2ae0afc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,169 +1,111 @@# Agent guide for kornia-This file gives coding agents practical context for working in this repository.+Use this file for execution. [CONTRIBUTING.md](CONTRIBUTING.md) owns contribution and+coding rules; [ROADMAP.md](ROADMAP.md) owns priorities and correctness policy;+[TESTING.md](TESTING.md) owns validation procedures and backend details.-## Project shape+## Start here-kornia is a differentiable computer vision library built on PyTorch. Most code lives in subpackages under `kornia/`; reusable test support lives in `testing/`, not under `tests/`.--Important areas include:--- `kornia/geometry/`: transforms, cameras, epipolar geometry, stereo, and 3D-- `kornia/filters/`: filtering and edge operators-- `kornia/augmentation/`: differentiable augmentation pipelines-- `kornia/feature/` and `kornia/models/`: feature and model implementations-- `kornia/onnx/`: ONNX loading, execution, composition, and export-- `kornia/core/`: shared tensor, module, and ONNX mixins--Import order in `kornia/__init__.py` matters: `filters` and `geometry` are loaded before modules that depend on them. Check for circular imports when changing package exports.+- Read the relevant issue decision and nearby implementation/tests before editing.+ Preserve existing user changes and keep the task focused.+- Library code lives in `kornia/`; reusable test support lives in `testing/`, not `tests/`.+ Check import cycles when changing exports: `kornia/__init__.py` loads `filters` and+ `geometry` before modules that depend on them.+- Search for an existing Kornia operation. Follow nearby shape, batching, dtype/device,+ and TorchScript conventions. Use the [coding standards](CONTRIBUTING.md#coding-standards)+ and [docstring style](CONTRIBUTING.md#docstring-style); public API changes need exports and docs.## Environment and commands-Use Pixi for project tasks and environment selection. The tasks call `uv`, and Python tests run in the repository `.venv` or a versioned `.venv-py*`; do not assume packages in `.pixi` are the versions under test.+Use Pixi. [Setup](CONTRIBUTING.md#developing-kornia) selects `.venv` or `.venv-py*` for+Python dependencies; `.pixi` supplies tools, not the packages under test. Read the+[CUDA installation notes](TESTING.md#environment-and-validation-tasks) before CUDA work.```bash-pixi install-pixi run -e default install-pixi install -e py312-pixi run -e py312 install-pixi install -e py313-pixi run -e py313 install-pixi run -e cuda install-pixi run test-module tests/path/to/test_file.py-pixi run test-module tests/path/to/test_file.py::TestClass::test_method-pixi run test-module tests/path/to/ -k "expression"+pixi run test-module tests/path/to/test_file.py --device=cpu --dtype=float32,float64KORNIA_TEST_OPTIMIZER=inductor pixi run test-module tests/path/to/test_file.py-pixi run test-quick-pixi run test-slow-pixi run lintpixi run pre-commit-allpixi run typecheck-pixi run toml-fmtpixi run doctest-pixi run doctest-weightspixi run -e default build-docs```-The `py312` and `py313` features select isolated `.venv-py312` and `.venv-py313` project environments automatically for install and test tasks.--Select devices and dtypes with pytest options or environment variables:--```bash-pixi run test-module tests/geometry --device=cpu --dtype=float32,float64-KORNIA_TEST_DEVICE=cuda KORNIA_TEST_DTYPE=float32 pixi run test-module tests/geometry-```--Supported fixtures include CPU, CUDA, MPS, and TPU when available, and `float16`, `bfloat16`, `float32`, and `float64`. Run focused checks first and expand them in proportion to the change.--`test-module` forwards its arguments to `pytest`, so a node ID or a `-k` expression narrows a run to a single test.--Use `KORNIA_TEST_RUNSLOW=true` to include slow tests. `KORNIA_TEST_OPTIMIZER=inductor` enables the dynamo and compile tests, which are deselected when the variable is unset; 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 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.+`test-module` forwards pytest node IDs and `-k`. Start focused, then cover affected+callers. Run full pre-commit before presenting a code change as finished; `lint` is+only Ruff. Report what passed and what remains unverified.### Comparing a branch against another revision-kornia is installed in editable mode, so `import kornia` resolves through the editable finder to-the **primary checkout** regardless of the current directory. A measurement script that lives-outside a worktree therefore imports the primary tree even when you run it from the worktree:-`python /tmp/probe.py` puts `/tmp` first on `sys.path`, nothing shadows the editable install, and-an A/B comparison silently measures the same revision twice and reports "no difference".--Run comparison snippets from the worktree root, as stdin or `-c`, never as a file stored-elsewhere. Only then does the leading empty `sys.path` entry -- the working directory -- shadow-the editable install:--```bash-git worktree add /tmp/base-wt <base-revision>-cd /tmp/base-wt && python - <<'EOF'-import kornia-print(kornia.__file__) # must name the worktree, not the primary checkout-EOF-```--Print `kornia.__file__` inside every measurement block and check that it names the tree you-meant. A `cd` into the worktree is not by itself enough, and neither is putting the worktree on-`PYTHONPATH` while the script still lives somewhere else. The same applies to `sys.executable`-when more than one virtualenv is in play: name the interpreter explicitly rather than relying on-`PATH`.--### Precision and device details--- For focused CPU half-precision coverage, add `--dtype=float16,bfloat16` to a `test-module` run. `pixi run test-half` runs the whole CPU test suite.-- The blocking Linux CPU half jobs run one dtype at a time with `--verify-known-failures` and an explicit- `--known-failure-profile=cpu-float16` or `cpu-bfloat16`, with no optimizer or `--runslow`. Focused file, node, and- `-k` runs use `--xfail-known-failures` with the same profile. Profile selection happens before parametrization and- deterministically isolates each node's RNG. Delete a manifest line after a fix, update it after a rename or- reparametrization, and fix or deliberately document a new failure. `pixi run test-half` is unseeded; a failure seen- only there is a test-determinism bug, not a manifest update. See [TESTING.md](TESTING.md) for guarded candidate- recording, fresh-process replay, and manual installation.-- CUDA `float16`/`bfloat16` tests need per-test subprocess isolation; use `pixi run -e cuda test-cuda-half` or pytest's `--isolate-half-precision` option.-- MPS does not support float64 gradcheck. MPS autocast can also change the effective dtype; inspect nearby tests before changing tolerances or skips.-- The blocking MPS job runs `--device=mps --dtype=float32 --xfail-known-failures`. Its exact strict-xfail baseline is `testing/known_failure_xfails/mps_float32.txt`. A fix removes its manifest line; a rename or reparametrization updates the node ID; a new failure is fixed, or gets its own tracking issue named in a manifest comment before being added. The manifest contract requires a full-suite run, without `-k` or a partial path.-- TF32 matmul is disabled by default; `--tf32` enables it. cuDNN convolutions still use PyTorch's TF32 default. Tests marked `tf32` are xfailed at collection unless `--tf32` is passed, and that marker is non-strict, so a default run reports neither their failure nor their recovery.-- `torch.clamp` is not a portable gradient guard: its derivative **at the bound** passes the incoming gradient- through (`1.0`) on torch 2.5.1 and 2.9.1 and returns `0.0` on 2.14.0. Wherever the bound is also the singular- point -- `clamp(min=0).sqrt()`, `clamp(-1, 1).acos()`, `clamp(-1, 1).asin()` -- the clamp bounds the value only,- so the unbounded derivative still reaches the backward pass as `inf` or `nan` on the older half of the supported- range while 2.14 masks it. A floor below the dtype's smallest subnormal is no guard either: `clamp(min=1e-12)`- underflows to `0` in `float16`. Substitute a safe argument into the expression that gets differentiated and take- the value from a `.detach()`ed copy, or from the other arm of a `torch.where`, instead; that is- version-independent by construction. A CPU float32 run on a recent torch does not exercise any of this -- the- 2.5.1 leg is what discriminates. The measurements and the audit of the pattern are in #4229.-- Preserve device and dtype rather than creating implicit CPU or default-dtype tensors. Use the injected `device` and `dtype` fixtures in tests.--## Library preferences--- Search for an existing `kornia` operation before building the same operation from raw PyTorch.-- Follow nearby batching, broadcasting, shape-validation, dtype, and device conventions.-- A `KORNIA_CHECK` message that formats a tensor size or an `int` argument specializes it under a dynamic-shape `torch.compile`, which then compiles a graph per value. Compare sizes with `KORNIA_CHECK_SAME_SIZE`, `KORNIA_CHECK_SIZES` or `KORNIA_CHECK_SHAPE`, or pass the message as `lambda: f"..."`. TorchScript rejects a `lambda`, so a function it compiles formats whole shapes instead, such as `{x.shape}`, which do not specialize. `tests/core/test_check_message_call_sites.py` enforces both and lists the functions TorchScript compiles.-- Use `BaseTester` from `testing.base`, injected `device`/`dtype` fixtures, and `self.assert_close()` for tensor comparisons. Its dtype-specific tolerances are intentional.-- Follow [TESTING.md](TESTING.md) for test mechanisms. Use `self.gradcheck()` for gradient checks and the injected `torch_optimizer` fixture for `torch.compile` coverage. Include smoke, exception, shape/cardinality, numerical, gradient, and compile tests when they apply; not every change needs every kind.-- Write docstrings in the style of [CONTRIBUTING.md](CONTRIBUTING.md#docstring-style): a unique task-word title line, a contract paragraph that starts from the call, `See Also:` with explanations, and shape literals instead of `:math:`. `tests/test_docstring_style.py` checks shape literals in every kornia source file and docs page, and See Also, references and catalogs for the modules listed in `testing/docstring_rollout.py`; `kornia/geometry/depth.py` is the worked example.-- Keep numerical correctness tests self-contained. For expected values produced by an optional reference library, prefer a hardcoded literal plus the small generation snippet and source. Optional-dependency integration tests, including ONNX tests, may still use `pytest.importorskip`.-- For a new algorithm, name the source that defines it, such as a paper or a reference implementation in PyTorch, OpenCV, or scikit-image.-- Do not keep or copy a bug just because the original implementation has it. When a port differs from its reference, decide which behaviour is correct before changing anything: "the reference does it" is not a justification on its own. For example, a non-maxima suppression that keeps positions equal to their window maximum (`>=`), or that re-admits positions once their stronger neighbours are suppressed, is unstable and wrong in principle; kornia keeps strict maxima. When kornia departs from a reference on purpose, say so in the docstring and give the reason.-- Public APIs need type hints, docstrings, and exports.-- `tests/api_surface.json` inventories the public names of stable-core modules; `tests/test_api_surface.py` rejects their removal until the inventory is updated in the same change. Run `tests.test_api_surface.regenerate()` to regenerate it. Keep tracked module keys (use `[]` when removing every name). Every module that declares `__all__` under a recorded package root has its own key; deleting such a module empties its key, and that empty key stays as the record. The `Import Surface` workflow also checks that each inventory removal corresponds to an actual export removal in the same diff. An inventory edit acknowledges an `__all__` removal only for the exact same module and name. For an `__all__` name of a module without its own key, such as a module outside the recorded package roots, add the exact module and name to `tests/api_surface_removals.json`, a JSON object mapping module names to lists of removed names (for example, `{"kornia.feature.dedode": ["DeDoDe"]}`). Only entries newly added relative to the merge base count, and each must match an actual `__all__` removal in that change; an unrelated source edit or a previously recorded acknowledgement does not count. Explicit acknowledgements do not replace updates to existing inventory entries, the deprecation window, or release notes.-- The codebase keeps a 120-character line length and Apache 2.0 source headers. Ruff and `ty` enforce the current style and types.-- JIT-compatible modules have stricter typing constraints. Follow nearby annotations and use `torch.Tensor` directly where TorchScript expects it.-- For non-JIT modules, use `from __future__ import annotations`.-- Avoid new runtime dependencies. If a dependency is genuinely useful, explain why the existing stack is insufficient and consider its install, build, and platform cost.--## Responding to review--- Treat a fix that a reviewer suggests, whether a maintainer, a bot or another agent, as a hypothesis about the cause. Before applying it, check whether kornia already maintains the invariant it protects. For example, `Boxes._valid` marks rows that are not boxes: every indexed read and write carries it and every export zeroes those rows, so rows that must never export as boxes do not need a separate count that each write path would have to keep in sync.-- If two review rounds in a row report a regression that the previous fix round introduced, stop patching individual cases. State the invariant, find the code responsible for keeping it, and redesign before pushing another fix, reverting earlier rounds when that is simpler.--## Documentation and generated examples--- A user-visible change adds a `changelog.d/<PR>.<type>.md` fragment (`added`, `fixed`, or `breaking`), not an edit to `CHANGELOG.md`. See [changelog.d/README.md](changelog.d/README.md) for naming before a PR exists and the release workflow. A breaking change says what used to happen as well as what happens now. Internal changes may omit a fragment with an explanation in the PR and the `no-changelog` label. Release PRs also use that label when consuming fragments. Only release PRs assemble and consume fragments.-- Add every new public class or function to the corresponding `docs/source/*.rst` page so it appears in the rendered API reference.-- A pull request description goes in the pull request body, never in a committed file such as `PR.md`. Fill in every section of the [pull request template](.github/pull_request_template.md), including "Which part was done by a human, if any?": state plainly what the user actually did in the session (for example, `"None — @<user> asked to fix #NNNN; AI did the rest"`, or the specific diagnosis, design, or edits the user provided) rather than repeating what the agent did in a faux-human `"Used <Agent> to..."` voice.-- Every pull request description, issue body, comment, and review posted to GitHub by an agent on a user's behalf must end with the line:+Run comparison snippets from each worktree root as stdin or `-c`, using an explicit+interpreter. Print and verify `kornia.__file__` and `sys.executable` inside each probe:+an external script can silently import the primary editable checkout. Follow the+[comparison procedure](TESTING.md#comparing-a-branch-against-another-revision).++## Read when the change touches++| Area | Required guidance/action |+| --- | --- |+| Numerical or gradient tests | Use `BaseTester`, injected device/dtype, `self.assert_close()`, and `self.gradcheck()`; use `torch_optimizer` for compile coverage. See [Test Structure](TESTING.md#test-structure). Use independent hardcoded expected literals plus their generation snippet/source, not a runtime optional reference dependency. |+| Singular gradient guards | `clamp` alone is not portable; differentiate safe arguments and test the older supported Torch leg. See [gradient guards](TESTING.md#gradient-guards-across-pytorch-versions), including the float16-underflow case. |+| CPU/CUDA half precision | Follow the [half-precision profiles](TESTING.md#7-half-precision-dtypes-float16--bfloat16); CUDA needs per-test subprocess isolation. Fix/remove or rename manifest entries with the corresponding test changes. |+| MPS or TF32 | Read [MPS limitations](TESTING.md#8-mps-apple-silicon-limitations) and [TF32](TESTING.md#1-tf32-tensorfloat-32-precision) before adjusting skips/tolerances. The MPS manifest is a full-suite contract, not a focused-run baseline. |+| Checks or dynamic shapes | Avoid specializing sizes in error strings; follow [Dynamic-shape check messages](TESTING.md#dynamic-shape-check-messages), including its TorchScript exception. |+| Public exports | Follow [Public API inventory](TESTING.md#public-api-inventory); exact removal acknowledgements do not replace deprecation or release notes. |+| Compile or ONNX | Run the [compile](TESTING.md#torchcompile-conformance-5819) and [ONNX](TESTING.md#onnx-conformance-5819) promised-package selections for touched packages and their importers. Inspect the ONNX subsystem/mixins before export changes and verify runtime as well as graph construction. |+| Performance | Follow [benchmarks/README.md](benchmarks/README.md), use public APIs and shared helpers, and benchmark base and branch on the same workloads. |++## Correctness triage and fixes++Apply [Correctness and backend support](ROADMAP.md#correctness-and-backend-support) in order:++1. Check the contract and equivalent plain-PyTorch operation where applicable. Classify+ the report: math/semantics, numerical formulation, upstream behavior, or no defect.+2. Check scope and existing solutions before coding. Stop for excluded inputs until an+ explicit scope decision; demonstrate benefit over existing options before adding a solver.+3. Expected autocast precision changes and SVD backward limitations at repeated singular+ values are not by themselves evidence of an upstream defect. For suspected upstream+ failures, test latest stable and available next PyTorch on the affected backend;+ record gaps. Follow the roadmap's fixed-upstream rule before adding a workaround.+4. Name the workflow, inputs, dtype/device, and grad/autocast mode. Separate synthetic+ proof, real-data exposure, and downstream impact; do not invent user frequency.+5. Pin independent expected results in focused tests (`test_convention_*` for conventions).+ Use `self.assert_close()`'s dtype tolerances or justify an override. Report worse+ downstream results and unresolved convention choices for maintainer judgment.+6. Record branch rationale and workaround scope, retirement, and a short measured-cost+ summary beside the code; put detailed results and tradeoffs in the PR and accepted+ behavior changes in release notes. State+ the outcome explicitly, including a supported alternative or no change.++## Review and completion++- Treat a reviewer's suggested fix as a hypothesis. Check the existing invariant first:+ `Boxes._valid`, for example, already follows indexed reads/writes and zeros invalid+ exports; adding a separate count can create another synchronization problem.+- If two review rounds in a row find regressions introduced by the preceding fix,+ stop patching cases. State the invariant and redesign the responsible code before+ pushing again, reverting previous fixes when simpler.+- Follow the [PR and AI disclosure rules](CONTRIBUTING.md#pull-request), including the+ accurate human-work statement. End agent-authored GitHub posts with the literal form:`Posted on behalf of @<github-handle> by <Agent> (<actual model>).`- Write the user's GitHub handle and the actual agent and model you are running as, never a copied literal or a generic tool footer (`Generated with ...`, `Co-Authored-By:`).-- Some modules document a known defect inline and link its tracking issue; `grep -rn "github.com/kornia/kornia/issues/" kornia/` finds them. That prose is part of the fix's blast radius: **before merging a change that closes one of those issues, run `grep -rnE "#NNNN|issues/NNNN" kornia/ tests/`.** Match the issue number rather than a name or a phrase — the wording varies across `Tracked in #NNNN`, a lowercase `tracked in` clause, a `Note:` block, a runtime error message, an `xfail` `reason=`, a plain comment and a test-name suffix (`test_wart_*_<issue>` and `test_convention_*_<issue>`, where that convention was followed), and a rendered link label can disagree with the URL beneath it. The `#`/`issues/` anchors keep the pattern off float literals. A surviving hit in `kornia/` means the change is incomplete. Hits in `tests/` are the pins that record the documented behavior; each has to be re-checked in the same change — a now-XPASSing strict `xfail` dropped, a wart assertion inverted — but a pin goes on naming its issue afterwards, so a hit there is not by itself a defect. Not every documented issue has a pin, so an empty `tests/` result is an answer rather than a failed search.-- When adding a feature detector or descriptor, update the `responses` list in `docs/generate_examples.py` and add the matching branch that renders its heatmap or score visualization. Follow the existing `DISK`, `ALIKED`, and `XFeat` examples and preserve the expected `(B, 3, H, W)` image shapes.--## Benchmarks--Follow the methodology contract and new-benchmark checklist in [benchmarks/README.md](benchmarks/README.md), using the helpers in `benchmarks/common.py`. Benchmark public kornia APIs rather than embedding a replacement implementation. For performance changes, run the same benchmark on the relevant base revision and changed branch.--## ONNX work--ONNX support is a real subsystem, not a generic export afterthought. Inspect `kornia/onnx/`, its mixins in `kornia/core/`, and existing ONNX tests before changing export behavior. Development uses the optional `onnx`, `onnxruntime`, and `onnxscript` packages. Test both graph construction/export and runtime behavior when the change affects both.--The stable-core operators the survey records as exporting are promised (#5819): `tests/onnx/test_conformance.py` exports each with the dynamo exporter and the legacy one and compares onnxruntime with eager. It is opt-in, `pixi run test-module tests/onnx/test_conformance.py --onnx-conformance=<package>|all`; run it for the packages a change touches and the packages that import them (`git diff --name-only origin/main... | python .github/scripts/conformance_packages.py onnx` prints that selection), and see [TESTING.md](TESTING.md) for its known-failure manifests.+- Base the PR's human-involvement section on the actual interaction and its outcome,+ updating it after scope or review decisions. Name substantive steering, diagnosis,+ design decisions, and supervision, even without human file edits. Distinguish reviews+ the human arranged with another model from agent-initiated checks and personal human+ verification; credit the model for its findings and tests. If the human only requested+ the task or said "follow the reviews", report no substantive human technical contribution+ and describe that limited role. Do not infer human review or testing from approval alone.+- Apply the [changelog rules](changelog.d/README.md), register public APIs in the matching+ docs page, and update detector/descriptor examples as described in+ [Contributing to Documentation](CONTRIBUTING.md#contributing-to-documentation).+- Before closing an issue, search its number through code/tests and repair stale defect+ prose and wart assertions; follow [Closing a documented defect](CONTRIBUTING.md#closing-a-documented-defect).+- Keep logs, measurements, plots, scratch data, and task reports outside the library diff.+ Inspect the complete PR file list before committing or pushing.## Helping users diagnose problems-Start with a minimal reproduction and the narrowest relevant test. Do not claim a failure is pre-existing until you have compared against the relevant base revision safely.--Ask only for environment details that help the diagnosis: kornia, PyTorch, and Python versions; OS family; device backend; CUDA availability/version; and GPU model when relevant. Prefer the same privacy-conscious command used by the bug template:--```bash-python -W ignore -c "import kornia, platform, sys, torch; gpu=torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'none'; backend=torch.version.cuda or getattr(torch.version, 'hip', None); print(f'kornia {kornia.__version__} | torch {torch.__version__} | python {sys.version.split()[0]} | OS {platform.platform()} | CUDA/ROCm {backend} (available={torch.cuda.is_available()}, GPU={gpu}) | MPS={torch.backends.mps.is_available()}')"-```--Before asking a user to share broader diagnostic output, tell them to preview and redact it. Do not request usernames, home or project paths, environment variables, tokens, internal hostnames, or names of private data and models.+Start with a minimal reproduction and the narrowest test. Compare with the relevant+base before claiming a failure is pre-existing. Request only the relevant version,+OS, and device details from [Diagnosing reported problems](TESTING.md#diagnosing-reported-problems).+Ask users to preview/redact broader output; do not request private paths, usernames,+environment variables, tokens, internal hostnames, or private data/model names.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5684cf404..1b9284caa 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -13,198 +13,91 @@ Above all, we ask you to care. Good work done with care makes the world better;The rest of this guide contains practical and technical guidance so nobody has to guess. If you have experience with open source, you probably already know most of it.+Coding agents should also follow the [execution checklist in AGENTS.md](AGENTS.md).+## Practical guidelines- Search existing issues and pull requests before starting. Focused fixes and documentation improvements are welcome as pull requests. For a new public API, a behavior change, or a large piece of work, an early issue or discussion can save everyone time. A conversation helps us align; it is not a promise that somebody will review or merge the result.- You do not need to ask before working on an issue that is not reserved. Say on the issue that you are taking it, then open a pull request, as a draft if you still have questions. If a claim has no pull request after two weeks, anyone may take the issue; say so on the issue when you do.- Some issues say they are reserved for a maintainer implementation, and some already have an open pull request. Please comment on the issue or on that pull request instead of opening another one.-- Open an issue with a reproducer before fixing a numerical edge case that realistic inputs do not reach, such as half-precision overflow at magnitudes far beyond image or coordinate ranges, or a matrix scaled by `1e15`. Each such fix costs a full review across dtypes and devices and adds a promotion path to maintain, so we decide first whether it is worth that cost. One issue can list several cases. Wrong results on realistic inputs are welcome directly as pull requests.+- Follow [Correctness and backend support](ROADMAP.md#correctness-and-backend-support) before implementing a numerical fix or backend workaround. Repairs within the supported contract are welcome directly as pull requests, subject to existing issue reservations. Do not add special paths solely for synthetic extremes: half-precision overflow far beyond image/coordinate ranges, `1e20` float32 image values or pixel coordinates, or a matrix scaled by `1e15`. These are examples, not universal magnitude cutoffs. First obtain an explicit maintainer scope decision on an issue with a concrete application and reproducer. A failing synthetic test alone does not justify expanding support.- Kornia functions take floating-point tensors, and images are floats in `[0, 1]` (see [Conventions & Pitfalls](https://kornia.readthedocs.io/en/latest/get-started/conventions.html)). Integer input is not a goal: a few cheap, scale-free image filters accept it, and we do not accept pull requests that add integer-input support anywhere else, especially for `int8` and other narrow integer types. If a function misbehaves on an integer tensor, convert the input to float first.- Check the part you changed and tell us what you ran. A bug fix is easier to trust when it includes a test that fails without the fix. Numerical work is easier to review when expected values come from a reference implementation, a paper, or a mathematical invariant.- Look for an existing `kornia` utility before adding another implementation. Keep changes focused, follow nearby code, and update the documentation when public behavior changes.- Read your own contribution and stay part of the conversation about it. You do not need perfect English or an immediate answer; we care that questions and technical concerns are treated seriously.- If you are contributing as part of an application, remember that we read the work and review conversation, not pull request counts.- Keep project decisions and review discussions in public GitHub issues, discussions, or pull requests so others can find and learn from them.-- Pull requests are marked stale after 15 quiet days to keep the queue usable. **We do not close pull requests for inactivity** — the label is a triage signal and nothing else, and it clears itself as soon as you comment or push. Maintainers can add `pinned` when a pull request should be exempt from the sweep entirely. A quiet pull request is often waiting on us, so take the label as a nudge to ping us, not as a deadline.+- Review and closure decisions belong to maintainers; see [Review Process](#review-process).## Ways to Contribute-1. **Ask/Answer questions:**- - [GitHub Discussions](https://github.com/kornia/kornia/discussions)- - `#kornia` tag in [PyTorch Discuss](https://discuss.pytorch.org)- - [Discord](https://discord.gg/HfnywwpBnD)- - Don't use GitHub issues for Q&A.--2. **Report bugs** via [GitHub issues](https://github.com/kornia/kornia/issues):- - Search for existing issues first.- - Use the bug report template.- - Include: clear description, reproduction steps, package versions, and code sample.--3. **Fix bugs or add features:**- - Check [help wanted issues](https://github.com/kornia/kornia/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22help%20wanted%22) for starting points.- - Follow the [development setup](#developing-kornia) below.- - See the [Pull Request](#pull-request) section for practical guidance.--4. **Donate resources:**- - [Open Collective](https://opencollective.com/kornia)- - [GitHub Sponsors](https://github.com/sponsors/kornia)- - We're looking for CUDA server donations for testing.+- Ask or answer questions in [GitHub Discussions](https://github.com/kornia/kornia/discussions),+ [PyTorch Discuss](https://discuss.pytorch.org) (`#kornia`), or [Discord](https://discord.gg/HfnywwpBnD).+ Use issues for bug reports rather than Q&A.+- Report bugs through the [issue templates](https://github.com/kornia/kornia/issues/new/choose),+ with a minimal reproduction and the requested environment details. Follow the+ [privacy-conscious diagnostic guidance](TESTING.md#diagnosing-reported-problems).+- Find work in the [roadmap](ROADMAP.md#areas-seeking-contributors) and+ [help wanted issues](https://github.com/kornia/kornia/labels/help%20wanted); check reservations first.+- Support the project through [Open Collective](https://opencollective.com/kornia),+ [GitHub Sponsors](https://github.com/sponsors/kornia), or CUDA testing resources.## Developing kornia### Setup-1. **Fork** the [repository](https://github.com/kornia/kornia/fork)--2. **Clone your fork** and add upstream:- ```bash- $ git clone [email protected]:<your GitHub username>/kornia.git- $ cd kornia- $ git remote add upstream https://github.com/kornia/kornia.git- ```--3. **Create a branch** (don't work on `main`):- ```bash- git checkout upstream/main -b feat/foo_feature- # or- git checkout upstream/main -b fix/bar_bug- ```--4. **Development environment**-- We use [pixi](https://pixi.sh) for package and environment management.-- **Install Pixi:**-- ```bash- # On Linux/macOS- curl -fsSL https://pixi.sh/install.sh | bash-- # On Windows (PowerShell)- irm https://pixi.sh/install.ps1 | iex-- # Or using conda/mamba- conda install -c conda-forge pixi- ```-- **Set up the development environment:**-- ```bash- # Create the default Pixi environment, then install development dependencies- pixi install- pixi run -e default install-- # For specific Python versions- pixi install -e py312 # Python 3.12- pixi run -e py312 install- pixi install -e py313 # Python 3.13- pixi run -e py313 install-- # For CUDA development- pixi run -e cuda install- ```-- The `py312` and `py313` environments use isolated `.venv-py312` and `.venv-py313` project environments automatically.-- **Available tasks:**-- kornia provides several tasks via pixi for common development workflows:-- ```bash- # Installation- pixi run -e default install # Install dev dependencies- pixi run -e default install-docs # Install dev + docs dependencies+Fork [kornia](https://github.com/kornia/kornia/fork), clone your fork, and branch from upstream:++```bash+git clone [email protected]:<your GitHub username>/kornia.git+cd kornia+git remote add upstream https://github.com/kornia/kornia.git+git fetch upstream+git switch -c fix/my-fix upstream/main+```++Install [Pixi](https://pixi.sh), then set up the project environment:++```bash+pixi install+pixi run -e default install+# Optional versioned environments+pixi install -e py312+pixi run -e py312 install+pixi install -e py313+pixi run -e py313 install+# CUDA development+pixi run -e cuda install+```++Python dependencies under test live in `.venv` or `.venv-py*`, not `.pixi`.+Before CUDA work, read the [environment and CUDA installation details](TESTING.md#environment-and-validation-tasks),+including resynchronization, Windows wheel replacement, and availability checks.- # Testing- pixi run test # Run tests (configure via KORNIA_TEST_* env vars)- pixi run test-f32 # Run tests with float32- pixi run test-f64 # Run tests with float64- pixi run test-slow # Run slow tests- pixi run test-quick # Run quick tests (same as `pixi run test`)- pixi run test-module tests/<path> # Run a focused test path- pixi run test-half # Run CPU float16/bfloat16 tests-- # CUDA testing (requires cuda environment)- pixi run -e cuda test-cuda # Run tests on CUDA- pixi run -e cuda test-cuda-f32 # Run CUDA tests with float32- pixi run -e cuda test-cuda-f64 # Run CUDA tests with float64- pixi run -e cuda test-cuda-half # Run isolated CUDA float16/bfloat16 tests-- # Code quality- pixi run lint # Run ruff linting- pixi run pre-commit-all # Run all repository pre-commit checks- pixi run pre-commit-install # Install the pre-commit Git hook- pixi run typecheck # Run type checking with ty- pixi run doctest # Run doctests-- # Documentation- pixi run -e default build-docs # Build documentation-- # Utilities- pixi run clean # Clean Python cache files- ```-- **Environment variables for tests:**-- Tests can be configured using environment variables:-- ```bash- # Set device (cpu, cuda, mps, tpu)- export KORNIA_TEST_DEVICE=cuda-- # Set dtype (float32, float64, float16, bfloat16)- export KORNIA_TEST_DTYPE=float32-- # Run slow tests- export KORNIA_TEST_RUNSLOW=true-- # Then run tests- pixi run test- ```-- **Dependencies:** Defined in `pyproject.toml`. Update it and run `pixi run -e default install`.-- **CUDA:** Run `pixi run -e cuda install` to install the locked PyTorch as a CUDA build into the project `.venv`,- which is also used by `pixi run -e cuda test-cuda`. PyPI's Linux wheels are already CUDA builds, so on Linux the- task only syncs the lock, reinstalling every package so that removing a stale wheel cannot take files a locked- wheel needs. PyPI's Windows wheels are CPU-only, so on Windows the task then replaces torch with the same version- from the PyTorch CUDA index; a lock update to a new PyTorch has to update that version and index in `pixi.toml`- and the index in `pyproject.toml` too. Pixi's `.pixi/envs/cuda` supplies the tools, not the Python dependencies- under test. Commands run with `-e cuda` do not synchronize `.venv` automatically, so re-run the CUDA install task- after a dependency or lock change. On Windows this is what preserves the CUDA build, and a default-environment- command that synchronizes `.venv` replaces it, so re-run the task after one of those too. For focused CUDA tests,- use `pixi run -e cuda test-module tests/<path> --device=cuda`.-- The locked build needs an NVIDIA driver from the R580 branch or newer and a Turing or newer GPU. Check- `torch.cuda.is_available()` after installing: when it is false, a `--device=cuda` run skips its tests and still- exits 0.--5. **Develop and test:**-- Create test cases for your code. Run tests with:- ```bash- # Run all tests- pixi run test-- # Run specific test file- pixi run test-module tests/<TEST_TO_RUN>.py+### Development Workflow- # For specific test with pytest options- pixi run test-module tests/<TEST_TO_RUN>.py --dtype=float32,float64 --device=all- ```+Keep each PR focused. Search for existing Kornia operations, follow nearby contracts,+and run focused validation before broad checks:- **dtype options:** `bfloat16`, `float16`, `float32`, `float64`, `all`- **device options:** `cpu`, `cuda`, `tpu`, `mps`, `all`+```bash+pixi run test-module tests/path/to/test_file.py --device=cpu --dtype=float32,float64+pixi run pre-commit-all+pixi run typecheck+```- We use [pre-commit](https://pre-commit.com) for code quality. Install its Git hook with `pixi run pre-commit-install`. See [coding standards](#coding-standards) below.+Run full pre-commit checks before presenting a code change as finished; `pixi run lint`+checks only Ruff. [TESTING.md](TESTING.md) owns test selection, device/dtype profiles,+compile/ONNX coverage, doctests, and revision comparisons. Performance changes use the+same benchmark on base and branch under [the benchmark methodology](benchmarks/README.md).## Contributing to Documentation-1. Set up your development environment (see [above](#developing-kornia))-2. Edit files in `docs/`-3. Build docs: `pixi run -e default build-docs`-4. Preview: `open docs/build/html/index.html`-5. Submit a PR following the [Pull Request](#pull-request) guidelines+Edit `docs/`, build with `pixi run -e default build-docs`, and preview+`docs/build/html/index.html`. Read the Docs treats Sphinx warnings as failures and uses+the locked docs dependencies. Public classes/functions must appear in the corresponding+`docs/source/*.rst` API page. For a new feature detector or descriptor, also update the+`responses` list and matching visualization branch in `docs/generate_examples.py`,+following DISK/ALIKED/XFeat and preserving `(B, 3, H, W)` images.### Docstring style@@ -221,245 +114,88 @@ A docstring is how a reader, human or agent, decides which function to call, so- **Module docstrings** open with a title line, then the conventions the module's functions share, then "Which function to use", grouped by task, one line each, naming every entry of the `__all__` of the namespace users import from as a role (`` :func:`name` ``) or a literal (``` ``name`` ```). A namespace without `__all__` (`kornia.geometry`, `kornia.geometry.transform`) catalogs its subpackages and main entry points instead; a defining file without `__all__` gets no catalog.- **Shapes** are literals such as ``` ``(B, 1, H, W)`` ```. Keep `:math:` for formulas, and for a tuple that is a value, such as a point's `` :math:`(X, Y, Z)` ``; write a value range as an interval, `` :math:`[0, 1]` ``.-What `tests/test_docstring_style.py` checks:--- every package of `kornia` is assigned to in scope or excluded (global);-- a converted module has no function or class, exported by an `__all__` or documented on a docs page, without a docstring;-- each public function and class of a converted module has a `See Also:` whose entries carry an explanation and name a kornia object, with no self-link or private target; an exception needs a non-empty reason, and an ``Alias of :func:`target`.`` or ``Deprecated: use :func:`target`.`` title line replaces the `See Also:`;-- every Python-domain object role (`:func:`, `:class:`, `:meth:`, `:attr:`, `:data:`, `:const:`, `:exc:`, `:obj:`) in a converted object's docstring, and in those of the methods, properties and attributes autodoc documents under a converted class, resolves as Sphinx resolves it. It must name either an object registered by the `.rst` pages under `docs/source`, or a torch, Python or NumPy object in the cached intersphinx inventories (`docs/source/_intersphinx`). Registered objects include the data attributes autodoc documents: enum members and dataclass fields under `:undoc-members:`, and variables with a `#:` comment or a docstring. An intersphinx object must be of a type the role links to: a function for `:func:`, a method for `:meth:`, an attribute or property for `:attr:`, and nothing for `:const:`. Only `:func:` and `:meth:` drop a trailing `()`. Roles in a catalog module docstring must import;-- no `kornia/**/*.py` file or `docs/source` page writes a shape tuple as `:math:`, comments included (global); a tuple that reads as a shape but is a value is listed with what it is in `MATH_NON_SHAPES` (`testing/docstring_rollout.py`), and an entry that no longer occurs fails;-- a catalog namespace's module docstring names every export of its `__all__` inside a role or a double-backtick literal, where a qualified name must be a path to that export (`torch.nn.functional.normalize` does not catalog `kornia.enhance.normalize`); the same word in plain prose or in single backticks does not count.--Read the Docs builds with `fail_on_warning: true` (`readthedocs.yml`) and the docs dependencies pinned in `uv.lock`, the same versions as `pixi run build-docs`, so a Sphinx warning fails the docs check. A module joins these checks when it is added to the lists in `testing/docstring_rollout.py`: `DOCSTRING_MODULES` (defining-module prefixes: `See Also:` and references) and `CATALOG_NAMESPACES` (namespaces whose `__all__` the module docstring must name). An object that needs no `See Also:` goes into `SEE_ALSO_EXCEPTIONS` with a reason. The package inventory is `IN_SCOPE_PACKAGES` and `EXCLUDED_PACKAGES`. The helpers are in `testing/docstring_style.py`; its `sphinx_registry` raises on an autodoc option it does not model, so a docs page that adds one (`:no-index:`, `:exclude-members:`, `:inherited-members:`) needs the registry taught first.+Enforcement, rollout tables, and reference-resolution rules are in [Docstring checks](TESTING.md#docstring-checks).## Coding Standards-- **Write small incremental changes:**- - Commit small, logical changes- - Write clear commit messages- - Avoid large files+- Use existing Kornia operations and nearby batching, broadcasting, shape, dtype, and device conventions.+ Preserve the caller's dtype/device; do not create implicit CPU/default-dtype tensors.+- Public APIs need annotated inputs/outputs, docstrings, exports, and rendered API entries.+ Use `torch.Tensor` and `torch.nn.Module` directly where practical; follow TorchScript's+ stricter types in scripted modules. Non-JIT modules use `from __future__ import annotations`.+- Keep 120-character lines, Apache 2.0 source headers, and English comments that explain why.+ Ruff and `ty` enforce style and types. Prefer clear code; profile before optimizing.+ Validate autograd, aliasing, and compile behavior before introducing in-place operations.+- For new algorithms, name a defining paper or reference implementation. Do not copy a+ reference's bug: decide the intended behavior and document deliberate departures.+ For example, Kornia's non-maxima suppression keeps strict maxima.+- Avoid new runtime dependencies. Explain why the existing stack is insufficient and+ consider install, build, and platform costs before proposing one.+- Follow [the stability policy](https://kornia.readthedocs.io/en/latest/get-started/stability.html)+ for API changes and [Public API inventory](TESTING.md#public-api-inventory) for export removals.+ Inventory acknowledgements do not replace deprecation or release notes.+- Follow [Test Structure](TESTING.md#test-structure) and the relevant device/precision guidance+ for tests, and [Dynamic-shape check messages](TESTING.md#dynamic-shape-check-messages) when adding validation.-- **Add tests:**- - Write unit tests for each functionality- - Use helpers from [testing/](./testing/)- - Put test utilities (not tests or fixtures) in `testing/`-- ```python- from testing.base import BaseTester--- class TestMyFunction(BaseTester):- # To compare the actual and expected tensors use `self.assert_close(...)`-- def test_smoke(self, device, dtype):- # test the function with different parameters arguments, to check if the function at least runs with all the- # arguments allowed.- pass-- def test_exception(self, device, dtype):- # tests the exceptions which can occur on your function-- # example of how to properly test your exceptions- # with pytest.raises(<raised Error>) as errinfo:- # your_function(<set of parameters that raise the error>)- # assert '<msg of error>' in str(errinfo)-- pass-- def test_cardinality(self, device, dtype):- # test if with different parameters the shape of the output is the expected- pass-- def test_feature_foo(self, device, dtype):- # test basic functionality- pass-- def test_feature_bar(self, device, dtype):- # test another functionality- pass-- def test_gradcheck(self, device):- # test the functionality gradients- # Uses `self.gradcheck(...)`- pass-- def test_dynamo(self, device, dtype, torch_optimizer):- # test the functionality using dynamo optimizer-- # Example of how to properly test your function for dynamo- # inputs = (...)- # op = your_function- # op_optimized = torch_optimizer(op)- # self.assert_close(op(inputs), op_optimized(inputs))-- pass- ```--- **Test coverage:** Cover different devices, dtypes, and batch sizes. Use `--dtype` and `--device` pytest arguments to generate test combinations:-- ```python- import pytest--- @pytest.mark.parametrize("batch_size", [1, 2, 5])- def test_smoke(batch_size, device, dtype):- x = torch.rand(batch_size, 2, 3, device=device, dtype=dtype)- assert x.shape == (batch_size, 2, 3)- ```--- **Type hints** (Python >= 3.11):- - Use typing when it improves readability- - **Use `torch.Tensor` directly** for type hints (preferred) or import from `kornia.core` for backward compatibility- - Use `torch.nn.Module` directly for module classes (preferred) or import from `kornia.core` for backward compatibility- - For non-JIT modules, use `from __future__ import annotations`- - **Always** type function inputs and outputs:- - Run type checking with `pixi run typecheck` (uses `ty`)- ```python- from __future__ import annotations- import torch-- def homography_warp(- patch_src: torch.Tensor,- dst_homo_src: torch.Tensor,- dsize: tuple[int, int],- mode: str = 'bilinear',- padding_mode: str = 'zeros'- ) -> torch.Tensor:- ```-- For module classes:- ```python- from __future__ import annotations- import torch.nn as nn--- class MyModule(nn.Module):- def forward(self, x: torch.Tensor) -> torch.Tensor:- return x- ```--- **Code style:**- - Follow [PEP8](https://www.python.org/dev/peps/pep-0008/)- - Use f-strings: [PEP 498](https://peps.python.org/pep-0498/)- - Line length: 120 characters- - Write comments in English so they are useful to the whole community- - Prefer comments that explain why; remove comments that merely repeat the code or no longer match it- - W504 (line break after binary operator) is sometimes acceptable. Example:-- ```python- determinant = A[:, :, 0:1, 0:1] * A[:, :, 1:2, 1:2] -- A[:, :, 0:1, 1:2] * A[:, :, 1:2, 0:1])- ```--- **Dependencies:** Avoid adding runtime dependencies. If one is useful, explain why existing dependencies are not enough and discuss the trade-off first.--## Best Practices--This section provides guidance for contributing to kornia, with a focus on Python and PyTorch best practices, performance, and maintainability.--### Before You Start--1. **Start Small**: If you're new to the project, a small bug fix or documentation improvement is a good way to learn the codebase and contribution process.--2. **Understand the Codebase**: Take time to explore existing code patterns, architecture, and conventions before implementing new features.--3. **Review Existing Utilities**: Before implementing new functionality, search the codebase for existing utilities in `kornia`.--### Development Workflow+### Changelog entries-1. **Keep PRs Focused**: Each PR should address a single concern. If you're working on multiple features, create separate PRs for each.+User-visible changes need a fragment; internal changes may explain their omission and+use `no-changelog`. Follow [the fragment guide](changelog.d/README.md) for names, types,+pre-PR filenames, and release handling. Only release PRs assemble `CHANGELOG.md`.-2. **Test Locally**: Run the checks that are relevant to your change:- ```bash- pixi run lint # Run the Ruff hooks- pixi run pre-commit-all # Run the full repository checks- pixi run test # Run all tests- pixi run typecheck # Verify type checking- ```+### Closing a documented defect-3. **Update Documentation**: When adding new features or changing behavior, update docstrings for public APIs. For documentation contributions, see [Contributing to Documentation](#contributing-to-documentation).+Before merging a fix that closes an issue, search its number in references and test-name+suffixes (replace `NNNN` with the issue number):-### Changelog entries+```bash+grep -rnE '(#|issues/)NNNN([^0-9]|$)|test_[[:alnum:]_]*_NNNN([^0-9]|$)' kornia/ tests/+```-For a user-visible change, add a short Markdown file such as `changelog.d/1234.fixed.md`,-where `1234` is the PR number (not an issue number). Use `added`, `fixed`, or `breaking` for the type.-Write what changes for the user; breaking changes must describe the old and new behavior.-Only release PRs edit `CHANGELOG.md`: separate files prevent unrelated PRs-from conflicting on the same lines.--If the PR number is not known yet, use a unique name such as `+fix-camera-shape.fixed.md`-and rename it to the PR number before merging. Internal refactors, tests, and CI-only changes can omit-an entry; explain why in the PR description and ask a maintainer to apply `no-changelog`.-CI still validates fragment names and rendering when this label is present.--Run `pixi run changelog-preview` to preview the notes without changing any files.-See [the fragment guide](changelog.d/README.md) for examples and release instructions.--### Code Quality--1. **Performance Considerations**:- - Prefer in-place operations when possible (e.g., `tensor.add_(other)` vs `tensor = tensor.add(other)`)- - Use tensor views and slicing instead of copying when possible- - Leverage PyTorch's vectorized operations over Python loops- - Profile before optimizing (use `torch.profiler` or `cProfile`)- - Consider memory efficiency for large tensors (use appropriate dtypes, avoid unnecessary copies)- - Use `torch.jit.script` or `torch.compile` for performance-critical paths when appropriate--2. **Code Clarity**:- - Use descriptive variable and function names that convey intent- - Keep functions focused and single-purpose- - Prefer clear code over comments; when comments are needed, explain "why" not "what"- - Avoid over-engineering; start simple and refactor when needed--3. **Tensor Operations**:- - Use `kornia` utilities instead of reimplementing common operations- - Ensure operations are device-agnostic (work on CPU, CUDA, MPS, etc.)- - Support multiple dtypes (float32, float64, float16, bfloat16) when applicable- - Handle batched and non-batched inputs consistently--### Testing Best Practices--- Write tests for happy paths, error cases, edge conditions, boundary conditions, and integration scenarios-- Use `BaseTester` from `testing.base` for consistent test structure (see [Coding Standards](#coding-standards) for examples)-- Test across different devices and dtypes using pytest parametrization (see [Coding Standards](#coding-standards) for examples)-- Make tests deterministic, fast, and independent-- Use descriptive test names; test both forward pass and gradients when applicable+This includes names such as `test_wart_example_NNNN` without matching bare numerical constants.+Check every hit: stale defect prose+in docstrings or errors must be corrected, strict xfails removed when fixed, and wart+assertions updated. Tests may keep the issue number to record the regression. Search+by number, not wording; a link label and its URL can disagree. No test hits is a valid+result, not a reason to invent coverage. See the test-name conventions in nearby files.-### Review Process+## Pull Request-- Review your own PR first: check for typos and formatting, run relevant tests, and update affected documentation-- Respond to review feedback when you can-- Be open to feedback and explain your decisions when questioned-- Remember that review is done by people with limited time and may not happen quickly-- Pull requests are reviewed by maintainers. Please do not post reviews or approvals on other contributors' pull requests; if you found a problem in one, describe it on the linked issue instead+Fill in the [PR template](.github/pull_request_template.md) in the PR body, never a committed+`PR.md`. Describe the behavior, evidence, compatibility/performance tradeoffs, and checks+run or unverified. Include a failing-before regression when appropriate and explain the+independent expected result for numerical work. Keep generated logs, benchmark output,+and investigation notes outside the library diff.### Working with AI-- AI tools are welcome. Read their output, check it in the same way you would check your own work, and state in the pull request which part was done by a human, if any, and which by AI.-- Useful details include whether you diagnosed the problem, designed the approach, edited the diff, or checked the result yourself, or whether an agent did the whole task from a prompt. We do not need a percentage.--### Communication+AI tools are welcome. Check their output as you would your own and describe the actual+human contribution and its effect: steering, diagnosis, design decisions, edits, review,+or supervision. Arranging another model's review is distinct from personally verifying+the result; credit AI-generated findings and tests to the AI. Merely requesting the task+or directing an agent to follow reviews can mean zero substantive human technical+contribution. The PR template asks for this distinction, not a percentage or a chat transcript.-- Write a clear, concise pull request description-- Link related issues or discussions when they exist-- Ask questions in Discord, GitHub Discussions, or pull request comments when useful+Every agent-authored GitHub PR description, issue, comment, and review on a user's behalf+ends with `Posted on behalf of @<github-handle> by <Agent> (<actual model>).` Use the actual+handle, agent, and model rather than a generic generated-by footer.-## Pull Request--Fill in the [pull request template](.github/pull_request_template.md) with enough context for another person to understand the change. Link related issues or discussions when they exist, say what you checked, and state which part was done by a human, if any, and which by AI. The description goes in the pull request itself; do not commit it to the repository as a file such as `PR.md`.--For bug fixes, a regression test that fails before the fix is especially helpful. For numerical or geometry changes, say where the expected behavior comes from. For new public APIs or behavior changes, an issue or discussion before a large implementation can uncover compatibility and design concerns early.+### Review Process-Reviewers may ask for changes, tests, documentation, or a smaller scope. They may also decide that a contribution does not fit the project. We will try to explain why, but review is not guaranteed. Pull requests that have been quiet for a while may be closed and can be reopened later.+Review your diff and validation before submission. Maintainers review PRs; contributors+should report problems in another contributor's PR on its linked issue rather than post+reviews or approvals. Respond to feedback and explain decisions; maintainers may request+a smaller scope or decline work, and review or merge is not guaranteed.-**PR checks and merge requirements:**-- Code changes run the CPU test matrix, dynamo/compile tests, and type checking with `ty`-- Pre-commit checks formatting, linting, license headers, spelling, and repository file hygiene-- Documentation changes run the documentation build-- Every non-draft pull request gets an automated Copilot review when opened or marked ready and needs one maintainer approval-- Pull requests are squash-merged+PRs are marked stale after 15 quiet days as a triage signal; activity clears the label,+and maintainers can use `pinned` to exempt a PR. There is **no automatic closure for+inactivity**. A maintainer may close a quiet PR at their discretion; it may be reopened.+A quiet PR may be waiting on us, so the label is a nudge to follow up, not a deadline.-If a check fails because of your change, please fix it or explain what you found.+Code changes run CPU, compile, and type checks; pre-commit checks formatting, spelling,+headers, and file hygiene. Documentation changes run the docs build. Every non-draft PR+gets automated Copilot review when opened or marked ready and needs a maintainer approval.+PRs are squash-merged. Fix failures caused by your change or explain them.## Licensediff --git a/README.md b/README.mdindex 2b6e9c332..71e812271 100644--- a/README.md+++ b/README.md@@ -132,7 +132,7 @@ Leverage pre-trained AI models optimized for a variety of vision tasks, all withThe module table below counts entries in the Linux CPU known-failure manifests([`cpu_float16.txt`](testing/half_precision_xfails/cpu_float16.txt),[`cpu_bfloat16.txt`](testing/half_precision_xfails/cpu_bfloat16.txt)), pinned to Python 3.11 and PyTorch 2.15.0.-There are **243 float16 and 255 bfloat16 recorded failures**. These are parametrized test cases, not counts of+There are **242 float16 and 255 bfloat16 recorded failures**. These are parametrized test cases, not counts ofunsupported functions. [#4153](https://github.com/kornia/kornia/issues/4153) tracked them until it was closed on2026-10-18; no single issue tracks the remaining entries.No CI job covers CUDA or MPS half precision; CPU results do not establish support on those backends. A local CUDA@@ -280,7 +280,7 @@ For development, Kornia uses [pixi](https://pixi.sh) for fast Python package manpixi run -e cuda test-cuda```-These commands set up a complete development environment with all dependencies. For more details on dependency management and available tasks, see [CONTRIBUTING.md](CONTRIBUTING.md).+These commands set up a complete development environment with all dependencies. For more details on dependency management and available tasks, see [TESTING.md](TESTING.md#environment-and-validation-tasks).#### From Github url (latest version)@@ -363,7 +363,7 @@ Kornia's differentiated value is its geometry core: warping and sampling, homogr- **Benchmark results from your hardware**: run the benchmark suite with `--contribute` and send the JSON — CUDA numbers from diverse GPUs are especially useful.- **Convention pinning tests and conformance vectors** for core geometry operations.- **Corrective error messages**: upgrade bare shape assertions into errors that state what was wrong, what was expected, and which convention applies.-- **Classical vision in the core domain**: camera intrinsic calibration, fiducial markers (ArUco/ChArUco), classical tracking, dense stereo, and Hough transforms. An early design discussion can be useful for work of this size.+- **Documented CUDA and half-precision failures**: fix existing CUDA reports, open half-precision issues, and entries in the [`float16`](testing/half_precision_xfails/cpu_float16.txt)/[`bfloat16`](testing/half_precision_xfails/cpu_bfloat16.txt) known-failure manifests under the [correctness policy](ROADMAP.md#correctness-and-backend-support). Take CUDA work only with a CUDA device available for reproduction and validation; remove the corresponding xfail or manifest entry after verifying the fix.See the [Roadmap's contributor areas](ROADMAP.md#areas-seeking-contributors) for more project context.diff --git a/README_zh-CN.md b/README_zh-CN.mdindex aff1cd16e..ec67832b2 100644--- a/README_zh-CN.md+++ b/README_zh-CN.md@@ -1,21 +1,25 @@<div align="center"><p align="center">- <img width="75%" src="https://github.com/kornia/data/raw/main/kornia_banner_pixie.png" />+ <img width="55%" src="https://github.com/kornia/data/raw/main/kornia_banner_pixie.png" /></p>-**The open-source and Computer Vision 2.0 library**----[English](README.md) | 简体中文+<p align="center">+ <a href="https://www.kornia.org/playground/"><img alt="在浏览器中试用" src="https://img.shields.io/badge/%E2%96%B6%20Try%20in%20your%20browser-F5B301?style=for-the-badge&labelColor=F5B301"></a>+ <a href="https://www.kornia.org"><img alt="网站" src="https://img.shields.io/badge/Website-0B1A2B?style=for-the-badge"></a>+ <a href="https://kornia.readthedocs.io"><img alt="文档" src="https://img.shields.io/badge/Docs-0B1A2B?style=for-the-badge"></a>+</p>+<!-- prettier-ignore -->-<a href="https://kornia.readthedocs.io">Docs</a> •-<a href="https://colab.sandbox.google.com/github/kornia/tutorials/blob/master/nbs/hello_world_tutorial.ipynb">Try it Now</a> •-<a href="https://www.kornia.org/tutorials/">Tutorials</a> •-<a href="https://github.com/kornia/kornia-examples">Examples</a> •-<a href="https://www.kornia.org/kornia-blog/">Blog</a> •-<a href="https://discord.gg/HfnywwpBnD">Community</a>+<a href="https://kornia.readthedocs.io">文档</a> •+<a href="https://colab.sandbox.google.com/github/kornia/tutorials/blob/master/nbs/hello_world_tutorial.ipynb">立即试用</a> •+<a href="https://www.kornia.org/tutorials/">教程</a> •+<a href="https://github.com/kornia/kornia-examples">示例</a> •+<a href="https://www.kornia.org/kornia-blog/">博客</a> •+<a href="https://discord.gg/HfnywwpBnD">社区</a>[](https://pypi.org/project/kornia)[](https://pepy.tech/project/kornia)@@ -27,65 +31,184 @@</p></div>-*Kornia* 是一款基于 [PyTorch](https://pytorch.org) 的可微分的计算机视觉库。+**Kornia** 是一个可微分计算机视觉库,提供丰富的可微分图像处理和几何视觉算法。Kornia 基于 [PyTorch](https://pytorch.org) 构建,可无缝融入现有的 AI 工作流程,支持[批量变换](https://kornia.readthedocs.io/en/latest/get-started/gpu-acceleration.html)、[自动微分](https://kornia.readthedocs.io/en/latest/get-started/differentiability.html)和 [GPU 加速](https://kornia.readthedocs.io/en/latest/get-started/gpu-acceleration.html)。无论您需要图像变换、数据增强还是 AI 驱动的图像处理,Kornia 都能提供实现这些想法所需的工具。++> **📢 发展方向**:Kornia 正在成为 PyTorch 生态中可微分计算机视觉与几何算法的**参考实现和可执行规范**——相比增加 API 数量,我们更重视明确的约定、一致性测试以及如实报告的性能基准。详情请阅读[路线图](ROADMAP.md)。++## 何时使用 Kornia++当手写实现变得冗长或容易出错,或者替代方案需要将数据移出 GPU 时,Kornia 尤其适用:++- **覆盖面广。** 提供 1,200 多个公开算子,大多数在 torchvision 中没有对应实现:相机模型与对极几何、最小求解器与 RANSAC、特征检测、描述与匹配、边缘检测、形态学、Lab 与 Bayer 颜色处理,以及图像损失函数和评估指标。与 torchvision 重叠的功能主要是缩放、裁剪、翻转、颜色扰动和模糊。+- **一次批量调用即可为每个样本使用不同参数。** `gaussian_blur2d(x, (9, 9), sigma)` 接受形状为 `(B, 2)` 的 `sigma`;`rotate` 接受 `(B,)` 的角度,`warp_affine` / `warp_perspective` 接受 `(B, 2, 3)` / `(B, 3, 3)` 的矩阵,`adjust_brightness` 接受 `(B,)` 的系数。torchvision 的函数式算子在每次调用中使用同一组参数。从 Kornia 0.9.1 起,`sigma` 张量以及图像增强函数的取值检查(gamma、contrast、solarize)均在设备上完成,因此 CUDA 调用以及 PyTorch ≥ 2.13 上的 MPS 调用无需为这些检查与主机同步。+- **批量最小求解器与鲁棒估计。** `find_fundamental(x1, x2, method="7POINT")` 求解形状为 `(B, 7, 2)` 的样本,将全部实数解返回为 `(B, 3, 3, 3)`,未使用的位置填充零矩阵;还提供 8 点法、5 点本质矩阵求解器(`find_essential`)、DLT 单应性求解器和 PnP 求解器(`solve_pnp_dlt`)。`RANSAC`(支持单应矩阵、基础矩阵和本质矩阵模型)在设备上采样和评分候选模型;默认情况下,细化与最终选择在主机上以 float64 进行,而 `compile=True`(PyTorch ≥ 2.14,CPU 和 CUDA)将整个估计过程作为一个编译图在设备上执行。+- **可微分几何。** 深度与三维坐标之间的转换(`depth_to_3d_v2`、`unproject_points`、`project_points`)、`warp_frame_depth`、`remap`、具有 Brown–Conrady 和 Kannala–Brandt 畸变的相机模型,以及李群(`So3`、`Se3`)均保留相对于深度、位姿和相机参数的梯度。+- **带标注的数据增强。** 在二维场景中,`AugmentationSequential` 将同一次采样得到的变换同步应用于图像、掩码、边界框和关键点,并可执行逆变换;三维增强用于变换体数据,不支持标注或逆变换。在 CUDA 上,增强操作会将采样参数传到 GPU,而不阻塞 GPU;同步检查测试确保每个公开增强操作都不会产生可避免的主机同步。+- **GPU 上的局部特征。** 支持 SIFT 和 HardNet、DISK、ALIKED、XFeat、DeDoDe、LoFTR 与 LightGlue,以及互为最近邻和比率测试匹配器。+- **形态学。** 支持在批量张量上使用任意结构元素。+- **编译与导出。** 几乎所有已探测的算子配置都可在 `torch.compile` 下运行,并与 eager 执行结果一致;超过 1,000 个配置可导出为 ONNX。每个算子的结果都列在[导出支持页面](https://kornia.readthedocs.io/en/latest/get-started/export-support.html)。+- **在设计目标场景中速度快:GPU 上的批量张量。** 在已发布的 0.9.0 旗舰基准测试中(RTX 4090,批量大小 32),许多滤波器、图像变换、特征匹配步骤和图像指标在 eager 模式下,比 CPU 上逐张执行的 OpenCV 或 scikit-image 快约 10× 至 70×;使用 `torch.compile` 后,其中一些超过 100×。在同一 GPU 上与 torchvision 重叠的少量操作中,eager Kornia 较慢;编译后的 Kornia 在色调调整、颜色扰动和高斯模糊上较快,在翻转、裁剪和亮度调整上仍较慢。对于 CPU 上的单张 `uint8` 图像处理,OpenCV 更快。结果会随硬件和工作负载而变化;所有数值、优势和劣势都公开在[性能页面](https://kornia.readthedocs.io/en/latest/get-started/performance.html)。++这些算子在输入所在的设备上运行,无需经由 NumPy 往返转换,且大多数可微分;鲁棒估计(`RANSAC`)以及 DeDoDe、XFeat 等学习型特征的提取方法不计算梯度。对于参数固定的单个操作,例如一次模糊或缩放,几行 PyTorch 或 torchvision 代码也同样合适。++## 主要组件++1. **可微分图像处理**<br>+ Kornia 提供全面的图像处理算子,支持微分,可集成到深度学习流水线中。+ - **滤波器**:高斯、Sobel、中值、方框模糊等。+ - **变换**:仿射、单应性、透视等。+ - **图像增强**:直方图均衡化、CLAHE、伽马校正等。+ - **边缘检测**:Canny、拉普拉斯、Sobel 等。+ - 更多内容请参阅[文档](https://kornia.readthedocs.io)。+2. **高级数据增强**<br>+ 使用 Kornia 内置函数执行数据增强,适用于包含复杂增强流水线的 AI 模型训练。+ - **增强流水线**:AugmentationSequential、PatchSequential、VideoSequential 等。+ - **自动增强**:AutoAugment、RandAugment、TrivialAugment。+3. **AI 模型**<br>+ 在 Kornia 生态中使用针对不同视觉任务优化的预训练 AI 模型。+ - **人脸检测**:YuNet+ - **特征匹配**:LoFTR、LightGlue+ - **特征描述子**:DISK、DeDoDe、SOLD2+ - **分割**:SAM+ - **分类**:MobileViT、VisionTransformer。-它由一组用于解决通用计算机视觉问题的操作模块和可微分模块组成。其核心使用 *PyTorch* 作为主要后端,以提高效率并利用反向模式自动微分来定义和计算复杂函数的梯度。+<details>+<summary>查看部分支持的方法(总计超过 500 个算子!)</summary>++| **类别** | **方法/模型** |+|----------|---------------|+| **图像处理** | - 颜色转换(RGB、灰度、HSV 等)<br>- 几何变换(仿射、单应性、缩放等)<br>- 滤波(高斯模糊、中值模糊等)<br>- 边缘检测(Sobel、Canny 等)<br>- 形态学操作(腐蚀、膨胀等) |+| **数据增强** | - 随机裁剪、擦除<br>- 随机几何变换(仿射、翻转、鱼眼、透视、薄板样条、弹性变换)<br>- 随机噪声(高斯、中值、运动、方框、雨、雪、椒盐)<br>- 随机颜色扰动(对比度、亮度、CLAHE、均衡化、Gamma、色调、反色、JPEG、Plasma、色调分离、饱和度、锐度、Solarize)<br>- 随机 MixUp、CutMix、Mosaic、Transplantation 等 |+| **特征检测** | - 检测器(Harris、GFTT、Hessian、DoG、KeyNet、DISK 和 DeDoDe)<br>- 描述子(SIFT、HardNet、TFeat、HyNet、SOSNet 和 LAFDescriptor)<br>- 匹配(最近邻、互为最近邻、几何感知匹配、AdaLAM、LightGlue 和 LoFTR) |+| **几何** | - 相机模型与标定<br>- 双目视觉(对极几何、视差等)<br>- 单应性估计<br>- 从视差估计深度<br>- 三维变换 |+| **深度学习层** | - 自定义卷积层<br>- 面向视觉任务的循环层<br>- 损失函数(如 SSIM、PSNR 等)<br>- 视觉专用优化器 |+| **光度函数** | - 光度损失函数<br>- 光度增强 |+| **滤波** | - 双边滤波<br>- DexiNed<br>- Dissolving<br>- 引导模糊<br>- 拉普拉斯<br>- 高斯<br>- 非局部均值<br>- Sobel<br>- 非锐化掩蔽 |+| **颜色** | - 色彩空间转换<br>- 亮度/对比度调整<br>- 伽马校正 |+| **双目视觉** | - 视差估计<br>- 深度估计<br>- 校正 |+| **图像配准** | - 基于仿射和单应性的配准<br>- 基于特征的图像对齐 |+| **位姿估计** | - 本质矩阵与基础矩阵估计<br>- PnP 问题求解器<br>- 位姿细化 |+| **光流** | - Farneback 光流<br>- 稠密光流<br>- 稀疏光流 |+| **三维视觉** | - 深度估计<br>- 点云操作 |+| **图像去噪** | - 去除高斯噪声<br>- 去除泊松噪声 |+| **边缘检测** | - Sobel 算子<br>- Canny 边缘检测 |+| **变换** | - 旋转<br>- 平移<br>- 缩放<br>- 剪切 |+| **损失函数** | - SSIM(结构相似性指标)<br>- PSNR(峰值信噪比)<br>- Cauchy<br>- Charbonnier<br>- 深度平滑<br>- Dice<br>- Hausdorff<br>- Tversky<br>- Welsch |+| **形态学操作** | - 膨胀<br>- 腐蚀<br>- 开运算<br>- 闭运算 |-<div align="center">- <img src="https://github.com/kornia/kornia/raw/main/docs/source/_static/img/hakuna_matata.gif" width="75%" height="75%">-</div>+</details>++## CUDA 与半精度支持++下表按模块统计 Linux CPU 已知失败清单中的条目([`cpu_float16.txt`](testing/half_precision_xfails/cpu_float16.txt)、[`cpu_bfloat16.txt`](testing/half_precision_xfails/cpu_bfloat16.txt)),对应固定的 Python 3.11 和 PyTorch 2.15.0 环境。+清单记录了 **242 个 float16 失败和 255 个 bfloat16 失败**。这些数量指参数化测试用例,并不代表不受支持的函数数量。[#4153](https://github.com/kornia/kornia/issues/4153) 曾跟踪这些失败,直到该议题于 2026-10-18 关闭;目前没有单个议题跟踪所有剩余条目。+没有 CI 任务覆盖 CUDA 或 MPS 半精度;CPU 结果不能证明这些后端的支持情况。完整测试套件的一次本地 CUDA 测量见[下文](#cuda-测试套件测量)。++| 模块 | float16 | bfloat16 | 已知失败(fp16 / bf16) | 说明 |+|------|:-------:|:--------:|:----------------------:|------|+| `kornia.color` | ✅ | ✅ | 0 / 0 | Lab/Luv 转换和 `rgb255_to_normals` 对半精度输入使用 float32 计算,并返回输入 dtype |+| `kornia.filters` | ✅ | ✅ | 0 / 0 | Canny、高斯核/模糊和 FFT 卷积对半精度输入使用 float32 计算,并返回输入 dtype |+| `kornia.enhance` | ✅ | ✅ | 0 / 0 | ZCA 对半精度输入保留 float32 拟合状态;白化和 JPEG 以 float32 计算后返回输入 dtype |+| `kornia.morphology` | ✅ | ✅ | 0 / 0 | |+| `kornia.augmentation` | ⚠️ | ⚠️ | 59 / 47 | float16:容器 autocast/运行时错误和精度问题;两种 dtype:三维反向传播和随机生成器精度问题 |+| `kornia.geometry.transform` | ⚠️ | ⚠️ | 31 / 31 | 旋转矩阵、仿射/透视变换和单应性变换器的精度问题 |+| `kornia.geometry.camera` | ⚠️ | ⚠️ | 13 / 23 | 投影、畸变往返变换和双目重投影;包括测试中的 dtype 断言 |+| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 12 / 12 | solve_pnp_dlt 拒绝半精度输入;undistort_points 精度问题 |+| `kornia.geometry.epipolar` | ⚠️ | ⚠️ | 36 / 36 | 本质矩阵分解/运动恢复和 KRt_from_projection 缺少 CPU 半精度内核;基础矩阵精度问题 |+| `kornia.geometry.homography` | ⚠️ | ⚠️ | 10 / 16 | DLT 求解器精度问题,包括迭代版本和基于直线的版本 |+| `kornia.geometry.liegroup` | ✅ | ✅ | 0 / 0 | So2/Se2 拒绝用 bfloat16 构造旋转:PyTorch 没有复数 bfloat16 dtype;这些预期错误/跳过项不计入清单 |+| `kornia.geometry.solvers` | ✅ | ✅ | 0 / 0 | |+| `kornia.geometry.subpix` | ⚠️ | ⚠️ | 6 / 3 | SpatialSoftArgmax2d 和 ConvQuadInterp3d 精度问题;bfloat16:render_gaussian2d 精度问题 |+| `kornia.geometry.conversions` | ⚠️ | ⚠️ | 65 / 65 | 轴角、四元数和旋转矩阵的精度问题;包括 tests/integration/test_conversions.py |+| `kornia.geometry.ransac` | ⚠️ | ⚠️ | 2 / 2 | 本质矩阵模型拟合在对极几何求解器中抛出异常 |+| `kornia.geometry (other)` | ⚠️ | ⚠️ | 6 / 13 | 边界框变换和深度的精度问题 |+| `kornia.image` | ⚠️ | ⚠️ | 2 / 2 | 圆/椭圆多边形填充的比较使用半精度计算的顶点和参考掩码 |+| `kornia.losses` | ✅ | ⚠️ | 0 / 2 | bfloat16:总变分精度问题 |+| `kornia.feature` | ✅ | ✅ | 0 / 0 | 特征匹配在半精度 dtype 下使用手动实现的 cdist 回退路径;LightGlue 的 float16 测试被跳过 |+| `kornia.metrics` | ✅ | ✅ | 0 / 0 | |+| `kornia.models` | ✅ | ⚠️ | 0 / 1 | bfloat16:RT-DETR RepVGG 融合精度问题 |+| `contrib, core, io, onnx, sensors, tracking, utils` | ✅ | ⚠️ | 0 / 2 | bfloat16:直方图匹配和 _torch_svd_cast 精度问题 |++✅ CPU 已知失败清单中没有条目 ⚠️ 存在已记录的 CPU 失败。+这两个符号都不承诺完整的 dtype 支持:跳过的测试、预期异常以及源码中的 xfail 不在这些计数内。一些算子内部使用 float32 或 float64 计算,再返回输入 dtype。++**观测到的 CPU CI 结果:**++[2026-10-21 在 `93f1376e` 上的定时运行](https://github.com/kornia/kornia/actions/runs/39524889979)使用 Linux x86_64、Python 3.11 和 PyTorch 2.14.0,不包含慢速测试或编译测试:++| 运行 | 通过 | 失败 | 跳过 | XFAIL(全部) | XPASS | 严格清单条目 |+|------|-----:|-----:|-----:|-------------:|------:|-------------:|+| [CPU float16](https://github.com/kornia/kornia/actions/runs/39524889979/job/118977300500) | 23905 | 0 | 5132 | 284 | 4 | 250 |+| [CPU bfloat16](https://github.com/kornia/kornia/actions/runs/39524889979/job/118977300410) | 23726 | 0 | 5286 | 309 | 4 | 274 |-<!--<div align="center">- <img src="http://drive.google.com/uc?export=view&id=1KNwaanUdY1MynF0EYfyXjDM3ti09tzaq">-</div>-->+每个任务还取消选择了 3 个 ONNX 一致性测试。XFAIL 总数包括严格清单条目和源码中的预期失败。每个成功任务中的 4 个 XPASS,是原本非严格预期失败但实际通过的测试;**清单**中的条目一旦通过,则会使验证失败,异常类型改变、条目被跳过或节点 ID 过期也同样如此。因此,CI 任务变绿意味着记录的基线得到复现,即便仍有已知失败和跳过项。这些总数描述的是所链接的版本;模块表描述的是仓库中提交的清单。-## 概览+在固定环境中验证完整 CPU 配置:-受现有开源库的启发,Kornia可以由包含各种可以嵌入神经网络的操作符组成,并可以训练模型来执行图像变换、对极几何、深度估计和低级图像处理,例如过滤和边缘检测。此外,整个库都可以直接对张量进行操作。+```bash+KORNIA_TEST_OPTIMIZER= pixi run test-module tests/ --verify-known-failures --known-failure-profile=cpu-float16+KORNIA_TEST_OPTIMIZER= pixi run test-module tests/ --verify-known-failures --known-failure-profile=cpu-bfloat16+```-详细来说,Kornia 是一个包含以下组件的库:+`pixi run test-half` 是一次未固定随机种子的 CPU 测试运行,不使用严格配置基线。定向检查和基线维护方法请参阅 [TESTING.md](TESTING.md#7-half-precision-dtypes-float16--bfloat16)。-| **Component** | **Description** |-|----------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|-| [kornia](https://kornia.readthedocs.io/en/latest/index.html) | 具有强大 GPU 支持的可微计算机视觉库 |-| [kornia.augmentation](https://kornia.readthedocs.io/en/latest/augmentation.html) | 在 GPU 中执行数据增强的模块 |-| [kornia.color](https://kornia.readthedocs.io/en/latest/color.html) | 执行色彩空间转换的模块 |-| [kornia.contrib](https://kornia.readthedocs.io/en/latest/contrib.html) | 未进入稳定版本的实验性模块 |-| [kornia.enhance](https://kornia.readthedocs.io/en/latest/enhance.html) | 执行归一化和像素强度变换的模块 |-| [kornia.feature](https://kornia.readthedocs.io/en/latest/feature.html) | 执行特征检测的模块 |-| [kornia.filters](https://kornia.readthedocs.io/en/latest/filters.html) | 执行图像滤波和边缘检测的模块 |-| [kornia.geometry](https://kornia.readthedocs.io/en/latest/geometry.html) | 执行几何计算的模块,用于使用不同的相机模型执行图像变换、3D线性代数和转换 |-| [kornia.losses](https://kornia.readthedocs.io/en/latest/losses.html) | 损失函数模块 |-| [kornia.morphology](https://kornia.readthedocs.io/en/latest/morphology.html) | 执行形态学操作的模块 |-| [kornia.image](https://kornia.readthedocs.io/en/latest/image.html) | 图像数据结构、绘制以及图像/张量常用工具 |-| [kornia.metrics](https://kornia.readthedocs.io/en/latest/metrics.html) | 评估指标模块 |+### CUDA 测试套件测量-## 支持我们+Kornia 接受 CUDA 张量以使用 GPU 加速,但受各算子的 dtype 和后端限制约束。目前没有 CUDA CI 任务,也没有提交到仓库的 CUDA 已知失败清单,因此下列总数只是某一版本的本地测量,不保证后续版本具有相同结果:版本 `e4a444e9b`(2026-11-04),RTX 4090,Python 3.11,PyTorch 2.15.0+cu132,关闭 TF32,对 `tests/` 使用 `--device=cuda`:++| CUDA 运行 | 通过 | 失败 | 跳过 | XFAIL | XPASS |+|-----------|-----:|-----:|-----:|------:|------:|+| float32 + float64 | 46079 | 0 | 9198 | 46 | 11 |+| float16 + bfloat16 | 45024 | 440 | 9813 | 50 | 7 |+| float32,`torch.compile`(inductor)测试 | 853 | 6 | 80 | 1 | 1 |++- **float32 和 float64:** 没有失败。+- **float16 和 bfloat16:** 440 个失败中,408 个是 CPU 清单条目在 CUDA 上的对应用例。其余 32 个中,21 个在独立进程中通过,2 个使用未固定随机种子的输入,在 CPU 上也会失败。有 9 个仅在 CUDA 上失败:其中 5 个是因为 CUDA 按批量大小选择卷积和矩阵乘法内核,使半精度 LoFTR、SmallSR 或 LightGlue 对同一图像的批量输出与单独输出略有不同(在 CPU 上逐位相同;使用预训练权重时,这一差异小于半精度误差本身);另外 4 个是 `RandomRotation3D` 的 bfloat16 反向传播用例,原因在于 bfloat16 的限制,而非 CUDA:测试中的 SGD 步长小于每个角度的半个 bfloat16 ulp,因此角度没有变化。+- **`torch.compile`:** 6 个编译测试仅在 CUDA 上失败(缩放裁剪的重放、Otsu 分箱边界、`fit_line`、`Hyperplane` 和 `Keypoints` 的标量索引)。++[精度指南](https://kornia.readthedocs.io/en/latest/get-started/precision.html#cuda-test-suite-measurement)列出了每项失败,给出了批量与单张处理的测量结果,并列出测试套件未覆盖的、仍未解决的 CUDA 专属问题。++运行 CUDA 半精度测试时,请使用 `--isolate-half-precision`,使每个测试都在新进程中运行。缺少此选项时,这些测试默认被跳过;仅选择半精度 dtype 并不能测试 CUDA 半精度支持:++```bash+pixi run test-module tests/color/ --device=cuda --dtype=float16,bfloat16 --isolate-half-precision+```++详情请参阅[完整精度指南](https://kornia.readthedocs.io/en/latest/get-started/precision.html)。++## 赞助++Kornia 是一个由志愿者开发和维护的开源项目。无论您是将其用于研究还是商业用途,都欢迎考虑赞助我们或与我们合作。您的支持将有助于确保 Kornia 的成长与持续创新。立即联系我们,成为塑造这一令人振奋项目未来的一员!<a href="https://opencollective.com/kornia/donate" target="_blank"><img src="https://opencollective.com/webpack/donate/[email protected]?color=blue" width=300 /></a>-## 安装说明+## 安装++[](https://pypi.org/project/kornia)+[](https://pytorch.org/get-started/locally/)-### 通过 pip 安装:+### 使用 pip 安装```bashpip install kornia```+部分功能(ONNX、Stable Diffusion 溶解)需要额外的软件包;请参阅[可选扩展](https://kornia.readthedocs.io/en/latest/get-started/installation.html#optional-extras)。+<details>- <summary>其他安装方法</summary>+ <summary>其他安装选项</summary>- #### 通过源码安装(软链接至当前路径):+#### 从源码以可编辑模式安装```bashpip install -e .```- #### 使用 Pixi 进行开发(推荐)+#### 使用 Pixi 进行开发(推荐)- 对于开发,Kornia 使用 [pixi](https://pixi.sh) 进行快速的 Python 包管理和环境管理。项目包含一个 `pixi.toml` 配置文件用于可重现的依赖管理。+开发 Kornia 时,我们使用 [pixi](https://pixi.sh) 进行快速的 Python 包与环境管理。项目包含一个 `pixi.toml` 配置文件,以实现可复现的依赖管理。```bash# 安装 pixi(如果尚未安装)@@ -103,32 +226,104 @@pixi run -e cuda test-cuda```- 这些命令将设置一个包含所有依赖的完整开发环境。有关依赖管理和可用任务的更多详细信息,请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。+这些命令会设置包含所有依赖项的完整开发环境。有关依赖管理和可用任务的更多详情,请参阅 [TESTING.md](TESTING.md#environment-and-validation-tasks)。- #### 通过源码安装(从GIT自动下载最新代码):+#### 从 Github URL 安装(最新版本)```bashpip install git+https://github.com/kornia/kornia```+</details>+## 快速开始-## 例子+Kornia 不只是另一个计算机视觉库——它是您轻松进入计算机视觉和 AI 世界的入口。-可以尝试通过这些 [教程](https://www.kornia.org/tutorials/) 来学习和使用这个库。+<details>+<summary>开始使用 Kornia 进行图像变换和增强!</summary>-<div align="center">- <a href="https://colab.sandbox.google.com/github/kornia/tutorials/blob/master/nbs/hello_world_tutorial.ipynb" target="_blank">- <img src="https://raw.githubusercontent.com/kornia/data/main/hello_world_arturito.png" width="75%" height="75%">- </a>-</div>+```python+import numpy as np+import kornia_rs as kr-:triangular_flag_on_post: **Updates**-- :white_check_mark: 现已通过 [Gradio](https://github.com/gradio-app/gradio) 将Kornia集成进 [Huggingface Spaces](https://huggingface.co/spaces). 可以尝试 [Gradio 在线Demo](https://huggingface.co/spaces/akhaliq/Kornia-LoFTR).+from kornia.augmentation import AugmentationSequential, RandomAffine, RandomBrightness+from kornia.filters import StableDiffusionDissolving++# Load and prepare your image+img: np.ndarray = kr.read_image_any("img.jpeg")+img = kr.resize(img, (256, 256), interpolation="bilinear")++# alternatively, load image with PIL+# img = Image.open("img.jpeg").resize((256, 256))+# img = np.array(img)++img = np.stack([img] * 2) # batch images++# Define an augmentation pipeline+augmentation_pipeline = AugmentationSequential(RandomAffine((-45.0, 45.0), p=1.0), RandomBrightness((0.0, 1.0), p=1.0))++# Leveraging StableDiffusion models+dslv_op = StableDiffusionDissolving()++img = augmentation_pipeline(img)+dslv_op(img, step_number=500)++dslv_op.save("Kornia-enhanced.jpg")+```++</details>++<details>+<summary>使用 ONNXSequential 探索 Kornia ONNX 模型!</summary>++```python+import numpy as np+from kornia.onnx import ONNXSequential++# Chain ONNX models from HuggingFace repo and your own local model together+onnx_seq = ONNXSequential(+ "hf://operators/kornia.geometry.transform.flips.Hflip",+ "hf://models/kornia.models.detection.rtdetr_r18vd_640x640", # Or you may use "YOUR_OWN_MODEL.onnx"+)+# Prepare some input data+input_data = np.random.randn(1, 3, 384, 512).astype(np.float32)+# Perform inference+outputs = onnx_seq(input_data)+# Print the model outputs+print(outputs)++# Export a new ONNX model that chains up all three models together!+onnx_seq.export("chained_model.onnx")+```+</details>++## 征集贡献者++如果 Kornia 对您有用,且您愿意提供帮助,我们欢迎各种形式的贡献:代码、错误报告、基准测试、文档、问题、解答和示例。维护者的时间有限,因此我们无法承诺审核或合并每一个提案或拉取请求。++### 强化核心(优先事项)++Kornia 的差异化价值在于其几何核心:图像变换与采样、单应性、相机、对极几何、旋转与李群,以及几何一致的增强。最具影响力的贡献能让这一核心更值得信赖——完整概览请参阅[路线图](ROADMAP.md)。可以从以下方面入手:++- **来自您硬件的基准测试结果**:使用 `--contribute` 运行基准测试套件并发送 JSON——来自不同 GPU 的 CUDA 数据尤其有价值。+- 为核心几何操作编写**锁定约定行为的测试和一致性测试向量**。+- **有助于纠正问题的错误信息**:将简单的形状断言升级为说明错误之处、预期内容及适用约定的错误信息。+- **已记录的 CUDA 和半精度失败**:根据[正确性策略](ROADMAP.md#correctness-and-backend-support)修复现有 CUDA 报告和未关闭的半精度议题中的问题,以及 [`float16`](testing/half_precision_xfails/cpu_float16.txt)/[`bfloat16`](testing/half_precision_xfails/cpu_bfloat16.txt) 已知失败清单中的条目。仅在有 CUDA 设备可用于复现和验证时开展 CUDA 修复;在验证修复后,移除相应的 xfail 或清单条目。++更多项目背景请参阅[路线图中面向贡献者的领域](ROADMAP.md#areas-seeking-contributors)。++### AI 模型++在维护者的精力集中于核心期间,模型库目前**暂停扩展**。已发布的模型(LoFTR、LightGlue、DISK、DeDoDe、SAM 等)将保持可用并继续维护,而在暂停前获批的模型工作(Efficient LoFTR、SANDesc)将在其既有范围内完成。新的集成——包括 VLM/VLA 模型——必须由明确指定的维护者支持,并由其承担长期维护责任;仅有贡献者的实现不足以重新开放模型扩展。有关原因和重新开放条件,请参阅[路线图](ROADMAP.md#guiding-themes)。++### 文档与教程优化++Kornia 的基础在于其丰富的经典计算机视觉算子集合,为图像处理、特征提取和几何变换提供了强大的工具。我们持续寻找贡献者,帮助我们改进文档,并为用户提供优秀的教程。## 引用-如果您在与研究相关的文档中使用 Kornia,您可以引用我们的论文。更多信息可以在 [CITATION](https://github.com/kornia/kornia/blob/main/CITATION.md) 看到。+如果您在研究相关文档中使用 Kornia,建议引用该论文。更多信息请参阅 [CITATION](./CITATION.md)。```bibtex@inproceedings{eriba2019kornia,@@ -141,13 +336,20 @@```## 贡献-我们(维护者)为自己和计算机视觉社区开发 kornia。如果它对您有用,或者您愿意通过代码、错误报告、文档、问题或想法来帮助改进它,我们都会很高兴。维护者的时间有限,因此我们无法承诺审查或合并每一项提议。详情请阅读 [贡献指南](https://github.com/kornia/kornia/blob/main/CONTRIBUTING.md)。参与本项目时也请遵守 [行为准则](https://github.com/kornia/kornia/blob/main/CODE_OF_CONDUCT.md)。++有关我们的社会契约、开发环境设置和技术指南,请参阅 [CONTRIBUTING.md](./CONTRIBUTING.md)。参与即表示您同意遵守[行为准则](./CODE_OF_CONDUCT.md)。## 社区-- **GitHub Discussions:** 提问,并讨论代码实现、研究和想法。[参与讨论](https://github.com/kornia/kornia/discussions)-- **GitHub Issues:** 报告错误和提出具体更改。[提交 Issue](https://github.com/kornia/kornia/issues/new/choose)-- **Discord:** 加入我们的 Discord 社区,与使用和开发 kornia 的人交流。[加入](https://discord.gg/HfnywwpBnD)-- 常见信息请访问我们的网站 www.kornia.org++- **Discord**:与使用和开发 Kornia 的人交流。[加入服务器](https://discord.gg/HfnywwpBnD)+- **GitHub Issues**:报告错误并提出具体更改。[创建 Issue](https://github.com/kornia/kornia/issues/new/choose)+- **GitHub Discussions**:提出问题并讨论实现、研究和想法。[参与讨论](https://github.com/kornia/kornia/discussions)++<a href="https://github.com/Kornia/kornia/graphs/contributors">+ <img src="https://contrib.rocks/image?repo=Kornia/kornia" width="60%" />+</a>++由 [contrib.rocks](https://contrib.rocks) 制作。## 中文社区扫描下方的二维码可关注 Kornia 的官方交流QQ群(679683070)以及Kornia知乎账号。@@ -162,3 +364,7 @@- 📢 更新 Kornia 的最新动态- 📘 进行更高效的答疑解惑以及意见反馈- 💻 提供与行业大牛的充分交流的平台++## 许可证++Kornia 采用 Apache 2.0 许可证发布。更多信息请参阅 [LICENSE](./LICENSE) 文件。diff --git a/ROADMAP.md b/ROADMAP.mdindex d5bef43f8..9c9e50be1 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,317 +1,211 @@# Kornia Roadmap-This document describes where Kornia is headed. It exists to help contributors find-high-impact work, to show users the direction of the project, and to make our-priorities legible to the wider community.+Kornia is becoming the **reference implementation and executable specification** for+differentiable computer vision and geometry in PyTorch. Concentrate on warping and+sampling, homographies, cameras, epipolar geometry, rotations/Lie groups, and+geometry-consistent augmentation. Progress means trustworthy results, explicit+conventions, dependable composition, and honest performance; API and PR counts are+not goals.-It is a living document. Dates are intentions, not commitments, and priorities shift-as the ecosystem does. If you want to work on something here, the technical guidelines-and social contract are in [CONTRIBUTING.md](CONTRIBUTING.md). For large features or-behavior changes, an early conversation may save work and surface compatibility concerns.--**Where Kornia is going.** Kornia is becoming the **reference implementation and-executable specification** for differentiable computer vision and geometry in the-PyTorch ecosystem. At ~3M downloads/month the highest-leverage work is not growing-the API — it is making the differentiated core (warping and sampling, homographies,-cameras, epipolar geometry, rotations and Lie groups, geometry-consistent-augmentation) unusually trustworthy: conventions explicit and pinned by tests,-behavior validated by conformance vectors, guarantees enforced by CI. Progress is-measured in confidence, not API count — a strong release can contain zero new public-APIs and still deliver better `torch.compile` coverage, fixed convention ambiguity,-improved numerical stability, and stronger dtype/device behavior.+This document owns strategy and correctness policy. [CONTRIBUTING.md](CONTRIBUTING.md)+is the contribution entry point; [AGENTS.md](AGENTS.md) guides agent execution, and+[TESTING.md](TESTING.md) describes validation. Dates are intentions, not commitments.## Release status — 2026-10-23-[Kornia 0.9.0](https://github.com/kornia/kornia/releases/tag/v0.9.0) is released and-verified. The published PyPI wheel and source archive match the CI build and GitHub-assets. Fresh Python 3.11/3.13 installs passed imports and image I/O; the installed-wheel passed the CPU/MPS workflow smoke checks, including compiled RANSAC on CPU.-Stable and versioned documentation serve the 0.9.0 LLM files.--Development now targets `0.9.1.dev`. The next patch prioritizes confirmed regressions-and compatible fixes. With 0.9.0 out, the repair & deprecation window (step 2 of the-first guiding theme below) is open on `main`: the box, camera and augmentation-convention repairs land there under the existing stability policy. The external-conformance corpus and the proposed Tier A policy remain longer-term work. The-current release sequence and follow-ups are tracked in-[#4620](https://github.com/kornia/kornia/issues/4620).+[Kornia 0.9.0](https://github.com/kornia/kornia/releases/tag/v0.9.0) shipped and its+published artifacts were verified. The repair/deprecation window is open under the+existing [stability policy](https://kornia.readthedocs.io/en/latest/get-started/stability.html).+Use [#4620](https://github.com/kornia/kornia/issues/4620) for the current release sequence,+evidence, and follow-ups. Patch releases prioritize confirmed regressions and compatible fixes.## Guiding themes-Four engineering north stars shape the roadmap below.--1. **The reference core: conventions, conformance, tiers.** Geometric code has a- uniquely dangerous failure mode: small convention mistakes (`align_corners`,- pixel-center vs corner, (x,y) vs (row,col), normalized vs pixel coordinates,- rotation direction, homography normalization) produce code that *runs correctly- while being mathematically wrong* — and this is exactly the error class LLMs- reproduce. The program, in order, per API surface:-- 1. **Document** — every core op gets a Convention block in its docs plus- `test_convention_*` pinning tests, describing actual behavior including known- warts. The first batches have landed- ([#3924](https://github.com/kornia/kornia/pull/3924),- [#3926](https://github.com/kornia/kornia/pull/3926)); the canonical- [Conventions & Pitfalls](https://kornia.readthedocs.io/en/latest/get-started/conventions.html)- page is live. Behavior bugs found by the audit get dedicated issues.- 2. **Repair & deprecate** — one coordinated window fixes accumulated semantic and- default-value bugs, so downstream users face a single loud migration instead of- a drizzle of breaking changes. The window runs *under* the- [stability policy](https://kornia.readthedocs.io/en/latest/get-started/stability.html),- not around it: a deliberate change to a default or convention gets the- policy's deprecation treatment (at least one minor release of warnings,- landing at a 0.x minor boundary) — "coordinated" means the changes are batched- into one migration, not that the deprecation rules are waived. Correctness- fixes (NaN, crashes, wrong math, or a result that contradicts what the- operation is documented to do) use the policy's escape hatch and land when- ready, with a release note that says what the old behavior was.- 3. **Freeze** — after the window, a **Tier A ("Kornia Core")** set is declared:- symbols with the strongest guarantees (autograd, gradcheck, compile, dtype/- device correctness, explicit conventions, semantic stability). Tier A starts- brutally small and a guarantee is only claimed where CI enforces it.- **These tiers are proposed, not yet in force**: until the tier policy is- published after the window, the current- [stability policy](https://kornia.readthedocs.io/en/latest/get-started/stability.html)- (stable core / best-effort / experimental) remains the authoritative contract.-- Alongside this grows a **conformance corpus**: framework-neutral golden vectors- (inputs, expected outputs, tolerances, convention metadata) that external- implementations — JAX ports, Rust/Triton kernels, vendored copies, and- LLM-generated code — can validate against. Long-term, Kornia defining the- conformance tests for differentiable geometric vision may matter more than owning- every implementation.--2. **Compile-first (`torch.compile` / dynamo).** The numeric core (filters, color,- geometry, enhance, losses) is already largely compile-clean. The remaining work is- concentrated in the stochastic augmentation pipeline and the dynamic-shape feature- detectors, which branch on tensor values and break the graph. The geometric parameter- generators (`RandomAffine`, `RandomPerspective`, `RandomResizedCrop`) now compile- fullgraph; the data-dependent crops and the `AugmentationSequential` container still- break ([#5137](https://github.com/kornia/kornia/issues/5137)). Compile support is- claimed **per evidenced surface**: today that means the functional core, not the- augmentation classes as a class-level guarantee — many individual augmentations- already run fullgraph in the PR-time dynamo job (see the compile/export spine- below), but the remaining breaks and CUDA coverage keep the class-level claim- off the table — and docs state the scope explicitly.--3. **Export-first (ONNX).** ONNX export fails on the *same* patterns that break- `torch.compile`: data-dependent control flow, `.item()` calls, and dynamic shapes.- [#3722](https://github.com/kornia/kornia/pull/3722) demonstrated the fix — replacing- the stochastic apply path with `torch.where` blends and gating linear-algebra- fallbacks on `is_tracing()` — which advanced both goals in a single change. The- remaining spine work pays out to compile and export together.--4. **Performance, honestly measured.** The benchmark harness is now first-class:- `benchmarks/` measures kornia (eager + compiled) against OpenCV, torchvision v2,- albumentations, and PIL with median+IQR timings, hardware metadata, and an- auto-published results page — and it publishes where Kornia *loses* (CPU,- batch=1) alongside where it wins (large-batch GPU, differentiability, compiled- paths), so the page is citable by skeptics. Measurement drives the fix order:- the systemic finding is that the augmentation pipeline is **launch-bound, not- kernel-bound** (per-call wrapper orchestration can make throughput *fall* as- batch grows), so orchestration overhead is fixed first; then the measured kernel- outliers (`median_blur`, `canny`, `rotate`). For the non-differentiable- CPU/`uint8` regime an opt-in `kornia-rs` backend is the path to a step-change,- and hand-written Triton kernels are reserved for the small set of ops `inductor`- structurally cannot fuse.--A fifth theme, **breadth**, is community-driven. One boundary is stated openly:-**model-zoo expansion is frozen.** No new model-or VLM/VLA integrations while maintainer bandwidth concentrates on the core; shipped-wrappers (LoFTR, LightGlue, DISK, DeDoDe, SAM, XFeat, ALIKED, Kimi-VL, …) remain-available and maintained under a *usable-or-deleted* rule. The single exception-rule, applied everywhere in this document: **a new integration requires a named-maintainer sponsor who accepts ongoing ownership — a contributor's implementation-alone, however good, does not reopen the surface.** The freeze lifts when a-maintainer with model-work capacity joins the project. Contributions already in-flight before the freeze (an open issue plus a PR under review) are grandfathered-and finish under the rules they started under.--## Short term — 0.9.1 maintenance candidates--These are priorities to investigate and validate, not a promise that every item-will ship in 0.9.1. Confirmed downstream regressions take precedence.--- **Bilateral-filter half gradients:** restore accuracy for learnable tensor sigmas- without losing backend performance ([#6284](https://github.com/kornia/kornia/issues/6284)).- Float32 sigmas remain the documented workaround until a fix is verified.-- **Compiled RANSAC cache safety:** isolate the CPU-to-CUDA cache collision and- verify a fix or mitigation ([#6278](https://github.com/kornia/kornia/issues/6278)).- Separate `TORCHINDUCTOR_CACHE_DIR` directories per device, or `KORNIA_RANSAC_AOT=0`,- remain the current workarounds.-- **CUDA reliability:** triage the Kannala-Brandt TorchScript second-call hang- ([#6257](https://github.com/kornia/kornia/issues/6257)); consolidate the 29 recorded- pre-existing CUDA-half test failures into explicit tracking and coverage work.+1. **Reference core.** Pixel-centre, coordinate-frame, and sampling convention mistakes+ let code run while producing mathematically wrong results; agents can reproduce those+ mistakes. Document actual behavior and known defects, repair the contracts,+ then freeze a small dependable surface. Coordinate convention changes and migration+ examples under the stability policy; the repair window does not waive it. Convention+ tests and independent expected results are the foundation of a future portable corpus+ that JAX, Rust, Triton, and other implementations can validate against.+2. **Compile-first.** Design tensor paths that work with `torch.compile` without avoidable+ graph breaks. Claim support per evidenced surface, not for every augmentation or model.+ The [compile promise](TESTING.md#torchcompile-conformance-5819) defines what CI enforces.+3. **Export-first.** Treat ONNX graph construction and numerical runtime behavior as part+ of the implementation. Prefer designs that improve compile and export together;+ [ONNX conformance](TESTING.md#onnx-conformance-5819) defines the enforced scope.+4. **Performance, honestly measured.** Use [the benchmark methodology](benchmarks/README.md)+ to compare realistic workloads, publish losses as well as wins, and choose work from+ measured bottlenecks. Reduce augmentation orchestration overhead before adding kernels;+ specialized kernels need evidence that the compiler cannot do the job.++**Model-zoo expansion is frozen** while maintainers concentrate on the core. Shipped+wrappers remain maintained under a usable-or-deleted rule. A new integration requires+an explicitly named maintainer sponsor who accepts ongoing ownership; a contributor's+implementation alone does not reopen the surface. The freeze lifts when a maintainer+with model-work capacity joins. Contributions already in flight before the freeze+(an open issue plus a PR under review) are grandfathered under their original rules;+the named pre-freeze commitments are listed below.++**Tier A/B/C is proposed, not in force.** The current stable-core / best-effort /+experimental stability policy remains authoritative. A future Tier A starts small and+claims autograd, dtype/device, compile, and semantic guarantees only where CI enforces them.++## Correctness and backend support++**Maintain correct, useful behavior within Kornia's agreed scope.** Distinguish+mathematical defects, numerical instability, and upstream workarounds.++1. **Check the contract.** Establish supported inputs, output dtype, conventions, and+ accuracy requirements. Separate wrong mathematics or avoidable instability from+ rounding, dtype limits, and undefined behavior. Compare with plain PyTorch where+ applicable: a sum exceeding float16's range does not justify widening its output.+ This does not excuse unstable computation of a representable result.+2. **Do not expand support through bug fixes.** Do not add integer-input support or+ special paths solely for synthetic extremes: half-precision overflow far beyond+ image/coordinate ranges, `1e20` float32 image values or pixel coordinates, or a matrix+ scaled by `1e15`. These are examples, not universal magnitude cutoffs; `1e5` already+ exceeds float16's finite range. Stop implementation and explain the supported input form. Expanding+ scope requires an explicit maintainer decision backed by a concrete application.+ A synthetic failure is insufficient; documented exceptions remain supported.+3. **Check the existing solution first.** If a supported dtype conversion, parameter+ such as `num_iters`, or workflow adequately solves the reported need, do not add+ another implementation without demonstrated benefit. Value and maintenance cost+ can justify declining a proposal, not merely postponing it.+4. **Check upstream before adding a workaround.** Expected autocast precision changes+ and SVD backward limitations at repeated singular values are not by themselves PyTorch+ defects. Kornia owns choosing a formulation and working precision that meet its contract.+ Isolate suspected PyTorch failures+ on latest stable and an available next-version build (pre-release or nightly) on the+ affected backend; record unavailable checks. If fixed upstream, default to documenting+ affected versions and alternatives without a new workaround or silently weakening+ existing promises. Record accepted workarounds' upstream issue, verified scope,+ measured cost, and retirement/reassessment condition beside the code. This also+ applies to backend performance workarounds.+5. **Prove the correction and report consequences.** Derive expected results independently+ and pin conventions with `test_convention_*` tests. An unchanged or worse downstream+ benchmark does not disprove a correction. Report results with uncertainty where+ applicable, investigate regressions, and leave acceptance to a maintainer; release+ notes state accepted tradeoffs. Prefer a shared stable formulation; extra device,+ version, size, or grad-mode branches need a measured reason stated beside the branch.+6. **Choose the outcome explicitly.** Repair the implementation, document a limitation, propose+ a scope change, or make no change. Measure performance on affected and common+ unaffected paths. Use justified dtype tolerances, not blanket bitwise equality.+ Exposure sets priority, not whether a proven defect exists. Unknown user incidence stays unknown.++At degenerate or nonsmooth points, establish whether the value or derivative exists+and is unique. A finite fallback alone does not prove correctness; document the choice.+For ambiguous boundary behavior, consult the+[stability policy](https://kornia.readthedocs.io/en/latest/get-started/stability.html):+a proven contract violation uses the correctness-fix route; changing a working+convention uses deprecation. Missing documentation or variation across PyTorch versions+alone does not authorize a silent change; unresolved cases need a maintainer decision.++## Short term — maintenance and correctness candidates++Confirmed downstream regressions take precedence. These are investigation priorities,+not release commitments. Issue reservations and ownership remain in force; the linked+issues own live status and acceptance decisions.++- **Coordinates and sampling:** feature pixel centres+ ([#6536](https://github.com/kornia/kornia/issues/6536),+ [#6537](https://github.com/kornia/kornia/issues/6537)), measured on matching/pose tasks;+ depth-warp identity [#6317](https://github.com/kornia/kornia/issues/6317), coordinated+ with the existing [#6371](https://github.com/kornia/kornia/pull/6371) author.+- **Mathematical geometry:** thin-plate splines+ [#6404](https://github.com/kornia/kornia/issues/6404) and fundamental-matrix RANSAC+ degeneracy [#6574](https://github.com/kornia/kornia/issues/6574), including downstream+ effects and release treatment.+- **Supported execution paths:** compiled RANSAC cache safety+ [#6278](https://github.com/kornia/kornia/issues/6278) and failures established by current+ [precision evidence](https://kornia.readthedocs.io/en/latest/get-started/precision.html).CUDA-half support is not a blanket patch-release guarantee.-- **Post-release checks and documentation:** confirm the next scheduled cross-platform- PyPI-package test, retain the verified release evidence, and decide how stable/versioned- LLM documents should link to their matching documentation rather than `/en/latest/`.-- **Contribution documentation:** keep the social contract, technical guidance, and- project automation consistent and easy to understand.-- **Progressively enable more `ruff` rule sets** to raise code health- ([#2445](https://github.com/kornia/kornia/issues/2445)).-- **Docs modernization** — evaluate the migration to MkDocs- ([#3454](https://github.com/kornia/kornia/issues/3454)).-- **Model-zoo maintenance (best-effort tier; future Tier C).** Shipped integrations- must be usable or deleted — kept loading, tested, and honest (recent example:- repointing Kimi-VL to working weights). The 2025-era coverage-gap issues are- resolved; newly found maintenance work gets a current tracking issue with- acceptance criteria — no new integrations.-- **`help wanted` label audit.** Older issue templates auto-applied the label;- re-triage open issues so the label points to current, well-described work where- outside help would be useful.+- **Usable guidance and maintenance:** runnable workflows, version-correct documentation,+ coherent contributor/agent instructions, and maintained shipped models. Keep `help wanted`+ labels tied to current, well-described work. Release checks remain in #4620.## Medium term — ~6 months-- **The Repair & Deprecation window → Tier A v1.** *Open on `main` since 0.9.0.*- Execute the one coordinated release motion for the semantic and default-value- repairs accumulated by the audit (e.g. `warp_image_tps` `align_corners` default- [#3928](https://github.com/kornia/kornia/issues/3928), `pyrdown` output rounding,- inconsistent 3D-crop defaults, bbox width arithmetic- [#3934](https://github.com/kornia/kornia/issues/3934)) — each change with an- old-vs-new conformance vector pair, the stability policy's deprecation treatment- (at least one minor release of warnings before landing at a 0.x minor boundary),- and one collective migration note. Afterwards, publish the support-tier policy and- declare Tier A v1: small, explicit, CI-enforced. Until that publication the- current stability policy remains the authoritative contract.-- **The conformance corpus.** Define the framework-neutral format (per-dtype/device- tolerances, convention metadata), migrate the existing convention-pinning tests- into it, add semantic invariant tests- (`warp(inv(H), warp(H, img)) ≈ img`, `project(unproject(d, K), K) ≈ uv`,- `R @ R.T ≈ I`), and publish a docs page: *validate your (hand-written or- LLM-generated) geometry code against Kornia*.-- **The agent knowledge layer.** `AGENTS.md` is live; `llms.txt` and `llms-full.txt` are live- and benchmark-fed. After the final convention batch, ship a small set of validated- skills (image warping & homographies, batched differentiable- augmentation with transform tracking, camera/epipolar conventions, feature- matching) — all derived from the canonical docs, never duplicating them.-- **The compile / export spine.** *In progress — much of the augmentation surface now- compiles fullgraph.* The stochastic-apply path, the `_extract_device_dtype`/version-check- helpers, the transform-matrix blend, and the shape-changing crops (`Resize`, `CenterCrop`)- have all landed as genuine single-path fixes; common intensity ops (color jitter, solarize,- brightness/contrast, erasing, flips), `equalize`, and the geometric parameter generators- (`RandomAffine`, `RandomPerspective`, `RandomResizedCrop`) are fullgraph on the CI torch.- Remaining: the data-dependent tail — random-coordinate `RandomCrop`/`crop_by_indices` and- the `AugmentationSequential` container, including its random-permutation dispatch — which- needs redesign, not guards ([#5137](https://github.com/kornia/kornia/issues/5137)). On the export- side: solve multi-output ONNX export generically so tuple-returning modules (e.g. `Canny`,- YUV conversions) are no longer blocked, and converge on a single modern ONNX opset.-- **Dynamo tests in CI — landed for the compile-clean core.** A PR-time `dynamo` job now runs- the compile-clean augmentation/enhance/filter/color/loss/morphology tests under `inductor` on- the CI torch version, so a fullgraph regression is caught at PR time. Still to do: publish an- ONNX export conformance matrix (exportable / numerically-verified / blocked-with-reason) for- the public API, and widen the dynamo job beyond the core once model/feature paths are vetted.-- **Augmentation performance — orchestration first.** GPU profiling shows the deficit- vs torchvision on cheap augmentations is *not* the kernels: for- `RandomHorizontalFlip` the raw flip is ~22% of the module forward and the other- ~78% is per-call orchestration in the augmentation base (transform-matrix build,- the `where`-blend, dtype/shape bookkeeping). The highest-leverage work is a leaner,- fully-compilable base `forward` (a fast path that skips `compute_transformation`- for non-affine ops) plus CUDA-graph capture — one fix that lifts every- augmentation. Compiled kornia pipelines already beat torchvision v2 on GPU while- staying end-to-end differentiable (see the published benchmark page); killing- wrapper overhead extends that lead to the eager path everyone runs by default.-- **A `kornia-rs` augmentation backend (opt-in).** Add a backend selector (e.g.- `backend="rust"`) that routes non-differentiable, CPU, `uint8` augmentation through- `kornia-rs`, while the PyTorch path stays the default for GPU-batched,- differentiable, and float workloads. Upstream kernels are already fast (recent- `kornia-rs` releases beat OpenCV raw on warps); the current bottleneck is the- tensor↔image interop cost, and the dispatch only ships for ops where it wins- ≥5× including conversion. Sequencing is conformance-first: `kornia-rs` outputs are- validated against Kornia's golden vectors before any dispatch, making it the- conformance corpus's first external consumer.-- **Triton for the kernel-bound minority.** Hand-written kernels only where- `inductor` structurally cannot help and the benchmark data shows a real gap:- `median_blur` (selection networks), `canny` (data-dependent NMS + hysteresis),- possibly large-kernel morphology. Capped ambition (2–3 kernels), each with a- registered custom op, backward, and conformance vectors; opt-in experimental until- GPU CI can verify them.-- **Batched RANSAC.** Restructure the RANSAC hot loop to not need a compiler:- vectorize over hypotheses (sample K minimal sets, solve batched, score batched)- with chunked execution and confidence-based stopping. GPU-batched robust geometry- is core mission; the variants (eager, lazy-scripted, compiled-chunked, batched)- are benchmark-arbitrated.+- **Coordinated repairs and Tier A v1:** settle box, camera, sampling, and augmentation+ conventions with executable old/new examples and a collective migration note. Concrete+ cases include bbox width arithmetic ([#3934](https://github.com/kornia/kornia/issues/3934))+ and the split `align_corners` defaults in augmentation ([#4412](https://github.com/kornia/kornia/issues/4412)),+ both reserved for maintainer implementation. Follow+ the stability policy's warning period and minor boundary for deliberate changes;+ use its correctness exception only for proven defects. Publish tiers after the repairs.+- **Portable conformance corpus:** define inputs, independent expected results,+ tolerances, and convention metadata; migrate convention tests and add composition+ invariants such as projection/unprojection and rotation orthogonality. Publish how+ external implementations can validate against Kornia.+- **Knowledge for users and agents:** keep package help, canonical docs, `llms.txt`, and+ `llms-full.txt` aligned. Derive validated workflow skills from those sources rather+ than duplicate conventions; assess them through completed user tasks.+- **Compile/export design:** finish data-dependent augmentation paths,+ tracked in [#5137](https://github.com/kornia/kornia/issues/5137): partial application in+ `RandomCrop` (`p < 1`), `ColorJiggle`'s random order, and `AugmentationSequential`'s+ `random_apply` dispatch. Recorded fullgraph runs of `RandomAffine`, `RandomPerspective`,+ and `RandomResizedCrop` include CUDA successes; these are evidence for the tested cases,+ not a blanket CUDA promise. `crop_by_indices` needs an explicit `size` to avoid value-dependent output shapes.+ Dynamic-shape feature detectors remain separate design work.+ Redesign the shared implementation instead of accumulating guards. Handle multi-output+ export generically, converge on a modern ONNX opset, and extend CI promises only with evidence.+- **Augmentation throughput:** reduce wrapper/transform bookkeeping and kernel-launch+ overhead, with CUDA-graph capture where useful. The [recorded GPU profile](benchmarks/augmentation/README.md#known-improvement-opportunities-the-improve-later-list)+ attributes about 78% of `RandomHorizontalFlip` forward to orchestration and 22% to the raw+ flip; a transform-matrix fast path has partially addressed it. Remeasure after changes.+ Keep eager and compiled comparisons+ in the benchmark evidence rather than promising uniform speedups.+- **Optional specialized execution:** evaluate a `kornia-rs` backend for non-differentiable+ CPU/`uint8` workloads only after conformance validation and at least a 5x improvement+ including conversion. This is an explicit backend proposal, not permission to add integer+ paths to ordinary operators. Limit hand-written Triton work to 2–3 measured kernel+ bottlenecks, such as `median_blur` and `canny`, with registered ops, backward, and conformance+ evidence; experimental until validated. The [benchmark evidence](benchmarks/README.md#the-honest-reading-across-apple-silicon-l4-rtx-pro-6000-rtx-4090wsl2)+ requires remeasuring `rotate` with matched interpolation before treating it as an outlier.+- **Batched RANSAC:** vectorize hypothesis sampling, solving, and scoring with chunked+ execution and confidence-based stopping. Choose eager/scripted/compiled variants by+ correctness and benchmarks, without requiring a compiler for the basic batched path.## Long term — vision-- **The reference implementation for differentiable CV.** External implementations —- JAX ports, native kernels, vendored code, and code written by LLMs — validate- against Kornia's conformance data, and humans and coding agents consistently- produce *correct* geometry code from Kornia's documentation. Success is fewer- convention bugs in the wild, not more modules in the package.-- **A fully compilable, fully exportable core.** Every applicable Tier A tensor- operator runs under `torch.compile` without unnecessary graph breaks and exports- to ONNX where ONNX can represent its semantics, with verified numerical- equivalence — including the stochastic augmentation and dynamic-shape feature- paths that break today. Best-effort and experimental surfaces are covered as- evidence allows, never by blanket claim.-- **The fastest differentiable, GPU-batched augmentation stack**, with a published,- reproducible benchmark that states precisely the regime in which we lead.+- A reference implementation whose conformance data makes correct geometric vision+ easier to implement across frameworks, languages, and human/agent workflows.+ Success is fewer convention bugs in users' code, not more modules in the package.+- A compilable and exportable core with per-symbol, CI-enforced guarantees, scoped to+ semantics ONNX can represent; best-effort and experimental coverage grows with evidence.+- A leading differentiable, GPU-batched augmentation stack, with reproducible evidence+ stating exactly where it leads and where it does not.## Areas seeking contributors-We especially welcome help in these areas. The-[`help wanted`](https://github.com/kornia/kornia/labels/help%20wanted) label is one-place to look, although some older issues still need to be checked for current scope-and context. Search for related issues and pull requests before investing substantial-work, and see [CONTRIBUTING.md](CONTRIBUTING.md) for the social contract and technical-guidelines.--**Classical vision in the core domain (highest priority):** these strengthen exactly-the geometry/camera surface the project is built around.--- **Camera intrinsic calibration** (Zhang's method, checkerboard / ChArUco- detection). Kornia can undistort and solve PnP but cannot yet calibrate a camera- from scratch — the largest gap in the camera core.-- **Fiducial markers** (ArUco / ChArUco) — detection feeding directly into the- calibration and pose pipelines.-- **Classical tracking** — Lucas-Kanade, KCF- ([#1381](https://github.com/kornia/kornia/issues/1381)).-- Dense stereo matching, Hough transforms and Hough voting, contour/shape analysis,- template matching.--**Reference-core contributions:**--- **Benchmark results from your hardware** — run the- suite with `--contribute` and send the JSON; CUDA numbers from diverse GPUs are- especially wanted.-- **Convention pinning tests and conformance vectors** for core geometry operations,- and **corrective error messages** (upgrading bare shape asserts into errors that- state what was wrong, what was expected, which convention applies, and the likely- fix). Because these changes can define or alter public behavior, sharing the- intended contract early is useful.--**Augmentation parity** — low-priority and community-driven: Kornia does-not compete on generic augmentation breadth (the differentiated value is-differentiability, GPU batching, and transform tracking). Ideas in this area include-dropout-family transforms (CoarseDropout, GridDropout), grid/optical distortion,-weather effects (fog, sun-flare),-noise variants (ISO noise), and additional compression transforms.--**Learned models — frozen (see the guiding themes):**--- **Grandfathered model work.** Efficient LoFTR- ([#3282](https://github.com/kornia/kornia/issues/3282), PR- [#3621](https://github.com/kornia/kornia/pull/3621) under review) and SANDesc- ([#3752](https://github.com/kornia/kornia/issues/3752), pre-freeze maintainer- approval on the issue) were approved and started before the model-zoo freeze and- may continue under their existing scopes. They are exceptions honoring prior- commitments, not invitations for new model integrations.-- **Acknowledged gaps — not currently soliciting contributions.** Learned optical- flow (RAFT / SEA-RAFT), pose estimation, and object-detection breadth beyond- RT-DETR and YuNet are real gaps, listed for honesty. New model work remains- frozen until a maintainer accepts ongoing ownership of the integration.--**Code health & infrastructure:**--- Expanding `ruff` rule coverage ([#2445](https://github.com/kornia/kornia/issues/2445)).-- Migrating test classes to `BaseTester`- ([#2752](https://github.com/kornia/kornia/issues/2752)).-- `torch.compile` and ONNX-export coverage for existing operators.+Check [help wanted](https://github.com/kornia/kornia/labels/help%20wanted), existing issues,+and [the contribution rules](CONTRIBUTING.md) before implementation. A roadmap area is+not approval for a new API; establish the concrete need and check reservations first.++- **Documented CUDA and half-precision failures:** fix existing CUDA reports, open+ half-precision issues, and entries in the known-failure manifests for+ [`float16`](testing/half_precision_xfails/cpu_float16.txt) and+ [`bfloat16`](testing/half_precision_xfails/cpu_bfloat16.txt). Take CUDA work only when a CUDA device is available+ for reproduction and validation. Apply the [correctness policy](#correctness-and-backend-support)+ and [precision testing guidance](TESTING.md#7-half-precision-dtypes-float16--bfloat16);+ remove the corresponding xfail or manifest entry after verifying the fix.+- **Reference evidence:** convention tests, independent expected vectors, corrective+ error messages, and hardware benchmark contributions, especially CUDA. Use the+ benchmark suite's `--contribute` workflow.+- **Code health:** compile/export coverage for existing operators.+- **Augmentation breadth:** low-priority, community-driven gaps such as dropout,+ distortions, weather/noise, and compression effects; the differentiated core remains+ differentiability, batching, and annotation consistency.++**Grandfathered model work:** Efficient LoFTR+([#3282](https://github.com/kornia/kornia/issues/3282),+[#3621](https://github.com/kornia/kornia/pull/3621)) and SANDesc+([#3752](https://github.com/kornia/kornia/issues/3752)) retain their pre-freeze scopes.+Learned optical flow, broader pose/object detection, and VLM/VLA integrations are+acknowledged gaps, not open invitations; the sponsor rule in the guiding themes applies.## How to contribute-See [CONTRIBUTING.md](CONTRIBUTING.md) for the social contract, development setup,-and technical guidelines. Tell us what you checked and how AI helped, if you used it.-For a new algorithm, a reference such as a paper, OpenCV, or PyTorch makes the idea-and implementation easier to understand.+Start with [CONTRIBUTING.md](CONTRIBUTING.md). Keep implementation, testing, release,+and attribution procedures there and in the linked technical guides rather than+adding another copy to this roadmap.diff --git a/TESTING.md b/TESTING.mdindex c73018311..c2ff716f1 100644--- a/TESTING.md+++ b/TESTING.md@@ -2,9 +2,42 @@This document explains how to run the Kornia test suite, what the common pytest flags are, and how to handle recurring classes of test failures.+## Environment and validation tasks++Use [the contributor setup](CONTRIBUTING.md#developing-kornia) and Pixi for project+commands. Tasks call `uv`; Python packages under test live in `.venv` or `.venv-py*`,+not `.pixi`. The `py312` and `py313` features select `.venv-py312` and `.venv-py313`.+Dependencies are defined in `pyproject.toml`; after an update run the matching install task.++**CUDA:** Run `pixi run -e cuda install` to install the locked PyTorch as a CUDA build into the project `.venv`,+which is also used by `pixi run -e cuda test-cuda`. PyPI's Linux wheels are already CUDA builds, so on Linux the+task only syncs the lock, reinstalling every package so that removing a stale wheel cannot take files a locked+wheel needs. PyPI's Windows wheels are CPU-only, so on Windows the task then replaces torch with the same version+from the PyTorch CUDA index; a lock update to a new PyTorch has to update that version and index in `pixi.toml`+and the index in `pyproject.toml` too. Pixi's `.pixi/envs/cuda` supplies the tools, not the Python dependencies+under test. Commands run with `-e cuda` do not synchronize `.venv` automatically, so re-run the CUDA install task+after a dependency or lock change. On Windows this is what preserves the CUDA build, and a default-environment+command that synchronizes `.venv` replaces it, so re-run the task after one of those too. For focused CUDA tests,+use `pixi run -e cuda test-module tests/<path> --device=cuda`.++The locked build needs an NVIDIA driver from the R580 branch or newer and a Turing or newer GPU. Check+`torch.cuda.is_available()` after installing: when it is false, a `--device=cuda` run skips its tests and still+exits 0.++`pixi run pre-commit-all` runs every hook; `pixi run lint` runs only Ruff. Use+`pixi run typecheck` for types and `pixi run toml-fmt` for TOML formatting. Install the+Git hook with `pixi run pre-commit-install`. Task definitions live in [pixi.toml](pixi.toml).++`pixi run doctest` skips examples needing an uncached checkpoint. Use+`pixi run doctest-weights` (or `KORNIA_DOCTEST_DOWNLOAD=1`) to exercise them with downloads+(about 838 MB on a cold cache). PR CI uses the restored cache and skips misses; scheduled+runs on `main` at 00:23 and 12:23 UTC download and exercise those examples.+## Running Tests-Kornia uses [pixi](https://pixi.sh) to manage the test environment.+`test-module` forwards pytest arguments: a file, node ID, or `-k` expression narrows the+run. Start focused and expand for the affected callers. `KORNIA_TEST_OPTIMIZER=inductor`+enables dynamo/compile tests; the conformance options below are separate.```bash# All tests, default device (cpu) and dtype (float32)@@ -47,7 +80,8 @@ pixi run test-quick## Test Structure-All tests inherit from `testing.base.BaseTester` and implement a standard set of methods:+Use `testing.base.BaseTester` for operator tests. Include smoke, exception, shape,+numerical, gradient, and compile tests where applicable; not every change needs every kind:```pythonfrom testing.base import BaseTester@@ -64,6 +98,85 @@ class TestMyFunction(BaseTester):The `device` and `dtype` fixtures are injected automatically from the CLI options. Use `self.assert_close()` for tensor comparisons — it automatically selects tolerances appropriate for the dtype.+Keep numerical expected values self-contained: prefer a hardcoded literal with the+small generation snippet and source to requiring an optional reference library.+Optional-dependency integration tests, including ONNX tests, may use `pytest.importorskip`.+Preserve device/dtype with the injected fixtures. Keep tests deterministic, independent,+and proportional to the change; test batched behavior and derivatives where applicable.+Reusable helpers belong in `testing/`, not under `tests/`.++## Comparing a branch against another revision++kornia is installed in editable mode, so `import kornia` resolves through the editable finder to+the **primary checkout** regardless of the current directory. A measurement script that lives+outside a worktree therefore imports the primary tree even when you run it from the worktree:+`python /tmp/probe.py` puts `/tmp` first on `sys.path`, nothing shadows the editable install, and+an A/B comparison silently measures the same revision twice and reports "no difference".++Run comparison snippets from the worktree root, as stdin or `-c`, never as a file stored+elsewhere. Only then does the leading empty `sys.path` entry -- the working directory -- shadow+the editable install:++```bash+# From the primary checkout; select .venv-py* here if that is the environment under test.+comparison_python="$PWD/.venv/bin/python"+git worktree add /tmp/base-wt <base-revision>+cd /tmp/base-wt && "$comparison_python" - <<'EOF'+import sys+import kornia+print(sys.executable)+print(kornia.__file__) # must name the worktree, not the primary checkout+EOF+```++On Windows, use the environment's `Scripts/python.exe` instead of `bin/python`.+Print `kornia.__file__` inside every measurement block and check that it names the tree you+meant. A `cd` into the worktree is not by itself enough, and neither is putting the worktree on+`PYTHONPATH` while the script still lives somewhere else. The same applies to `sys.executable`+when more than one virtualenv is in play: name the interpreter explicitly rather than relying on+`PATH`.++## Gradient guards across PyTorch versions++`torch.clamp` is not a portable gradient guard: its derivative **at the bound** passes the incoming gradient+through (`1.0`) on torch 2.5.1 and 2.9.1 and returns `0.0` on 2.14.0. Wherever the bound is also the singular+point -- `clamp(min=0).sqrt()`, `clamp(-1, 1).acos()`, `clamp(-1, 1).asin()` -- the clamp bounds the value only,+so the unbounded derivative still reaches the backward pass as `inf` or `nan` on the older half of the supported+range while 2.14 masks it. A floor below the dtype's smallest subnormal is no guard either: `clamp(min=1e-12)`+underflows to `0` in `float16`. Substitute a safe argument before evaluating the singular expression;+take any value-only correction from a detached copy. `torch.where` does not protect an+unselected arm's backward pass: both differentiated arms must have finite derivatives.+For example, `safe = torch.where(x > 0, x, torch.ones_like(x))` followed by+`torch.where(x > 0, safe.sqrt(), torch.zeros_like(x))` chooses a zero derivative at zero+without evaluating `sqrt(0)` in autograd; that convention still needs a contract justification.+A CPU float32 run on a recent torch does not exercise the version difference -- the+2.5.1 leg is what discriminates. The measurements and the audit of the pattern are in #4229.++## Repository contract checks++### Public API inventory++`tests/api_surface.json` inventories the public names of stable-core modules; `tests/test_api_surface.py` rejects their removal until the inventory is updated in the same change. Run `tests.test_api_surface.regenerate()` to regenerate it. Keep tracked module keys (use `[]` when removing every name). Every module that declares `__all__` under a recorded package root has its own key; deleting such a module empties its key, and that empty key stays as the record. The `Import Surface` workflow also checks that each inventory removal corresponds to an actual export removal in the same diff. An inventory edit acknowledges an `__all__` removal only for the exact same module and name. For an `__all__` name of a module without its own key, such as a module outside the recorded package roots, add the exact module and name to `tests/api_surface_removals.json`, a JSON object mapping module names to lists of removed names (for example, `{"kornia.feature.dedode": ["DeDoDe"]}`). Only entries newly added relative to the merge base count, and each must match an actual `__all__` removal in that change; an unrelated source edit or a previously recorded acknowledgement does not count. Explicit acknowledgements do not replace updates to existing inventory entries, the deprecation window, or release notes.++### Dynamic-shape check messages++A `KORNIA_CHECK` message that formats a tensor size or an `int` argument specializes it under a dynamic-shape `torch.compile`, which then compiles a graph per value. Compare sizes with `KORNIA_CHECK_SAME_SIZE`, `KORNIA_CHECK_SIZES` or `KORNIA_CHECK_SHAPE`, or pass the message as `lambda: f"..."`. TorchScript rejects a `lambda`, so a function it compiles formats whole shapes instead, such as `{x.shape}`, which do not specialize. `tests/core/test_check_message_call_sites.py` enforces both and lists the functions TorchScript compiles.++### Docstring checks++The authoring rules live in [Docstring style](CONTRIBUTING.md#docstring-style).++What `tests/test_docstring_style.py` checks:++- every package of `kornia` is assigned to in scope or excluded (global);+- a converted module has no function or class, exported by an `__all__` or documented on a docs page, without a docstring;+- each public function and class of a converted module has a `See Also:` whose entries carry an explanation and name a kornia object, with no self-link or private target; an exception needs a non-empty reason, and an ``Alias of :func:`target`.`` or ``Deprecated: use :func:`target`.`` title line replaces the `See Also:`;+- every Python-domain object role (`:func:`, `:class:`, `:meth:`, `:attr:`, `:data:`, `:const:`, `:exc:`, `:obj:`) in a converted object's docstring, and in those of the methods, properties and attributes autodoc documents under a converted class, resolves as Sphinx resolves it. It must name either an object registered by the `.rst` pages under `docs/source`, or a torch, Python or NumPy object in the cached intersphinx inventories (`docs/source/_intersphinx`). Registered objects include the data attributes autodoc documents: enum members and dataclass fields under `:undoc-members:`, and variables with a `#:` comment or a docstring. An intersphinx object must be of a type the role links to: a function for `:func:`, a method for `:meth:`, an attribute or property for `:attr:`, and nothing for `:const:`. Only `:func:` and `:meth:` drop a trailing `()`. Roles in a catalog module docstring must import;+- no `kornia/**/*.py` file or `docs/source` page writes a shape tuple as `:math:`, comments included (global); a tuple that reads as a shape but is a value is listed with what it is in `MATH_NON_SHAPES` (`testing/docstring_rollout.py`), and an entry that no longer occurs fails;+- a catalog namespace's module docstring names every export of its `__all__` inside a role or a double-backtick literal, where a qualified name must be a path to that export (`torch.nn.functional.normalize` does not catalog `kornia.enhance.normalize`); the same word in plain prose or in single backticks does not count.++Read the Docs builds with `fail_on_warning: true` (`readthedocs.yml`) and the docs dependencies pinned in `uv.lock`, the same versions as `pixi run build-docs`, so a Sphinx warning fails the docs check. A module joins these checks when it is added to the lists in `testing/docstring_rollout.py`: `DOCSTRING_MODULES` (defining-module prefixes: `See Also:` and references) and `CATALOG_NAMESPACES` (namespaces whose `__all__` the module docstring must name). An object that needs no `See Also:` goes into `SEE_ALSO_EXCEPTIONS` with a reason. The package inventory is `IN_SCOPE_PACKAGES` and `EXCLUDED_PACKAGES`. The helpers are in `testing/docstring_style.py`; its `sphinx_registry` raises on an autodoc option it does not model, so a docs page that adds one (`:no-index:`, `:exclude-members:`, `:inherited-members:`) needs the registry taught first.+## Markers| Marker | Meaning |@@ -74,8 +187,41 @@ The `device` and `dtype` fixtures are injected automatically from the CLI option| `@pytest.mark.onnx_conformance` | Part of the ONNX conformance test; deselected unless `--onnx-conformance` selects packages || `@pytest.mark.compile_conformance` | Part of the torch.compile conformance test; deselected unless `--compile-conformance` selects packages |+### Selecting conformance packages++From the repository root after fetching the target branch, select changed packages and+their importers, including committed, staged, unstaged, and untracked files. Use+`upstream/main` from the contributor setup, or `origin/main` when `origin` is Kornia itself:++```bash+(+ set -eu+ conformance_target=upstream/main+ # For a direct clone of Kornia, use this instead:+ # conformance_target=origin/main+ conformance_base=$(git merge-base "$conformance_target" HEAD)+ conformance_paths=$(+ git diff --no-renames --name-only "$conformance_base" &&+ git ls-files --others --exclude-standard+ )+ printf '%s\n' "$conformance_paths" | pixi run python .github/scripts/conformance_packages.py onnx+ printf '%s\n' "$conformance_paths" | pixi run python .github/scripts/conformance_packages.py compile+)+```++The selectors use Pixi's Python so they can parse the repository's Python syntax.+The subshell stops if the base cannot be resolved; check the selected remote and fetch it+before retrying. `--no-renames` includes both the old and new paths of a moved file, as CI does.+Each command prints the corresponding conformance option's package value (`all`, a+comma-separated list, or empty when no promised operator is affected). Recompute after edits.+### ONNX conformance (#5819)+Before changing export behavior, inspect `kornia/onnx/`, its mixins in `kornia/core/`,+and existing ONNX tests. Development uses optional `onnx`, `onnxruntime`, and+`onnxscript`; verify graph construction/export and runtime behavior when both change.+Use the [package selection](#selecting-conformance-packages) for changed packages and their importers.+`tests/onnx/test_conformance.py` holds kornia's ONNX promise: every *promised* case -- a record of the surveysnapshot `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`)@@ -116,6 +262,9 @@ promised operator is a regression to fix.### torch.compile conformance (#5819)+Run this check for changed packages and their importers using the+[package selection](#selecting-conformance-packages).+`tests/test_inductor_conformance.py` holds the torch.compile promise the same way: every record of the survey snapshotwith 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@@ -150,7 +299,7 @@ conformance jobs run with `--timeout=600`.**Effect on tests.** Numerically sensitive tests that compare float32 outputs of matrix operations against hardcoded expected values (or against a CPU reference) can fail because the accumulated rounding error exceeds the test tolerance.-**In Kornia's test suite.** TF32 is **off by default**. Pass `--tf32` (or set `KORNIA_TEST_TF32=true`) to enable it. Tests that are known to be sensitive to TF32 are marked `@pytest.mark.tf32`; without `--tf32` they are marked `xfail` so the suite stays green.+**In Kornia's test suite.** TF32 is **off by default** for both matmul and cuDNN convolutions. Pass `--tf32` (or set `KORNIA_TEST_TF32=true`) to enable it. Tests that are known to be sensitive to TF32 are marked `@pytest.mark.tf32`; without `--tf32` they are marked non-strict `xfail`, so a default run reports neither their failure nor their recovery.**Fixing a TF32-sensitive test.** Prefer fixing the test data over relaxing tolerances:@@ -203,16 +352,11 @@ will fail on CUDA/MPS even though the code is correct.**Affected operations.** Histogram-based orientation estimators (`LAFOrienter`), ALIKED backbone (scatter/pool ops), and any custom op that uses `torch.scatter_add` or `atomicAdd` on CUDA.-**Fix.** Pass `nondet_tol` to gradcheck:-```python-# In a test using self.gradcheck():-self.gradcheck(fn, inputs, rtol=1e-3, atol=1e-3, nondet_tol=1e-3)--# In a test calling torch.autograd.gradcheck() directly:-torch.autograd.gradcheck(fn, inputs, eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True, nondet_tol=1e-3)-```--A value of `1e-3` is usually sufficient; it should not exceed `atol`.+**Use `self.gradcheck()`.** `BaseTester` supplies `nondet_tol=1e-10` for CUDA inputs+when the caller does not set it; CPU keeps zero. This covers measured rounding from+ordinary CUDA kernels without changing which kernels are tested. If an operation needs+more, measure the discrepancy and justify its tolerance in the test instead of applying+an arbitrary blanket relaxation. See `CUDA_GRADCHECK_NONDET_TOL` in `testing/base.py`.---@@ -427,6 +571,18 @@ When an MPS failure is fixed, remove its line from `mps_float32.txt`. When a tes- **Seed the RNG** when the test compares against reference values: `torch.manual_seed(seed)`.- **Generate random inputs on CPU** then move to device, to avoid device-specific RNG sequences.- **Use realistic inputs**: positive depths, in-bounds pixel coordinates, valid rotation matrices, and sensible intrinsic matrices.-- **Avoid hardcoding CUDA expected values** computed from CPU runs — they will differ.-- **Use `nondet_tol`** in `gradcheck` for ops that use CUDA atomics.-- **Check the error magnitude** before relaxing tolerances: only relax `atol`/`rtol` if the maximum observed error is well below 0.01, and document why.+- **Use independent expected values** from the mathematical definition or an appropriate reference, often at higher precision; another run of the implementation is not an independent oracle.+- **Use `self.gradcheck()`**; if CUDA nondeterminism exceeds `BaseTester`'s default, measure it and justify any larger `nondet_tol`.+- **Justify tolerance overrides** using dtype, scale, conditioning, and the algorithm's accuracy requirements. Measure the discrepancy and keep the test sensitive to regressions.++## Diagnosing reported problems++Start with a minimal reproduction and the narrowest relevant test. Do not claim a failure is pre-existing until you have compared against the relevant base revision safely.++Ask only for environment details that help the diagnosis: kornia, PyTorch, and Python versions; OS family; device backend; CUDA availability/version; and GPU model when relevant. Prefer the same privacy-conscious command used by the bug template:++```bash+python -W ignore -c "import kornia, platform, sys, torch; gpu=torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'none'; backend=torch.version.cuda or getattr(torch.version, 'hip', None); print(f'kornia {kornia.__version__} | torch {torch.__version__} | python {sys.version.split()[0]} | OS {platform.platform()} | CUDA/ROCm {backend} (available={torch.cuda.is_available()}, GPU={gpu}) | MPS={torch.backends.mps.is_available()}')"+```++Before asking a user to share broader diagnostic output, tell them to preview and redact it. Do not request usernames, home or project paths, environment variables, tokens, internal hostnames, or names of private data and models.diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex 4621375bb..88bac1166 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -7,7 +7,7 @@ CUDA, float16 and bfloat16 supportThe module table below counts entries in the Linux CPU known-failure manifests(`cpu_float16.txt <https://github.com/kornia/kornia/blob/main/testing/half_precision_xfails/cpu_float16.txt>`_,`cpu_bfloat16.txt <https://github.com/kornia/kornia/blob/main/testing/half_precision_xfails/cpu_bfloat16.txt>`_), pinned to Python 3.11 and PyTorch 2.15.0.-There are **243 float16 and 255 bfloat16 recorded failures**. These are parametrized test cases, not counts of+There are **242 float16 and 255 bfloat16 recorded failures**. These are parametrized test cases, not counts ofunsupported functions. `#4153 <https://github.com/kornia/kornia/issues/4153>`_ tracked them until it was closed on2026-10-18; no single issue tracks the remaining entries.No CI job covers CUDA or MPS half precision; CPU results do not establish support on those backends. A local CUDA