π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Avoid changelog merge conflicts with per-PR fragments (#4513)
Dmytro Mishkin060d8461440e
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex 7ccd58b46..36d8e24ff 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -2,6 +2,11 @@<!-- Explain the problem and the change. A few clear sentences are enough. -->+<!-- For user-visible changes, add changelog.d/<PR>.<type>.md (added, fixed, or breaking).+Before a PR number exists, use +unique-name.<type>.md and rename it before merging.+Use PR numbers, not issue numbers: generated links point to pull requests.+For internal changes without a fragment, explain why and ask for the no-changelog label. -->+## Related issue or discussion<!-- Link one if it exists, for example: Fixes #123. This is optional. -->diff --git a/.github/scripts/check_changelog.py b/.github/scripts/check_changelog.pynew file mode 100644index 000000000..b305e8dbc--- /dev/null+++ b/.github/scripts/check_changelog.py@@ -0,0 +1,136 @@+#!/usr/bin/env python3++# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Check changelog fragment names and require one for each pull request.++Towncrier builds the fragments in a separate CI step. This check keeps its+input predictable and makes the per-PR policy explicit: a normal PR must add+or update a fragment named for its own number and leave the assembled changelog+to release PRs. The ``no-changelog`` label is reserved for internal work and+release PRs; it waives those two rules. It never permits malformed fragments.+"""++from __future__ import annotations++import argparse+import re+import subprocess+import sys+from pathlib import Path++FRAGMENT_DIR = Path("changelog.d")+README = "README.md"+IGNORED_FILES = {".DS_Store", README}+FRAGMENT_NAME = re.compile(r"(?:[0-9]+|\+migration-[0-9]+)\.(?:added|fixed|breaking)\.md\Z")+++def fragment_paths(root: Path = Path(".")) -> list[Path]:+ """Return every fragment candidate, excluding the contributor guide."""+ directory = root / FRAGMENT_DIR+ if not directory.is_dir():+ return []+ return sorted(path for path in directory.iterdir() if path.name not in IGNORED_FILES)+++def validate_fragments(root: Path = Path(".")) -> list[str]:+ """Return policy violations for the complete fragment directory."""+ errors: list[str] = []+ directory = root / FRAGMENT_DIR+ if not directory.is_dir():+ return [f"{FRAGMENT_DIR} is missing"]++ for path in fragment_paths(root):+ relative = path.relative_to(root)+ if not path.is_file() or not FRAGMENT_NAME.fullmatch(path.name):+ errors.append(+ f"{relative}: fragment names must be <PR>.(added|fixed|breaking).md; "+ "only reserved +migration-<number> files may use an orphan prefix"+ )+ continue+ try:+ content = path.read_text(encoding="utf-8")+ except UnicodeDecodeError:+ errors.append(f"{relative}: fragment must be UTF-8 text")+ continue+ if not content.strip():+ errors.append(f"{relative}: fragment must not be empty")+ return errors+++def changed_paths(base_ref: str) -> set[Path]:+ """Return all paths changed since the PR merge base, including deletions."""+ merge_base = subprocess.run( # noqa: S603+ ["git", "merge-base", base_ref, "HEAD"], # noqa: S607+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ diff = subprocess.run( # noqa: S603+ ["git", "diff", "-M", "--name-only", "-z", f"{merge_base}..HEAD"], # noqa: S607+ check=True,+ capture_output=True,+ text=True,+ ).stdout+ return {Path(path) for path in diff.split("\0") if path}+++def has_current_pr_fragment(paths: set[Path], pr_number: int) -> bool:+ """Whether this PR changed a valid fragment that credits itself."""+ prefix = f"{pr_number}."+ return any(+ path.parent == FRAGMENT_DIR+ and path.is_file()+ and path.name.startswith(prefix)+ and FRAGMENT_NAME.fullmatch(path.name)+ for path in paths+ )+++def main(argv: list[str] | None = None) -> int:+ """Run the changelog policy check."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base-ref", required=True, help="Base branch ref, such as origin/main")+ parser.add_argument("--pr-number", required=True, type=int, help="Current pull request number")+ parser.add_argument(+ "--skip-presence",+ action="store_true",+ help="Allow an internal or release PR to omit its fragment and edit CHANGELOG.md",+ )+ args = parser.parse_args(argv)++ errors = validate_fragments()+ if not args.skip_presence:+ changed = changed_paths(args.base_ref)+ if not has_current_pr_fragment(changed, args.pr_number):+ errors.append(+ f"no changed changelog.d/{args.pr_number}.(added|fixed|breaking).md fragment found; "+ "add one for a user-visible change or apply the no-changelog label for an internal or release PR"+ )+ if Path("CHANGELOG.md") in changed:+ errors.append("ordinary PRs must not edit CHANGELOG.md; assemble it only in a labeled release PR")++ for error in errors:+ print(f"::error::{error}")+ if errors:+ return 1+ print("Changelog fragments are valid.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/check_import_surface.py b/.github/scripts/check_import_surface.pyindex 5835cc337..5babcec0e 100644--- a/.github/scripts/check_import_surface.py+++ b/.github/scripts/check_import_surface.py@@ -842,7 +842,7 @@ def main(argv: list[str] | None = None) -> int:print(f"::error file={report.path}::Removed from __all__: {sorted(tracked)}. If deliberate, "f"drop these names from this module's {INVENTORY_PATH} entry in this PR. "- f"Honor the deprecation window and document the removal in CHANGELOG.md."+ f"Honor the deprecation window and document the removal in changelog.d/<PR>.breaking.md.")stale = untracked & old_explicit.get(_module_name(report.path), set())if stale:@@ -857,7 +857,7 @@ def main(argv: list[str] | None = None) -> int:f"::error file={report.path}::Removed from __all__: {sorted(untracked)}. Add these exact "f"module/name pairs to {REMOVALS_PATH}; they have no exact-module inventory entry. "f"Update affected package inventory entries too, honor the deprecation window, "- f"and document the removal in CHANGELOG.md."+ f"and document the removal in changelog.d/<PR>.breaking.md.")else:print(f"::notice file={report.path}::Removed from __all__ (exempt, see comment above): {unrecorded}")diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.ymlnew file mode 100644index 000000000..796d4c071--- /dev/null+++ b/.github/workflows/changelog.yml@@ -0,0 +1,50 @@+name: Changelog++on:+ pull_request:+ branches:+ - main+ types:+ - opened+ - synchronize+ - reopened+ - labeled+ - unlabeled++permissions:+ contents: read+ pull-requests: read++jobs:+ check:+ name: Check changelog fragments+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ with:+ # The check compares the PR to its merge base, rather than the moving main tip.+ fetch-depth: 0++ - uses: actions/setup-python@v7+ with:+ python-version: '3.12'++ - name: Check fragment names and PR entry+ env:+ BASE_REF: origin/${{ github.base_ref }}+ NO_CHANGELOG: ${{ contains(github.event.pull_request.labels.*.name, 'no-changelog') }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ run: |+ args=(--base-ref "$BASE_REF" --pr-number "$PR_NUMBER")+ if [[ "$NO_CHANGELOG" == "true" ]]; then+ args+=(--skip-presence)+ fi+ python3 .github/scripts/check_changelog.py "${args[@]}"++ - uses: prefix-dev/[email protected]+ with:+ pixi-version: v0.40.0+ cache: true++ - name: Build draft release notes+ run: pixi run changelog-previewdiff --git a/AGENTS.md b/AGENTS.mdindex a6acde98e..2e210173c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -127,7 +127,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather## Documentation and generated examples-- `CHANGELOG.md` is maintained per change, not at release time. A user-visible change adds an entry under `## Unreleased` citing its PR number, under the Keep a Changelog headings the file already uses (`Added`, `Bug fixes`, `Breaking changes`); a breaking change says what used to happen as well as what happens now.+- 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.- 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.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d786e5b09..d8358e1b9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,1538 +4,12 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).-****--## Unreleased+Pending changes live in [changelog.d](changelog.d/README.md).+Run `pixi run changelog-preview` to read the assembled notes.-### Added+****-* Optional-dependency extra `kornia[image]` installs Pillow for PIL-backed image input/output,- display helpers and `kornia.io.sample`; missing-Pillow errors now name the extra to install, and the unused- `DinoVisionTransformer.forward_features_list` list path has been removed. (#4464)-* Documented the shared 2D contract of `kornia.augmentation` β the `(B, C, H, W)` float working layout- and `keepdim`, `p` / `p_batch` / `same_on_batch`, where random parameters are drawn and how `torch.manual_seed`- and `params=` replay them, what a module serializes, and what `AugmentationSequential` does with each data key- (layouts, the inclusive `xyxy_plus` boxes and integer-centre flips, nearest masks, `extra_args`, `inverse`) β- as Convention blocks on the base classes and containers, with the canonical randomness and serialization- statements on the Conventions & Pitfalls page and executable pins. The contracts distinguish sampler and- returned-parameter placement, trainable range parameters, application-time replay exceptions, padding labels,- information lost by rotated tensor boxes, mask-list gates, mixed mask dtypes, dictionary-key exceptions,- and the transplantation constructors. Scope corrections and regression tests cover mix-specific contracts,- inverse support, mask erasing/filtering/precision, nested matrices, serialization and sampler limitations;- the container, `p_batch`,- `set_rng_device_and_dtype`, `state_dict` and `B = 0` defects are tracked in dedicated issues. (#4452)-* Implemented the exported Brown-Conrady, Kannala-Brandt K3, and Orthographic sensor camera models,- including distortion/projection plumbing, intrinsic matrices, and batched project/unproject support. (#4284, #4377)-* New "Camera and world conventions across the ecosystem" page cataloguing the pixel-centre, axis- and extrinsics conventions of OpenCV, COLMAP, OpenGL, ARKit, ARCore, PyTorch3D and Direct3D with the- kornia converter for each, plus the baked `align_corners` rows for the depth and undistortion warps on- the Conventions & Pitfalls page. (#4315)-* Documented the `kornia.sensors.camera` conventions (`Vector`-typed inputs, the per-model `params`- layout, the shared half-pixel `scale` rule, and the pinhole mapping shared with `kornia.geometry.camera`,- including its camera-axis broadcasting, projection rounding and zero/near-zero depth differences) and- added executable pins, with the unimplemented models tracked in a dedicated issue; the three non-pinhole- models now appear on the sensors documentation page. (#4318)-* Documented depth and stereo conventions (the two meanings of depth, the `(B, 3, H, W)` versus- `(B, H, W, 3)` layouts, the opposite source/destination naming of `warp_frame_depth` and- `DepthWarper`, the rectified stereo `Q` matrix) and added executable pins for `kornia.geometry.depth`- and `StereoCamera`, including dtype promotion, extra-axis broadcasting, subpixel border sampling,- and singular stereo reprojection. Remaining defects are tracked in dedicated issues. (#4317)-* Documented camera distortion and calibration conventions (normalized versus pixel inputs, the- coefficient layout, the `new_K`/`K` roles, the iterative inverses) and added executable pins for- `kornia.geometry.camera`'s distortion models and `kornia.geometry.calibration`, with the- tilt-projection, Kannala-Brandt Jacobian and float16 defects tracked in dedicated issues. (#4312)-* Documented camera projection-core conventions (`PinholeCamera` frames, integer pixel centres, the two- meanings of depth, the `z = 0` policies) and added executable pins for `kornia.geometry.camera`'s- projection core, with the known scale-rule, aliasing, guard and legacy-API limitations tracked in- dedicated issues. (#4294)-* API reference entries now carry a **Try in browser** badge that links a function, its- `nn.Module` counterpart or a browser model to its interactive page on the kornia.org- playground, so readers can run the operator on a sample image without installing anything.- The set of linked APIs is a snapshot of the playground in `docs/source/_playground_links.json`,- refreshed by `docs/generate_playground_links.py`. (#4333)-* Optional-dependency extras `kornia[onnx]` and `kornia[sd]` declare the third-party packages that- the ONNX and Stable-Diffusion-dissolving wrappers lazily import, and are documented on the- installation page. Missing-dependency errors now name the extra to install, and `dev` no longer- pulls `diffusers` and `transformers`. (#4301)-* KimiVL and SigLIP2 builders load their safetensors checkpoints with kornia's own downloader- (`kornia.core.download_hf_file`/`download_file_from_url`, which share the retrying, rate-limit-aware- cache every other checkpoint uses) and a pure-torch reader (`kornia.core.load_safetensors`);- `huggingface_hub` and `safetensors` are no longer needed. Both were imported without ever being- declared as dependencies, so `KimiVLBuilder.from_pretrained_hf()` and- `SigLip2Builder.from_pretrained_hf()` used to raise `ImportError` on a plain `pip install kornia`.- The checkpoints move to torch's hub cache as a result; see *Breaking changes*. (#4293)-* `kornia.models.RRDBNet`, a vendored Real-ESRGAN generator; `RRDBNetBuilder` no longer needs `basicsr`. (#4292)--* Repeatable Oxford affine local-feature benchmarks for SIFT, SIFT-AffNet-HardNet, and- KeyNet-HardNet, with eager/compiled median/IQR speed, homography corner error, and JSON output;- historical scale-space SIFT CPU/CUDA batch-runtime comparisons and plotting. (#4254)--* Documented bbox/Boxes geometry-operation conventions and added executable pins for transforms,- NMS, padding, clipping, and area filtering, including known unbatched-input limitations. (#4245)--* Documentation pages now provide search-specific titles and descriptions, canonical tutorial links, and a- canonicalized redirect from the retired highlighted-features page. (#4226)--* `kornia.feature.laf_is_filled(laf)` returns the `(B, N)` mask of the slots a detection filled, the complement- of a detector's zero-LAF padding. Fixed-shape detectors pad the slots no detection filled with an all-zero LAF,- and those slots must be dropped before matching -- their descriptors are identical to one another, so they match- each other at zero distance and a mutual nearest-neighbour test does not reject them. `LocalFeature.forward`'s- docstring already required callers of a hand-rolled pipeline to do this and gave them the expression to copy;- they can now call the function instead. It replaces the same expression at four internal sites in- `kornia/feature`. (#4223)--* `benchmarks/feature/laf_ops.py` microbenchmarks seven public LAF operations- (`laf_from_center_scale_ori`, `make_upright`, `ellipse_to_laf`, `laf_to_boundary_points`,- `laf_is_inside_image`, `extract_patches_simple`, `extract_patches_from_pyramid`) as kornia eager vs- `torch.compile`, and its CPU and CUDA runs are the first committed non-Apple result set, so the docs- performance page now shows CUDA numbers. The page labels its throughput column from a new optional- `units` metadata key (`LAFs/s` here, `items/s` when absent) and identifies a row by every config field- that varies within a result file rather than by `(op, batch)` alone, which a suite sweeping a second- axis at a fixed batch would otherwise collapse onto one row. `run_batch_sweep` gained `label_fn`,- `items_fn` and `units` so such a suite can use the shared sweep; the existing callers are unchanged.- (#4119)--* Linux CPU half-precision CI now uses explicit reproducible profiles, exact phase/exception manifests, complete- lifecycle verification, and guarded candidate-only baseline regeneration. (#4154)-* The documentation site was rebuilt on `pydata-sphinx-theme` with a top navigation bar- (Learn / API / Models plus Ecosystem, About and Support menus), a redesigned landing page, a- restructured API reference with per-topic subpages, and a long list of fixed doc examples and- removed dead interactive demos. Old deep links into the split module pages- (e.g. `augmentation.module.html#kornia.augmentation.RandomAffine`) are forwarded to the subpage- that now documents the object, so existing links keep resolving. The furo layout stayed available- behind `KORNIA_DOCS_THEME=furo` until #4304 removed that fallback. (#4155)-* An **Adoption** page (`community/adoption`) listing the most-starred GitHub repositories and- packages that depend on kornia, rendered at build time from `docs/source/_data/dependents.json`;- `docs/fetch_dependents.py` refreshes that snapshot from GitHub's dependency graph. (#4155)-* Dynamo ONNX export (`torch.onnx.export(..., dynamo=True)`) now covers a much larger part of the- library: about 140 additional operator cases in the export survey capture, pass the ONNX checker- and match eager execution under onnxruntime. Operators that failed graph capture or had no ONNX- lowering gained an export-time path that returns the same values eagerly: matrix inverses up to- 4x4 use a closed-form adjugate instead of `aten::linalg_inv` (`warp_perspective3d`,- `warp_affine3d`, `rotate3d`, `affine3d`, `get_projective_transform`, `invert_affine_transform`,- `denormalize_homography`, `symmetric_transfer_error`, `safe_inverse_with_mask`, `DepthWarper`,- `PinholeCamera`, `StereoCamera`, `NamedPose`, `ImageRegistrator`, `ParametrizedLine.intersect`- and the `Se2`/`Se3`/`So2` groups); `MedianBlur`/`median_blur` select the median through `sort`;- `HausdorffERLoss`/`HausdorffERLoss3D` pool through `amax` (which also makes the 3D loss run on MPS); `distance_transform` avoids `hypot`;- `match_nn`/`match_mnn`/`DescriptorMatcher` avoid `cdist`; the mutual-information losses, the- Bessel kernels, `solve_quadratic`, `matrix_cofactor_tensor`, `decompose_essential_matrix_no_svd`,- `distort_points`/`undistort_points`/`undistort_image`, `Boxes`/`Boxes3D` (`from_tensor`,- `to_mask`), `bbox_to_mask3d`, `mean_iou_bbox`, `conv_soft_argmax2d` with a tensor temperature,- `JPEGCodecDifferentiable`, `ZCAWhitening` (`transform`/`inverse_transform`), `BoxFiltering`,- `MotionBlur3D`, `center_crop`/`crop_and_resize`/`crop_by_transform_mat3d` and the- `OriNet`/`LAFOrienter`/`LAFAffNetShapeEstimator`/`HardNet`/`HardNet8`/`SIFTFeature`/- `LAFDescriptor`/`DeDoDe` feature stack are branch-free or guard their data-dependent checks with- `kornia.core.utils.is_exporting()`. Among augmentations, `LongestMaxSize`, `SmallestMaxSize`,- `RandomCrop`, `RandomResizedCrop`, `RandomAffine3D`, `RandomRotation3D`, `RandomMotionBlur3D`,- `RandomJPEG`, `RandomMedianBlur`, `RandomPlanckianJitter` and `AugmentationSequential` with- crops or boxes now export, and `LightGlue` exports once `depth_confidence`/`width_confidence`- pruning is disabled. Behavior notes: `Se2`/`Se3`/`So2`/`ParametrizedLine` built from a tensor- that already carries autograd history (`Se2.exp(v)`, `ParametrizedLine.through(p0, p1)`) keep- that history: the tensor is registered as a buffer instead of being re-rooted as an- `nn.Parameter`, so `.to()`, `state_dict()` and `load_state_dict()` still reach it under the same- key but it no longer appears in `parameters()`; `kornia.core.utils.is_exporting()` falls back to- `is_compiling()` on torch < 2.6, which has no export flag (inside a Dynamo trace newer torch- folds its flag to `True` for `torch.compile` as well, so the export-safe paths are what a- compiled graph contains on every supported version); under export `crop_by_indices` with a- `size` resamples the crop and without one keeps the eager path, `distort_points`/- `undistort_points` always apply the tilt term (a no-op when the coefficients are zero) and- `normalize`/`denormalize` accept a 1-D `(C,)` mean/std; `matrix_cofactor_tensor` returns exact- cofactors for singular matrices instead of raising when every matrix in the batch is singular.- (#4182)-* An **ONNX, torch.compile and torch.export support** page under Resources (`get-started/export-support`)- lists every surveyed public operator, grouped by package and section, with its dynamo ONNX export,- `torch.export` and `torch.compile` outcome, the cause of each failure and a search box with result- filters. It is rendered at build time from the committed snapshot- `docs/source/_data/export_support.json`; `docs/export_support/run.py` reruns the survey to refresh- it. (#4182)-* Every page in the **Models** section of the docs now opens with the shortest script that runs the- model and a figure of its output on a real input, with the paper card moved to the bottom. The- figures are rendered by `docs/generate_model_examples.py` and committed under- `docs/source/_static/img/models/`, so the docs build needs neither the weights nor the sample- images. (#4178)-* The blocking MPS CI gate now runs on torch 2.14.0 instead of 2.9.1, on the `macos-15` image- instead of `macos-latest`, and its recorded failure baseline drops from 200 entries to 14.- torch 2.14.0 adds MPS kernels for `grid_sample`'s 2-D and 3-D backward passes, for- `padding_mode="border"` and 5-D `mode="nearest"` sampling, and for the eigen/QR/LU/SVD family- (`eigh`, `svd`, `svdvals`, `qr`, `lu_solve`, `lstsq`, `cholesky_solve`, `matrix_exp`), so most of- what used to fail on Apple silicon now runs there natively. What is still *pinned* in the- baseline: `torch.linalg.eigvals`, which has no MPS kernel and keeps the 5-point essential-matrix- solver off the device, and the `yuv420`/`yuv422` empty-input reshape defect. Separately,- `tests/geometry/test_ransac.py` is *skipped* rather than pinned β it aborts the process on the- runners' paravirtualized GPU, and a `SIGABRT` has no exception type to record- ([#4204](https://github.com/kornia/kornia/issues/4204)); the skip costs 9 tests that pass on real- Apple hardware, and `--run-mps-process-abort` runs them locally. The underlying limit is that a- **batched** `torch.linalg.svd`/`svdvals`/`lstsq` fails to build a Metal pipeline once its input- holds 8192 elements or more, which keeps `RANSAC`'s batched minimal solvers off the device- ([#4201](https://github.com/kornia/kornia/issues/4201)); a single unbatched matrix is unaffected- at any size. The image stays on `macos-15`: on `macos-latest` (macOS 26) the runner's *virtual*- GPU cannot compile the Metal 4 cooperative-tensor shaders torch 2.14 emits, which fails 664- tests β a physical M1 on macOS 26 compiles them fine. kornia still supports torch 2.5.1, so the- in-tree MPS workarounds stay. (#4202)--### Breaking changes-* `PatchSequential` now preserves the batch size in both padding modes. `same` preserves the input- spatial size and `valid` keeps only the complete, centred grid region. Previously, a `(2,3,8,8)`- input on a `(3,3)` grid produced `(2,3,7,7)` with `same` (now `(2,3,8,8)`) and `(2,3,8,8)` with- `valid` (now `(2,3,6,6)`). With `valid`, a `(2,3,6,8)` input on a `(4,4)` grid changed the batch- size to produce `(3,3,6,6)`; it now produces `(2,3,4,8)`. Geometric children may move temporarily- padded zeroes into the retained image. `restore_from_patches` now defaults to `self.grid_size`- instead of `(4,4)` and raises `ValueError` for a mismatched patch count instead of inferring a- different batch size or failing later in reshape. `forward_parameters` accepts both image- `(B,C,H,W)` and patch `(B,N,C,h,w)` shapes; parameter generation now covers `B*N` patch rows rather- than `B*C`, so fixed-seed outputs and RNG consumption can change. Refs #4421. (#4460)--* Removed the unused `preprocess_boxes` helper, which had no public export or caller. (#4181, #4321)--* `kornia_rs>=0.1.14` is required; the floor used to be 0.1.9. kornia_rs 0.1.11 relocated its image I/O- and 0.1.12/0.1.13 lack the libjpeg-turbo reader, so no single call site works across 0.1.9-0.1.14;- rather than dispatch per version, kornia calls the current layout. `pip install -U kornia_rs` on an- environment that pins an older one. (#4326)-* `kornia.contrib.BoxMotTracker` is removed, together with the `kornia.contrib.boxmot_tracker` module.- It wrapped the [boxmot](https://github.com/mikel-brostrom/boxmot) tracker zoo around a kornia detector,- but called the boxmot 10.x API (`boxmot.DeepOCSORT(model_weights=..., device=..., fp16=...)`), and no- boxmot release that installs alongside the torch versions kornia supports (`torch>=2.5.1`) provides- it, so the class could not be instantiated on any supported stack (see- [#4320](https://github.com/kornia/kornia/issues/4320)). Track with boxmot directly, feeding it the- output of a kornia detector such as `RTDETRDetectorBuilder`. `kornia.core.external.boxmot` is gone- with it. (#4301)--* `SegmentationModelsBuilder.build()` no longer imports `segmentation_models_pytorch` (smp). It used- to take `model_name`, `encoder_name`, `encoder_weights`, `in_channels`, `classes`, `activation` and- `**kwargs`, import smp lazily, instantiate the smp architecture and look up the encoder's- preprocessing parameters itself. It now takes a constructed `nn.Module` and the encoder's- preprocessing-parameter dictionary (`build(model, preproc_params=None, name="segmentation_model")`),- where `preproc_params` is what `smp.encoders.get_preprocessing_params(encoder_name)` returns; build- the smp network and fetch its parameters yourself. Kornia no longer imports smp anywhere, and- `kornia.core.external.segmentation_models_pytorch` is gone. `SemanticSegmentation` gained the- `__init__(model, pre_processor, post_processor, name=None)` its siblings have, so the container the- builder returns can be instantiated (it was abstract before). The `input_range: [0, 255]`- preprocessing step is now `kornia.enhance.Rescale(255.0)`, a multiply by 255, instead of a- `Normalize` by a stored `1/255`: bfloat16 rounds that reciprocal to a ~254.0 multiplier (0.5 mapped- to 127.0 instead of 127.5), and float32 outputs of that step move by at most one ulp. (#4301)--* `kornia.core.external.transformers` was removed; it was a `LazyLoader` handle no kornia code used.- Previously `from kornia.core.external import transformers` gave a lazy proxy that imported- `transformers` on first attribute access; that name no longer exists, so import `transformers`- directly instead. (#4301)-* `KimiVLBuilder.from_pretrained_hf()` and `SigLip2Builder.from_pretrained_hf()` cache their- checkpoint where every other kornia checkpoint lives. `cache_dir=None` used to mean the HuggingFace- cache (`~/.cache/huggingface/hub/models--<owner>--<name>/snapshots/<sha>/model.safetensors`) and now- means torch's hub directory (`<torch hub dir>/checkpoints/<owner>--<name>--model.safetensors`); an- explicit `cache_dir` used to hold the same `models--<owner>--<name>/β¦` tree and now holds the flat- `<owner>--<name>--model.safetensors` file. Either way the first `from_pretrained_hf()` call after- upgrading re-downloads the checkpoint (854 MB for KimiVL, ~1.5 GB for SigLIP2) even for users who- already had it. (#4293)--* Non-maxima suppression applies one border rule at every window size. `NonMaximaSuppression2d` /- `nms2d` with a window larger than `(7, 7)`, and `NonMaximaSuppression3d` / `nms3d`, no longer report- maxima inside the `(k - 1) // 2` border strip. Previously the general path replicate-padded its input,- so a position whose window ran off an edge was judged against duplicated copies of the edge values,- which both fabricated plateaus that suppressed genuine maxima and hid genuine neighbours that should- have suppressed spurious ones; the `(3, 3)`, `(5, 5)` and `(7, 7)` paths meanwhile rejected the strip- outright, so the two disagreed about the same pixel. The explicit paths' rule is now the rule- everywhere. Every kornia detector already rejects that strip -- ALIKED by hand after calling `nms2d`,- DISK and XFeat by using `k = 5`, `MultiResolutionDetector` by zeroing 15 px before the call -- so no- detector output changes. (#4239, #4242)--* `nms2d(x, (1, 1))` and `nms3d(x, (1, 1, 1))` return `x` unchanged. A unit window has no neighbours,- so nothing can be suppressed; the old 2-D result was an artifact of the zeroed centre tap of the- convolution kernel summing to `0.0`, while the old 3-D path raised because of #4241. (#4242)--* Kornia's minimum supported PyTorch version rises to 2.5.1. Previously the declared floor was- 2.0.0; PR-time CI has only ever exercised 2.5.1 and newer, and this same change retires the- scheduled-CI legs that tested anything older.- Installing kornia now requires `torch>=2.5.1`; a `torch` install below that version no longer- satisfies the dependency, and `pip`/`uv` will refuse to resolve it. (#4197)--* Removed `kornia.to_tensorflow()`, `kornia.to_jax()` and `kornia.to_numpy()`, along with the- multi-framework-support advertising in the README and the docs landing page. These functions used- to lazily transpile the library to TensorFlow, JAX or NumPy through the third-party `ivy` package- (an optional `dev`/`docs` dependency, now also removed). Testing in September 2026 found the- integration unreliable across all three targets β a checkout-path crash in Ivy's module walker, a- torch/triton segfault when `transformers` is also installed, an undocumented `flax` requirement for- JAX, and a `jaxlib`/`numpy` API-compatibility break β against Ivy's latest release (1.0.0.5, June- 2025), with the upstream project showing little ongoing maintenance. Reaching for any of the three- functions, at the top level or under `kornia.transpiler`, now raises an `AttributeError` that says- what was removed and links the page below, rather than a bare "has no attribute". See- `get-started/multi-framework-support` for what was tested and why. (#4196)--* `extract_patches_from_pyramid` now samples ordinary-sized inputs once from a packed pyramid atlas instead of- sampling every LAF at every pyramid level. A statically selected levelwise fallback keeps atlases larger than- 128 MiB from becoming a memory hazard. LAFs whose nominal level is coarser than the last usable pyramid level now- sample that actual coarsest level; they previously returned an all-zero patch. For `float16` and `bfloat16` inputs- the whole pyramid -- padding, `pyrdown`, coordinate arithmetic and sampling -- runs in `float32` and the patches- are cast back, on every device: this avoids the normalized-coordinate precision loss caused by the wider atlas,- keeps the extraction off `replication_pad2d`/`grid_sampler_2d` kernels that old torch builds lack for half dtypes- on the CPU (torch <= 2.5.1 would otherwise crash), and avoids recasting the full atlas on every sampling chunk.- `extract_patches_simple` computes its sampling grid in `float32` for reduced-precision inputs on every device for- the same reason -- its output matches the pyramid extractor's level-0 output again. Half-precision patches- therefore change on CUDA and MPS as well as the CPU, and floating-point results are not byte-identical to the- former levelwise implementation.- The universal `float32` sampling is a real cost where the native half kernels were fine: on CUDA, `float16`- `extract_patches_simple` is roughly 2x slower at high N, and peak CUDA memory rises at moderate N (the atlas plus- the one-time upcast copy) even though the high-N peaks drop.- Both extractors now reject an image/LAF batch-size mismatch at the boundary with a clear error: former releases- raised an internal `grid_sample` error for most batch mixes, except a smaller LAF batch, where both extractors- silently returned patches for only the first `min(B_img, B_laf)` images. A LAF on another device is moved once to- the image, while a different LAF dtype is promoted with the image dtype for grid arithmetic rather than rejected or- rounded down; this preserves mixed-precision autocast pipelines and subpixel LAF coordinates. Patches still return- with the image's dtype and device. Both extractors chunk their sampling along N, in the spirit of `batched_forward`, so- the folded `(B, N*PS, PS, 2)` grid and channel-scaled sampled chunk each stay within a fixed 64 MiB budget (remap- intermediates can still make the total peak a multiple of that). Batched high-N extraction now peaks below even the- pre-batching per-image loop (468 MiB- against 495 MiB on `main` for B=8,- N=4000, PS=32 on a 512x512 float32 image, where the unchunked atlas peaked at 1.24 GiB), eager throughput stays- within ~5% of the unchunked atlas, and float32/float64 patches are bitwise identical to it; a `torch.compile`d- call whose grid exceeds the budget splits into several `grid_sample` calls (~1.5x the unbounded atlas latency at- B=8, N=2000 on CPU inductor, still ~10x faster than the per-level loop it replaces). Both extractors return an- empty `(B, N, CH, PS, PS)` tensor for `B == 0` or `N == 0` instead of raising from inside `affine_grid` --- `extract_patches_from_pyramid` with `B == 0` returned the empty result before the batched rewrite below- regressed it; every other empty combination raised on all prior releases. `extract_patches_from_pyramid` now- also accepts a LAF on a different device than the image, as `extract_patches_simple` always has, and returns- patches on the image's device; both extractors move the LAF to the image's device up front, so a cross-device- call now samples on the image's device and matches the same-device result (`extract_patches_simple` previously- built the full sampling grid on the LAF's device).--* `AUTUMN` is dropped from `kornia.color.__all__` (#4143). The class was deprecated in 0.7.2 in favour of- `ColorMap(base='autumn')` and removed by #3432, which left the `__all__` entry behind. Since that removal- `from kornia.color import AUTUMN` has raised `AttributeError` and `from kornia.color import *` has failed on- it, so nothing that works today stops working β the entry named a binding that no longer existed. Callers- still reaching for the class should use `ColorMap(base='autumn')`.--* The shape guards of `normalize_homography` and `denormalize_homography` now reject everything but a- `(3, 3)`/`(B, 3, 3)` matrix, and `normalize_homography3d`'s everything but a `(4, 4)`/`(B, 4, 4)` one (#3999).- A rank-4 input used to pass the guard and come back with its rank unchanged β- `normalize_homography(eye(3).expand(2, 4, 3, 3), (4, 5), (8, 9))` returned a `(2, 4, 3, 3)` matrix and now raises- `ValueError`. A wrong-sized input, such as a `(B, 4, 4)` to the 2-D functions, used to pass the guard and fail- later inside `matmul`; it now raises at the guard, and `normalize_homography3d`'s message names `Bx4x4` instead of- `Bx3x3`. Unbatched `(3, 3)`/`(4, 4)` matrices are still accepted and still promoted to a leading batch of 1.-- One side effect reaches tracing callers: the rewritten guard evaluates its shape comparison unconditionally, where- the old `or`-form short-circuited past it for a rank-3 input, so `torch.jit.trace` of any of the three functions- now emits a `TracerWarning` about converting a tensor to a Python boolean that it did not emit before. The guard- is a static check and the traced graph is unchanged β the warning is noise, not a correctness signal.--* `MultiResolutionDetector` and `KeyNetDetector` change their output: padded slots now read as a zero response and- a zero LAF instead of `torch.finfo(dtype).min / 2` and an arbitrary border coordinate; the previously inert `mask`- argument now suppresses detections, and must be `(1 or B, 1, H, W)` at the image size -- a `(B, H, W)` mask- passed directly to either detector, which was accepted only because it went unread, is rejected; half-precision- input yields half-precision LAFs; the returned shape is always `num_features`; a multi-channel response is rejected instead of- producing invalid or duplicate LAFs; a negative `score_threshold` is rejected with `ValueError`; and `detect`- enforces its documented `(1, C, H, W)` input. The `mask` of both detectors is now "where a detection may be": a- boolean or integer mask is binary (a 0/255 mask no longer scales the responses by 255), a floating-point mask- weights the scores, it is resampled conservatively so a thin zero region survives the coarse levels, and it is- applied to the non-maxima-suppression output, so its edge cannot manufacture maxima (#4102). A mask whose dtype- differs from the image no longer promotes the response dtype, and a mask that is not `(1 or B, 1, H, W)` for the- image is rejected instead of stretched or broadcast onto the wrong axis -- that includes an image-shaped- `(1, C, H, W)` mask and a coarse `(N, H/8, W/8)` one, which `LocalFeatureMatcher` used to accept and silently- ignore (the old docstring said "same shape as the input image") and now forwards to the detector's check.- `ScaleSpaceDetector` additionally stops returning its own top-K sentinel as a detection for a batch, no longer- returns a frame for a candidate its border check rejected, and re-checks a sub-pixel-refined centre against the- mask; a short result is sorted in both detectors. `detect_features_on_single_level`'s new `mask` parameter is- keyword-only, and it now requires the response map to have the level's spatial size: a valid-convolution- response net that returned a smaller map had every keypoint decoded one pixel off its peak, since a response- index is read as a level pixel with no offset, and is rejected with a message rather than silently misplaced.- See the entry under **Bug fixes** (#4089, #4090, #4091) for the details and the- migration.--* `MKDDescriptor` runs in `float16` and `bfloat16`. Its gradient-embedding and spatial-encoding stages were held in- a plain `dict`, so `.to(device, dtype)` never reached their buffers and a half-precision input failed at the- whitening matmul with `expected m1 and m2 to have the same dtype`. They are now an `nn.ModuleDict`; float32 and- float64 outputs are byte-identical, and `state_dict()` gains the stages' buffer keys (`feats.<parametrization>.*`).- A state dict saved by an earlier release still loads with `strict=True`: those buffers are derived from the- constructor arguments, and when a state dict has no `feats.*` key at all they are filled in from the module being- loaded into (one that has some and lost one is reported by `strict=True`, as for any other missing key). The- reverse is not covered: a state dict saved by this release carries the `feats.*` keys and fails `strict=True` on- an earlier kornia, which does not know them; load it with `strict=False` there.--* `DescriptorMatcherWithSteerer(normalize=True)`, `DiscreteSteerer.steer_descriptions(normalize=True)` and the- `MKD` descriptors, like `SIFTDescriptor` and `HardNet`, L2-normalise a float16 input in float32 and cast back,- so an all-zero float16 descriptor normalises to zero instead of NaN (the 1e-12 guard underflows in float16) and a- descriptor whose norm sits below the smallest float16 normal still normalises to one rather than being clamped.- `PatchDominantGradientOrientation`, and with it `LAFOrienter`, take the gradient magnitude and orientation of a- float16 patch through the same float32 step `SIFTDescriptor` uses, so a flat patch yields a finite angle instead- of a NaN LAF -- which reached a *filled* detection slot in a float16 `SIFTFeature` pipeline and poisoned that- descriptor row. `SIFTDescriptor(rootsift=True)` and `DenseSIFTDescriptor(rootsift=True)`- compute the RootSIFT square root in float32 for a float16 input: the float16-representable guard would have- read every empty bin as `sqrt(6.1e-5)` and biased the descriptor norm to ~1.004. Float32 and float64 outputs are- unchanged.--* `LocalFeatureMatcher` no longer matches the zero-LAF slots with which a fixed-shape detector pads an under-filled- result, and now forwards its documented `mask0`/`mask1` inputs to feature extraction. `nn` and `mnn` callers can- therefore receive fewer correspondences: identical descriptors sampled at padded origin frames are no longer- reported as matches. Three-dimensional `(B, H, W)` masks keep working and are promoted to the detectors'- `(B, 1, H, W)` form; four-dimensional masks are forwarded unchanged. Because the masks now reach the detector,- they are subject to its check: a mask that is not at the image's spatial size, which used to be ignored, is- rejected. A floating-point mask changes meaning in `ScaleSpaceDetector`-based pipelines too, see below.--* `ellipse_to_laf` no longer raises on a degenerate ellipse. One whose `a` or `c` is `0` after rounding to the input- dtype makes the matrix being inverted singular; the batched `torch.inverse` it now replaces (see below) failed the- whole call with `linalg.LinAlgError`, and the closed form returns non-finite values in that LAF instead, leaving- the other rows of the batch usable. Callers that relied on the exception to reject bad input -- reading- Oxford-format `.ellipse` files, say -- should test the result with `kornia.feature.laf_is_valid`, since an invalid- LAF otherwise propagates silently through `get_laf_scale` and into matching. Detecting the degenerate rows up front- would cost a device synchronisation and the `fullgraph=True` capture, so it is left to the caller. The in-repo- affine estimators handle invalid candidates before nonlinear LAF operations. `PatchAffineShapeEstimator` computes- half-precision gradients, Gaussian weights, moments, and normalization in `float32`, preserving valid anisotropic- shapes that would otherwise underflow; `LAFAffineShapeEstimator` sanitizes non-positive-definite ellipse- coefficients before conversion; and both it and `LAFAffNetShapeEstimator` use a finite fallback with finite- backward. The fallback is the input LAF when `preserve_orientation=True` and its upright form otherwise; a finite- zero-scale input keeps its center and zero affine block.--* `create_meshgrid` and `create_meshgrid3d` return different normalized coordinates at `float16`- and `bfloat16`. They used to evaluate `(xs / (size - 1) - 0.5) * 2` as three half-precision ops- in eager, rounding after each, and to materialize the half ramp before the graph-capture branch- widened it; `torch.compile` instead computed the chain in `float32` and rounded once, and folded- the narrow-then-widen round trip away so that above `2 ** p` the two paths divided different- numerators. A half-precision grid therefore changed the moment a model was wrapped in- `torch.compile` -- by up to 0.0117 in the `[-1, 1]` range at `bfloat16` width 300 and 0.0156 at- width 6000. A normalized half-precision grid is now built and normalized in `float32` and- narrowed once, so eager, traced and compiled grids agree; the eager values move onto the- correctly rounded side, which is the numeric change. `float32`, `float64` and integer grids and- the pixel ramp are bit-for-bit unchanged, since none of them widen. On CUDA at `float16` up to- one ulp of the coordinate dtype can still differ, because ATen's and triton's `float32` division- are not bit-identical; `bfloat16` absorbs it and the CPU kernels agree exactly. The Linux CPU- half-precision baselines move with it. `HomographyWarper` builds its precomputed grid in `float32`- and its on-the-fly grid in the input dtype, and the two now agree, which fixes- `test_homography_warper` at both dtypes and `test_translation[shape1]` at `float16`. At `bfloat16`- `test_translation[shape0]` and `[shape2]` join the `shape1` and `shape3` entries already recorded:- that test's `atol=1e-4` is out of reach for all four of its shapes there, and the two that passed- did so only because the old grid's larger error round-tripped through `grid_sample`'s `bfloat16`- unnormalize as an exact pixel index. Refs #4030. (#4231)--### Bug fixes--* `RandomCutMixV2` and `CutmixGenerator` document `cut_size` as what it is: the `[min, max]` clamp on the- Beta-sampled mixing coefficient `lambda`, where the cut side is `floor(sqrt(1 - lambda) * side)`, so a larger- `cut_size` gives a smaller cut. It was described as the "minimum and maximum cut ratio". A minimum of `1.0` is- now rejected with a `ValueError`: it forced `lambda = 1`, built an inverted zero-size box and silently made the- augmentation an identity. (#4439, #4491)--* Made uncompiled `RandomGaussianIllumination` instances serializable with `pickle` and `torch.save`,- preserving parameter replay and the `compile()` execution path after restoring the module. (#4457)-* The `Args` blocks of `ColorJitter`, `RandomBrightness` and `RandomGaussianBlur` no longer document a- `silence_instantiation_warning` argument that none of them accepts, and `ColorJitter` now documents its- `order` argument: a fixed (sub)set of brightness/contrast/saturation/hue indices that makes the transform- `torch.compile` fullgraph-safe, with the drawn `_params["order"]` entry ignored when it is set.- (#4437, #4490)--* `kornia.enhance.equalize`, `equalize3d`, `RandomEqualize` and `RandomEqualize3D` raise a `RuntimeError` naming- the `[0, 1]` input range for values the 256-bin lookup cannot index, instead of a raw- `index 259 is out of bounds for dimension 1 with size 256` from the gather. The check uses- `torch._assert_async`, so it adds no device sync and `torch.compile` fullgraph still works, and inputs that- equalized before (including values a hair above 1) are unchanged. The docstrings now state the range, the- 256-bin histogram, and that a 3D volume of at most 255 voxels per channel comes back unchanged.- (#4431, #4432, #4489)--* `kornia.contrib.diamond_square` generates fractals with a spatial side below 3 px. A 1 px side raised- `ValueError: math domain error` and a 2 px side a `TypeError` from a float in the `torch.rand` size, so- `RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow` failed on such images. A small- side is now drawn on the 3 px grid and sliced; outputs for sides of 3 px and more are bit-identical.- (#4472, #4488)--* `RandomBoxBlur`'s `normalized` argument is documented as what it does. It was described as "if True, L1 norm- of the kernel is set to 1", but it was forwarded positionally into `kornia.filters.box_blur`'s `separable`- parameter: it chooses between the separable and the single 2D pass, and the kernel is L1-normalized either- way, so `normalized=False` returns window means, not sums. The call now passes `border_type` and- `separable` by keyword; outputs are unchanged. (#4433, #4486)--* `So3.exp`, `So3.log`, `Se3.exp`, `Se3.log` and `Se2.exp` return finite gradients at the identity,- and `So3.log` also at a half turn, instead of `nan` on every dtype. The forward values are unchanged;- `torch.where` was differentiating the singular branch it does not select. (#4405)-* `ycbcr_to_rgb` now uses the exact inverse of the `rgb_to_ycbcr` coefficients, so an- `rgb -> ycbcr -> rgb` round trip is lossless to floating-point precision instead of drifting- by ~2.7e-4. The forward transform is unchanged. (#4378)-* `bbox_to_mask3d` now preserves the input dtype in the returned mask, matching `bbox_to_mask`- and the `Boxes3D.to_mask` contract: the earlier implementation downcast every result to- `float32`, so a `float64` or half-precision box produced a mask that silently lost precision.- The mask keeps the input box's dtype end to end. (#4376)-* Fixed `RandomPlasmaBrightness`, `RandomPlasmaContrast`, and `RandomPlasmaShadow` to replay deterministically from stored `params=`. (#4462)-* `ManyToManyAugmentationDispather` now rejects mismatched numbers of input bundles and- augmentations before applying any transformation, instead of silently dropping surplus inputs- or skipping augmentations. (#4461)-* `PatchSequential` now augments every patch of every image and runs the complete selected sequence.- The padding, reconstruction and parameter-generation behaviour changes are listed under- *Breaking changes*. Refs #4421. (#4460)-* `RandomMosaic` now preserves `(H, W)` for non-square inputs when `output_size=None`; it previously- returned `(W, H)`. `start_ratio_range` now scales x by width and y by height; it previously scaled- x by height and y by width. (#4459)--* `RandomThinPlateSpline(scale=0.0)` now generates zero control-point displacement instead of- raising an error when constructing a degenerate uniform distribution. (#4463)-* `unproject_meshgrid` now requires camera intrinsics of shape `(B, 3, 3)`, rejecting extra- camera axes before they can broadcast across pixel columns and reporting the caller's original shape. (#4383)-* Correct non-zero sensor tilt in `tilt_projection` and `distort_points` to match OpenCV,- restoring forward/inverse round trips and correcting `undistort_image` sampling. (#4384)--* `reproject_disparity_to_3D` (the `StereoCamera` method and the module-level function, which share- one body) no longer transposes the two pixel indices. The pixel meshgrid was unbound as- `v, u = torch.unbind(uv, dim=-1)`, but `create_meshgrid(normalized_coordinates=False)` returns- `(x, y)`, so the column fed `v` and the row fed `u`: `X` was computed from the row and `Y` from- the column. Every returned point was the value belonging to its transposed pixel -- kornia's- answer at `(row, col)` was what `cv2.reprojectImageTo3D` puts at `(col, row)`, the OpenCV- semantics this function was added to provide (#2042). A square rig with `fx == fy` and- `cx == cy` agrees only on the diagonal, so the error was silent rather than absent. Output- changes at every pixel with `row != col`, square inputs included. The real-data regression- fixture stored ten points as ten rows of one column while its own comment and its ground truth- describe one row of ten columns,- which is why it passed against the swapped code; it is now laid out as the comment says, and- the fixed code reproduces the unchanged ground-truth values. #4317's two wart pins for this defect- are retired and its strict-xfail convention test is now an ordinary passing regression. (#4269, #4366)--* `RandomRain` with `same_on_batch=True` now samples the same number of rain drops for all samples in the batch. (#4453)-* `RandomRain` now rejects drop heights equal to the image height and absolute drop widths equal to the image- width with the documented validation error, instead of allowing boundary-sized drops to reach an internal- `IndexError`. (#4451)-* `depth_to_normals` now raises `ShapeError` when `H < 2` or `W < 2`, since surface normals need two- tangent directions. Previously, singleton axes could yield zero or non-finite normals, and empty- spatial dimensions failed inside padding. Inputs with both dimensions at least 2 are unchanged. (#4458)-* `Boxes.pad`, `Boxes.unpad` and `Boxes.clamp` accept the unbatched `(N, 4, 2)` container the class- documents and constructs. All three assumed the batched `(B, N, 4, 2)` indexing: `pad` and `unpad`- broadcast the padding as `(B, 1, 1)`, which does not fit the unbatched `(N, 4)` coordinate view and- raised `RuntimeError: output with shape [1, 4] doesn't match the broadcast shape [1, 1, 4]`, and `clamp`- materialized its bounds with `repeat(1, _data.size(1), 4)` and raised `IndexError: too many indices for- tensor of dimension 2`. Adding a leading singleton batch axis to the same boxes made all three work.- They now broadcast against whichever rank the container holds and match the singleton-batch result;- an unbatched container carries one image, so a per-image tensor with more than one row is rejected.- Batched results are byte-identical, including for a non-finite bound: `clamp` stays comparison-based, so- a `NaN` bound leaves the coordinate alone rather than propagating into it (closes #4244). (#4372)-* `RandAugment`'s `m` guard is exclusive at both ends, but its docstring and its error message- both named the closed interval `[0, 30]`, so a user who asked for the maximum strength the- message advertised got an exception saying `30` was in range. Both now read `(0, 30)`; the- accepted values are unchanged. `n` was validated nowhere: `n=0` constructed a `RandAugment`- that applied nothing, and `n` above the policy length was silently clamped, because the- sampler draws without replacement. It is now checked against the policy. `AutoAugment`'s- magnitude bin indexes two adjacent points of an 11-point scale, so `9` is the last usable- bin; a larger one raised a raw `IndexError` naming an internal tensor, and a negative one- wrapped silently onto a reversed range. Out-of-range bins now name the operation and the- valid range. Operations that ignore the magnitude entirely keep accepting any bin. (#4447)--* `PinholeCamera.project` now reports rank-1 inputs with the same explicit `ValueError` used by the point-conversion- helpers instead of an internal `IndexError`. Refs #4266. (#4450)-* `pixel2cam` now validates the full `Bx4x4` shape of `intrinsics_inv`, rejecting invalid matrix sizes- before they cause unrelated transformation errors or return the wrong number of coordinate components. (#4381)-* `Boxes.to_mask` leaves list-padding channels empty, including after coordinate transforms,- instead of treating padding entries as real boxes. (#4390)-* Fixed fixture teardown between files when running half-precision tests with- `--isolate-half-precision`, including reporting parent fixture finalizer errors. (#4388)-* Corrected the matrix-shape checks shared by `PinholeCamera` and `PinholeCamerasList`, the- `pixel2cam` coordinate-shape check, and the `cam2pixel` coordinate/projection checks. Invalid- inputs now raise the intended `ValueError` instead of being accepted or failing later in tensor- operations. The rank-4 matrices used by `PinholeCamerasList` remain supported. (#4387)-* Fixed `dx_distort_points_kannala_brandt` to return the true Jacobian of `distort_points_kannala_brandt`, including a finite affine Jacobian at the origin. (#4277, #4368)-* `Boxes3D.from_tensor(..., validate_boxes=True)` rejects non-finite coordinates, and `validate_bbox3d`- returns `False` for them instead of raising an `AssertionError` that names the wrong defect. This is the- 3D counterpart of #4243. An `inf` passed the positive-extent checks outright, and a `NaN` passed them- because every comparison against `NaN` is `False`, so the box was constructed with non-finite vertices;- in `validate_bbox3d` the `NaN` instead reached the `allclose` extent comparisons and raised- "Boxes must have be cube, while get different widths". `validate_bbox3d`'s four internal callers use it- for its raise and discard the result, so they now convert the `False` themselves and keep raising the same- `AssertionError` they did before, with a message that now names the non-finite coordinates instead of- reporting mismatched cube extents. The `validate_boxes=False` opt-out and the export gate are unchanged- (closes #4258). (#4343)-* `axis_angle_to_rotation_matrix` accepts the `(*, 3)` shape its own guard message promises, instead of- only `(N, 3)`. The body did `wxyz.unbind(dim=1)` and `.view(-1, 3, 3)`, so an unbatched `(3,)` raised- `IndexError: Dimension out of range` and any extra batch dimension raised `ValueError` out of the unbind,- three frames below kornia's own shape guard. Every sibling conversion in the module already accepted- `(*, 3)`, so `axis_angle_to_rotation_matrix(rotation_matrix_to_axis_angle(R))` composed for an `(N, 3, 3)`- rotation matrix and for nothing else, including for the shape `rotation_matrix_to_axis_angle`'s own- doctest returns. This is additive: `(N, 3)` output and gradients are byte-identical, and only shapes that- used to raise now return (closes #3955). (#4342)-* Make calibration `distort_points` and `undistort_points` tilt checks compatible with- `torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)-* Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)-* `PinholeCamera`, `StereoCamera`, and `warp_frame_depth` now support empty batches. (#4386)-* `elastic_transform2d` now builds its identity sampling grid with the requested `align_corners`- convention, so a zero displacement field preserves the input image. (closes #4235). (#4382)--* `rad2deg` and `deg2rad` now handle integer tensor inputs correctly and preserve- float64 precision. `angle_to_rotation_matrix` inherits the corrected conversion,- while the implementation preserves ONNX export compatibility. (#4358)-* `fft_conv` now accepts CPU float16 and bfloat16 inputs by computing the FFTs- in float32 and returning the input dtype. (#4394)-* Corrected stereo disparity validation errors to describe the required channels-last- `(B, H, W, 1)` layout and report the received shape. (#4380)-* `CameraModelBase.__init__` now validates `params` against the shape it documents, instead of storing- whatever it is given. The typed constructors (`PinholeModel`, `BrownConradyModel`, `KannalaBrandtK3`,- `Orthographic`) each apply the same two comparisons, so only the direct-construction path -- which is- public, and is what the class docstring's own example uses -- was unguarded. A short vector used to- construct and then fail with an `IndexError` from inside `AffineTransform.distort`, naming neither- `params` nor the camera; a rank-3 `(B, 1, N)` tensor used to construct, project, and silently return a- `(1, 1, 2)` result. Both now raise `ValueError` from the constructor. (#4316, #4369)-* `undistort_points_kannala_brandt` no longer collapses representable `float16` points next to the principal point- to the origin, and the exact principal-point path now has finite autograd gradients. The zero-radius decision is- made from the unsquared normalized coordinates, and the `float16` radius uses `float32` intermediates so its- squared value does not underflow; nonzero radial rescaling remains epsilon-free. (#4308, #4370)-* `solve_quartic` now validates Ferrari resolvent candidates with a dtype-aware scaled residual,- falls back to the smallest scaled residual when no candidate passes, and keeps the Ferrari `E`- factorization away from an ill-conditioned `R` division. Cancellation-level `R^2` is snapped to- zero relative to the coefficient scale, and all Ferrari compute dtypes choose between the linear-- and constant-term `E` forms by normalized coefficient error; float32 also refines the selected- resolvent root once. The gradient-safe zero-radicand path remains intact, preventing half-precision- non-finite or dropped roots and full-precision non-roots while preserving the public contract. (#4357)--* `StereoCamera` now rejects projection matrices whose last two dimensions are not `(3, 4)` with a- `StereoException` naming the invalid camera. Previously, the shape guards never fired, so malformed- matrices could be accepted or fail later with an unrelated tensor error. (#4385)--* `warp_affine`, `warp_perspective` and `remap` crashed on MPS for an empty destination -- a `dsize` with a- zero dimension, or zero-sized `remap` maps -- with an internal- `[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder tensor is empty!` from PyTorch. The MPS backend- rejects *any* zero-element `grid_sample` operand before torch 2.14, including a zero-element grid sampled- against a non-empty source, which is what the empty-destination path built. That path now samples a connected- 1x1 stand-in and expands the result to the requested empty shape, so `grid_sample` never receives a- zero-element operand on any backend and an empty warp costs the same whatever the non-zero side of `dsize` is.- The empty path also resolves its output batch the way each operation's non-empty path does, so a singleton- transform or map batch broadcasts identically and a mismatched batch is rejected rather than silently- returning the wrong cardinality. Outputs, autograd links and the documented empty-source policy are unchanged- on CPU and CUDA. (#4032, #4354)-* `VideoBoxes.get_boxes_shape()` and `VideoBoxes.to_mask()` no longer raise `TypeError`. Both are- inherited from `Boxes` and pass `as_padded_sequence=True` to `to_tensor`, but the `VideoBoxes`- override declared only `mode`, so every call on a `VideoBoxes` failed -- including the containers- `AugmentationSequential` builds for video box inputs. The override now accepts and forwards the- keyword; it only changes a list-backed container, and a `VideoBoxes` built from a- `(B, T, N, 4, 2)` tensor is not one, so no working call changes its result. Indexing a- `VideoBoxes` still drops `temporal_channel_size`, which is the remaining half of #4249.- (#4176, #4365)--* Fixed `unproject_points_z1` depth shape handling for singleton and multi-axis batches,- accepting both trailing-singleton and flat depth tensors. (#4355)-* `solve_quartic` returns finite gradients for a pure biquadratic such as `x^4 - 16`. Its two- `torch.clamp(..., min=0.0).sqrt()` sites do not guard the gradient they look like they guard:- `d(sqrt)/dx` is unbounded at 0, and on torch below 2.14 `clamp` passes the incoming gradient- through at the bound rather than zeroing it, so on the older half of kornia's supported torch- range the backward returned `inf` and then `nan` (#4229). Both sites now substitute a safe- radicand under the `sqrt`, as `solve_quadratic` in the same module already did. Forward values- are unchanged. (#4339)--* `depth_from_plane_equation` returns a finite depth for a ray exactly parallel to the plane. The- near-singular guard was `eps * torch.sign(denom)`, and `torch.sign` is zero at zero, so at the exact- singularity the epsilon was multiplied away and the division still ran against zero, returning `inf`.- A grazing ray is not an exotic input: it is every pixel on the horizon of a ground plane. The guard- now picks its sign with a comparison, which has no such hole and keeps the sign the small non-zero- denominators already got. `torch.copysign` reads the same but is not exportable, and this function- is in the documented ONNX export surface, so the comparison form is pinned in- `tests/onnx/test_export_coverage.py`. The finite-depth promise is bounded by the dtype: the default- `eps=1e-8` is below float16 resolution, so half-precision callers must pass a representable `eps`.- (#4280, #4348)--* `depth_from_disparity` accepts Python integers and scalar tensors for the baseline and focal length. (#4392)--* `iterative_quad_interp3d`'s `max_candidates` cap is now a per-image budget rather than one shared- across the batch. The `topk` ranked the flattened `(B*C)` candidate list, so an image's refined- keypoints depended on which other images shared its batch: a quiet image next to a high-contrast- one got none. This also reaches `IterativeQuadInterp3d` and `AdaptiveQuadInterp3d` in `patch` mode.- The docstring already read as a per-image budget. A negative `max_candidates` now raises- `ValueError`; it previously raised a `topk` `RuntimeError`, and under the per-image ranking it- would otherwise have silently disabled refinement instead. (#4256, #4350)--* `infer_bbox_shape3d` and `bbox_to_mask3d` reject rank-4 `(B, N, 8, 3)` input with a `ShapeError`,- the way `infer_bbox_shape` and `bbox_to_mask` have since #4218. `validate_bbox3d` accepts the rank-4- form and reshapes internally, but both callers index dim 1 as the vertex axis, so the box axis was- read as the vertices: an out-of-bounds error with one box, and three `(1, 3)` tensors -- one value- per coordinate rather than per box -- with eight. (#4248, #4351)-* `solve_cubic` and `solve_quartic` return finite gradients for a row whose neighbours in the- same batch take a different branch. The `D > 0` branch selected its rows with `abs(R) > 1e-16`- alone, so it evaluated `sqrt(D)` on `D < 0` rows too. Those rows are never read back, but the- resulting `-Q / nan` stays in the graph and its backward returns `nan`, which reaches every- coefficient: a three-real-root cubic differentiated correctly on its own and gave `nan` as soon- as a one-real-root cubic shared the batch, and `solve_quartic` inherited it through its- resolvent cubic. The forward values are unchanged. (#4334, #4338)--* `Normalize`, `Denormalize` and `Rescale` register their constants (`mean`, `std`, `factor`) as- non-persistent buffers instead of plain attributes, so `.to(device)` moves them with the module.- Previously they stayed on the CPU: eager tolerates the mix, but `torch.export` traces with fake- tensors and refused it, so exporting a preprocessing pipeline from an accelerator failed while- the same pipeline exported fine from the CPU. `Denormalize` now coerces a scalar `mean`/`std` to- a 1-D tensor, as `Normalize` already did, which changes its `__repr__` to match `Normalize`'s and- lets a scalar `Denormalize` reach the ONNX export branch instead of raising `IndexError` there.- The buffers are non-persistent, so `state_dict()` is unchanged and existing checkpoints still- load. (#4323, #4330)--* `download_file_from_url` and `download_hf_file` take an optional `validate=` callable, and- `kornia.core.check_safetensors` is the one the KimiVL and SigLIP2 builders pass. A transfer cut- short after a 2xx status leaves a truncated file in the cache, which was then returned as a cache- hit on every later call -- `from_pretrained_hf()` failed until the user deleted it by hand.- `validate` gives a download-only call the quarantine `load_state_dict_from_url` gets from its load- step: a rejected entry is moved aside, the next source is tried, and the discarded source is- re-fetched once. Without `validate` the behaviour is unchanged. (#4309, #4332)--* `PinholeCamera.scale` no longer shares its `extrinsics` tensor with the source camera. The- intrinsics were cloned, the extrinsics were handed to the new object by reference, and the- constructor stores what it is given, so `scaled.tx = 7` moved the camera `scale()` was called on.- The returned camera's numbers are unchanged. (#4264, #4349)--* A fresh transfer that `validate` rejects is now removed even when no other source could have used- the emptied path -- which is every `download_hf_file` caller, since it passes one URL. Those bytes- arrived during the call and were refused, so unlike the ambiguous load failures- `load_state_dict_from_url` weighs, keeping them would end the call having added a poisoned entry to- a cache that had none. An offline re-fetch also reports the validator's rejection rather than the- network error stacked on top of it, so the message names the file rather than an entry that is- intact and, by then, restored. (#4367)--* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering- time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never- moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so- `RenderingDeFMO().half()` left `times` at `float32` and the first forward raised `RuntimeError: Input- type (torch.FloatTensor) and weight type (torch.HalfTensor) should be the same`. `times` is now a- non-persistent buffer (it is fully determined by `tsr_steps`, not learned, so `state_dict()` keys and- existing checkpoints are unaffected), and `forward` casts into a local variable rather than depending- on the caller having matched dtype. Same bug shape as #4069/#4079 in a different class; the normal- `float32` path is byte-identical to before. (#4319)-* `jpeg_codec_differentiable` no longer returns an all-`NaN` image at `jpeg_quality=0`, a value inside the- `[0, 100]` range it documents and validates. `_jpeg_quality_to_scale` divides `5000` by the quality on the- `< 50` branch, which is `inf` at `0`, and the polynomial floor of `inf` is `NaN`, poisoning the image and- its gradient. A quality of exactly `0` is now given the scale of quality `1`, which is the table libjpeg- gives quality `0`. The guard is that one point: a fractional quality in `(0, 1)` was already finite, keeps- its own larger scale, and is untouched, so this endpoint is not the limit of the formula from above.- Output and gradients for every quality `> 0` are byte-identical. The tests drew- the quality with `torch.randint(low=0, high=100)` unseeded at sixteen sites, so roughly one run in twenty of- `tests/enhance/test_jpeg.py` went red on any job; the draws now start at `1` and the boundary has pinned- cases of its own. (#4205)-* `ModelBase.save` and `_save_outputs` write the visualizations they are given instead of raising.- They handed `visualize`'s float output to `write_image` under a hard-coded `.png` name, but PNG is- `uint8`/`uint16` only, so every container's `save` (`SemanticSegmentation`, `ObjectDetector`,- `EdgeDetector`, `DepthEstimation`) raised on its first write and left an empty directory behind.- Float images are now converted to `uint8`, clamped to `[0, 1]` first so an out-of-range- visualization does not wrap. A batched `(B, 3, H, W)` output -- the shape the containers document- -- is written as one file per item rather than passed whole to `write_image`, which takes- `(3, H, W)` and rejected the rank with a message naming neither. (#4322)--* `RandomChannelDropout.fill_value` and `RandomGaussianBlurGenerator.sigma` (when passed as a- Tensor) are registered as non-persistent buffers instead of plain attributes, so they move with- `Module.to()`/`.half()`/`.cuda()` and appear in `named_buffers()` like the rest of the module's- state; `state_dict()` keys are unchanged. Neither crashed before this change (both re-derived- device and dtype inline on every call), so this is a hygiene fix, not a bug fix for a crash.- One user-visible effect: after `.half()`/`.bfloat16()` the fill value is now held in that dtype,- so an input already in the module's dtype is unaffected, while a `float32` input fed to a- half-converted `RandomChannelDropout(fill_value=0.3)` is filled with `0.300048828125` (float16)- or `0.30078125` (bfloat16) rather than `0.3` -- the same buffer semantics as `Normalize`.- (#4337)--* `Z1Projection.unproject` now materialises a python `int`/`float` `depth` on the device and- in the dtype of `points`; it used to build a CPU float32 tensor, which raised `RuntimeError`- on every accelerator and widened float16/bfloat16 results to float32. (#4340)-* `_cdist` replaces `dm.clamp(min=0.0).sqrt()` with a masked argument substitution, avoiding `NaN` gradients for- exact zero-distance pairs on PyTorch 2.5.1 and 2.9.1 where `clamp`'s boundary gradient passed through to `sqrt(0)`.- PyTorch 2.14.0 was already finite, and forward behavior and computed distances are unchanged. (#4233)--* `bbox_to_mask` built its pixel-position grid in the box dtype. With `float16` boxes (and- `bfloat16` boxes) on images wider or taller than 2048 px (256 px for `bfloat16`) consecutive- pixel positions collapsed, so rows and columns near the collapse were mismasked; the grid is- now built in `float32` and `float16`/`bfloat16` results are byte-identical to `float32`/`float64`.- `RandomErasing` and `RandomCutMixV2` build their masks through it. (#4336)--* `kornia.contrib.super_resolution` builders construct again. `SuperResolution` never implemented- `ModelBase`'s abstract `from_config` and defined no `__init__`, so `SmallSRBuilder.build()` and- `RRDBNetBuilder.build()` both raised `TypeError` at construction β the whole public- super-resolution entry point had been unreachable since the models refactor made `from_config`- abstract. It now has a `SuperResolutionConfig` and a `from_config` that dispatches to either- builder family, and both builders are covered by tests. Fixes #4291. (#4335)--* `tilt_projection` preserves its documented leading batch dimensions, so `distort_points`,- `undistort_points`, and `undistort_image` no longer fail on multi-axis batches when tilt distortion- is applied. (#4345)--* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`- resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into- `kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raised- `AttributeError` for every JPEG and every PNG that is not plain RGB, and `write_image` raised for- TIFF, 16-bit and float32 output (8-bit JPEG and PNG writes still worked); the lock's 0.1.10 kept CI- green. kornia now calls `kornia_rs.io` and requires kornia_rs 0.1.14 (see *Breaking changes*). That- decoder also reads 16-bit PNG/TIFF and float TIFF, which 0.1.10 rejected: `ImageLoadType.UNCHANGED`- returns them as `uint16`/`float32`, and the 8-bit load types raise a `NotImplementedError` that says- so instead of mislabelling the tensor. The nightly PyPI job now imports the installed wheel from- outside the checkout (it used to import the source tree) and round-trips an image instead of only- importing. (#4326)--* `distance_transform` no longer returns NaN gradients when the cascade's convolution is exactly zero, including- sparse masks and all-zero inputs; the existing forward output is unchanged. (#4232)--* `SemanticSegmentation.visualize` works for CUDA, MPS and half-precision models. It indexed the- CPU-drawn colormap with the mask's `argmax`, which raises for CUDA and MPS masks, and recognised a- softmax head with `torch.allclose(sum, 1)` at float32-sized default tolerances, which a float16 or- bfloat16 sum of probabilities never meets; the tolerance now scales with the number of classes and the- dtype's epsilon, and the colormap follows the mask's device and dtype, so the visualization keeps the- model's dtype instead of coming back as float32. `OnnxLightGlue` without `onnxruntime` raises an- `ImportError` that names `pip install "kornia[onnx]"`, like the lazy-loader handles do, instead of a- bare `BaseError`. (#4301)-* `PinholeCamera.from_parameters` now fills `height` and `width` for the whole batch. It built them with- `height_tmp[..., 0] += height` on a `(B,)` zero tensor, so every batch element after the first kept `0`- while `fx`, `fy`, `cx`, `cy`, `tx`, `ty` and `tz` were broadcast correctly, and the camera looked healthy- until something read its image size. `batch_size=1`, the only case that worked, is unchanged. (#4279)-* `unproject_meshgrid` now returns the documented `(*, H, W, 3)` shape when `W` is 1. It squeezed the- meshgrid with a bare `.squeeze()`, which drops the width axis along with the leading batch axis whenever- `W == 1`, so `unproject_meshgrid(1, 3, K)` and `unproject_meshgrid(3, 1, K)` returned the same shape with- different values. The grid then broadcast across a phantom width in the two public functions built on it:- `depth_to_3d_v2` returned `(1, 3, 3, 3)` for a `W = 1` depth where `depth_to_3d` correctly returns- `(1, 3, 1, 3)`, and `warp_frame_depth` returned a 4-pixel-wide image for a 1-pixel-wide input. Only the- batch axis is dropped now. Output for every `W > 1` is byte-identical, and `depth_to_3d_v2` agrees with- `depth_to_3d` at `W = 1` as it already did everywhere else. (#4278)-* The generated example figures in the API reference are rendered from RGB input.- `docs/generate_examples.py` decoded the sample images with `cv2.imdecode` and wrote them with- `cv2.imwrite`, both BGR, so every tensor the examples fed to kornia held reversed channels. The two- swaps cancel in the written file for channel-agnostic operations, but 35 colour-dependent figures- change, and the ones that depend on which channel is which (`rgb_to_hsv`, `ColorJitter`,- `apply_colormap`, the bbox and keypoint colours of `AugmentationSequential`, ...) showed a blue cast- or swapped overlay colours. The generator now decodes and writes with PIL, draws the KeyNetAffNet- LAF figure with kornia's own `get_laf_pts_to_draw`, and `opencv-python` and `kornia_moons` leave- the `[docs]` extra. (#4306)-* `kornia.io.get_sample_images` and `kornia.onnx.ONNXLoader.list_operators` / `list_models` no longer need- `requests`, which `pip install kornia` never installed; they fetch with the standard library `urllib` instead.- The failure exceptions change with it, all still `OSError` subclasses: a sample-image URL that returns 404 now- raises `urllib.error.HTTPError` instead of `PIL.UnidentifiedImageError`, and an unreachable host raises- `urllib.error.URLError` instead of `requests.exceptions.ConnectionError`. A 404 from the Hugging Face listing- still raises the same `ValueError` (#4302)-* `packaging` is no longer a runtime dependency; it was never imported. The `dev` extra no longer lists- `pytest-cov` (CI runs `coverage run -m pytest`), `ruff` (the pre-commit hook installs the pinned copy) or a- `numpy<3` cap, and `uv.lock` is regenerated to match (#4296).-* `import kornia` no longer imports onnxruntime when it is installed (#4295)-* DeDoDe's vendored DINOv2 no longer probes for `xformers`; the pure-PyTorch path it always ran is the- only one. (#4288)-* `kornia.feature.LightGlue` no longer probes for `flash_attn`; the SDPA path it always used is now- the only one. `kornia.feature.lightglue.Attention.enable_flash`, the attribute that combined the- constructor argument with the probe result (and so always equalled the argument, because SDPA is- present on every supported torch), was renamed to `Attention.allow_flash`. (#4287)-* `bbox_to_mask3d` now returns the intersection of the three axis ranges for a box that covers or- overhangs a whole output axis, matching `Boxes3D.to_mask`, instead of filling the entire volume- (#4255, #4303). The old implementation `|`-ed the three broadcast axis slabs and tried to recover the- intersection with a three-way `all()` reduction; that recovery breaks the moment any one slab- covers a whole axis, since the union is then all-true on that axis and the reduction can no- longer see the other two slabs' bounds. Computing the intersection directly with `&` needs no- such recovery step. Interior boxes (the case the old reductions happened to recover correctly)- are unaffected and byte-identical.-* `solve_cubic`'s `D <= 0` (three-real-roots) branch no longer returns `nan` gradients for a- repeated or near-repeated real root (#4290, #4299). It differentiates `acos(R / sqrt(-Q3))`, whose own- derivative `-1/sqrt(1-x^2)` is unbounded at `x = +-1`; the branch condition guarantees the ratio- lies in `[-1, 1]`, but a repeated or near-repeated root pushes it to exactly that boundary,- where the value is correct but the derivative diverges. A double-root quartic reaches this- through `solve_quartic`'s resolvent cubic routinely, not as an edge case: measured on 20,000- random real-rooted quartics, 10.7% hit a non-finite gradient or a disconnected graph overall,- 35.3% for exact double-root pairs specifically. Same failure shape as the `acos`/`asin`- boundary in `quaternion_exp_to_log`/`euler_from_quaternion` (#4007, fixed in #4228) β this is a- different call site, not covered by that fix, using the same guard: differentiate a substituted- safe argument, take the value from a detached copy of the real (possibly boundary) argument.- Forward values are unchanged; re-running the same 20,000-trial search with the fix applied- drops the failure count to 1,269 β a real, separate residual (a disconnected-graph case with- two simultaneous double-root pairs) remains and is tracked in #4290, not fixed here.--* `pixel2cam` now rejects depth tensors outside the documented `Bx1xHxW` shape. The guard's predicate- bound as `(ndim != 4) and (shape[1] == 1)`, so four-dimensional multi-channel depth bypassed the- channel check β a three-channel depth silently broadcast into separate camera coordinates β while- scalar and one-dimensional inputs raised `IndexError` from the guard itself. Code that passed those- shapes and relied on them being accepted now raises `ValueError`. Valid `Bx1xHxW` depth is unaffected- and its output is unchanged. (#4314)-* `ConvQuadInterp3d` / `conv_quad_interp3d` no longer return NaN gradients for `float16` input. The- Hessian determinant `_solve_cramer_sym3x3` divides by is a product of three second derivatives, so for- a `[0, 1]` response it lands around 1e-4 and below and still clears the `eps` gate. The forward divides- by it once and stays finite, but the backward scales by `1 / det**2`, which `float16` cannot represent- (`finfo(float16).tiny` is 6.1e-5), so the gradient overflowed and reduced to NaN over part of the- volume. The solve is now promoted to `float32` for `float16` input and the shifts cast back, as #4231- already does for the half-precision meshgrid. `bfloat16` keeps `float32`'s exponent range and was never- affected; `bfloat16` and `float32` outputs are unchanged. (#4305)--* `RandAugment`, `AutoAugment`, `TrivialAugment` and `AugMix` no longer silently upcast half-precision- batches to `float32`. `OperationBase.forward` β the shared gate every auto-augment op routes through β- moved its `batch_prob` mask to `input.device` but not `input.dtype`, and since `batch_prob` is `float32`- the expression `batch_prob * op(x) + (1 - batch_prob) * x` promoted a `float16` / `bfloat16` input up to- `float32` (the op output and input are both low precision, only the gate was not). `float32` / `float64`- inputs are unaffected and their numeric output is byte-identical. The mask is now cast to `input.dtype`- as well. Partially addresses #4153: this clears the `RuntimeError` behind nineteen of that issue's Linux- CPU half-precision xfail lines for `tests/augmentation/test_auto_operation.py` (all ten `cpu_bfloat16`- entries, nine of the ten `cpu_float16`), which are removed from `testing/half_precision_xfails/`. The- tenth `float16` line is kept: `TestAutoAugment::test_reproduce[cpu-float16]` still fails, now on an- `AssertionError` rather than a `RuntimeError` β a smaller residual, not a fix. (#4210)-* Reduce local-feature extraction overhead by accumulating orientation histograms directly,- batching built-in DoG extrema refinement, selecting coordinates before combining response signs,- and using faster activation layouts in KeyNet and CPU HardNet. Detector settings and pretrained- checkpoint formats are preserved. On CUDA the orientation histogram now accumulates with atomics,- so identical inputs can differ at the ulp level between calls unless- `torch.use_deterministic_algorithms(True)` is set. (#4254)--* `quaternion_to_axis_angle` returns the correct gradient at every identity-like quaternion, not only the- positive unit identity `(1, 0, 0, 0)` (#4237). Its zero-vector-part branch used the constant `k = 2.0`,- which is only the `w = 1` case of the true analytic limit `k = 2 / w` (`w` = the real component); every- other identity-like input got a wrong gradient. That included the negative unit identity `(-1, 0, 0, 0)`- -- the same physical rotation as `(1, 0, 0, 0)` under the double cover -- which got the **wrong sign**- (`+2` instead of `-2`), and any non-unit "identity" such as `(2, 0, 0, 0)` (a scale this function- explicitly permits), which got the **wrong magnitude** (`+2` instead of `+1`). This was a genuine- backward-correctness defect, not a missing edge case: a valid unit quaternion could produce the opposite- gradient direction in pose optimization depending purely on which sign of the identity it started from.- The prior regression test for the `#3949` NaN-gradient fix only exercised `w = 1`, the one point where- the wrong constant and the correct formula happen to agree, and so could not have caught this. The- division needed for `2 / w` is guarded at `w = 0` the same way the function's existing `sin_theta`- division already is. That gate is `~pos` -- the mask that actually selects the branch -- and not merely- `w != 0`: `2.0 / t` lowers to `t.reciprocal() * 2`, whose backward is `-grad * result**2`, and for a- rotation just short of a half turn `w` is small but non-zero, so `(1 / w)**2` overflows to `inf` and- meets the exact `0.0` that the unselected branch receives as `0 * inf` -> `nan`. In `float16` that- would have been every rotation within ~0.45 degrees of 180 -- ordinary inputs, not degenerate ones.- The `2 / w` coefficient is also detached, because on the branch that selects it the vector part is- zero, so `d(out)/dw` is exactly zero there and computing it through `-2 / w**2` only reintroduces the- same overflow.-- The fully degenerate all-zero quaternion `(0, 0, 0, 0)` -- not a valid rotation -- keeps its- `(0, 0, 0)` forward value. Its gradient there changes, and improves: it was `(0, 2, 2, 2)` on torch- 2.14 but already `(nan, 2, 2, 2)` on torch <= 2.9.1, where `atan2(0, 0)`'s derivative with respect to- its second argument -- a `0 / 0` -- returns `nan`. `atan2` is now shielded across that whole masked- branch, which also clears a pre-existing `nan` for a zero vector part whose `w**2` underflows- (`w = 1e-30` in `float32`, `|w| < 2.4e-4` in `float16`). No gradient is analytically correct at a point- with no well-defined limit, so the changed value is not a regression.-- The forward value is unaffected everywhere: the `atan2` shield deliberately takes its value from the- unshielded expression, because routing `cos_theta` through `torch.where` hands `atan2` a contiguous- tensor instead of a stride-4 view and can select a different kernel. Verified byte-identical against- the previous implementation over 2000 random inputs in `float64`, `float32`, `float16` and `bfloat16`,- including forced unit, negative-unit, scaled, all-zero and near-half-turn quaternions, with no- non-finite gradient row remaining at any of those dtypes.--* Non-maxima suppression with a window larger than `(7, 7)` no longer builds a `(k*k, 1, k, k)` one-hot- convolution to gather each neighbour into its own channel. On CPU in half precision that convolution- has no vectorized kernel and falls back to `_slow_conv2d_forward`, where it accounted for 99% of a- `MultiResolutionDetector.detect` call. The window minus its centre is now covered by rectangular- `max_pool2d` regions whose full-width slabs share one column pass, costing `O(ky + kx)` taps per- position rather than `ky * kx - 1`, with the centre excluded by construction so the suppression stays- strict. `detect` on a 240x240 image drops from 5757 ms to 27 ms in float16 and from 73.8 ms to 13.8 ms- in float32; a 353x353 `k = 15` suppression drops from 3150 ms to 10.5 ms in float16 and from 42.6 ms to- 8.7 ms in float32, and from 12.1 ms to 0.15 ms for 1024x1024 `k = 21` on CUDA. (#4242)--* `nms2d` accepts a non-square `kernel_size`. It used to raise `RuntimeError: shape '[1, 1, -1, H, W]' is- invalid for input of size ...`, because the neighbourhood kernel was built with its two extents swapped- and the padding was applied to the wrong pair of edges. (#4240, #4242)--* `nms3d` accepts any `kernel_size`. Every size other than `(3, 3, 3)`, the one served by a hand-written- branch, used to raise: `_compute_zero_padding3d` defined a `(k - 1) // 2` helper and then returned the- full kernel sizes, so the padded volume did not match the kernel it was convolved with. (#4241, #4242)--* Eager bbox validation now rejects NaN and infinite coordinates: `validate_bbox` returns `False` and- `Boxes.from_tensor(..., validate_boxes=True)` raises `ValueError` for the `xyxy`, `xyxy_plus` and `xywh`- modes, instead of accepting them as valid geometry (closes #4238). (#4243)--* `HyNet` and `SOSNet` now run in half precision, on CPU and on GPU, and no longer return NaN for a- degenerate patch (closes #4224). Two defects sat on the same line. On CPU both raised- `NotImplementedError: "avg_pool3d_out_frame" not implemented for 'Half'` (and the `'BFloat16'` spelling):- their final `LocalResponseNorm` is handed a 4-D `(B, C, 1, 1)` tensor, which routes- `torch.nn.functional.local_response_norm` through `avg_pool3d`, and that kernel has no CPU- `float16`/`bfloat16` implementation. Separately, in `float16` on a device where the kernel does exist- (MPS, CUDA), the descriptors came back all-NaN for any patch the network maps to exactly zero: the `eps`- that keeps the normalisation's division defined (`SOSNet.forward`'s `eps`, `HyNet`'s `eps_l2_norm`, both- `1e-10`) is not representable in `float16` and flushes to `0.0`, leaving `0/0`. Every `Conv2d` in `SOSNet`- has `bias=False` and every `BatchNorm2d` is `affine=False`, so any constant patch reaches the- normalisation as exactly zero; `HyNet` reaches it only with `is_bias=False`. `bfloat16` keeps `float32`'s- exponent range, so the guard survives there and only the CPU kernel gap applied to it. Both models now- take that one normalisation step in `float32` for either half-precision input and cast the result back --- a wider lift than the `float16`-only one `kornia.feature.siftdesc` gives its own `1e-10` guards, because- the CPU kernel gap covers both dtypes. `float32` and `float64` take the original expression and are- bitwise unchanged on CPU, CUDA and MPS. Half-precision output does change, by 0.25-2.25 eps, and where it- moves most it moves towards the `float64` reference rather than merely away from NaN: `SOSNet` `float16`- goes from 2.15e-03 to 2.28e-04 of maximum absolute error against a `float64` model carrying the same- weights, and the configurations that do not improve stay within one eps of where they were.- Half-precision descriptors are therefore not comparable bit-for-bit across this release. (#4225)-* The `Import Surface` CI check accepts deliberate public-name removals recorded in the same change.- Edits to `tests/api_surface.json` must correspond to actual export removals and acknowledge only the exact- recorded module/name. Submodule APIs recorded only under an ancestor, and APIs outside the inventory, use- exact module/name entries in `tests/api_surface_removals.json`; only new entries matching a current- `__all__` removal count. Malformed records, deleted inventory module keys, unrelated Python edits, and- acknowledgements staged in earlier changes cannot authorize removals. Both record files trigger the workflow.- The export resolver includes implicit submodule bindings and rejects unsupported dynamic binding expressions- as evidence of removal. Deprecation windows and release notes still apply. (#4190, #4230)--* `resize` and `rescale` return an empty image for a zero-sized output instead of raising- `ZeroDivisionError` out of the scale-factor computation (#4115). `resize(x, (0, 4))`, `resize(x, 0)`,- `Resize((0, 4))`, and any `rescale` factor that takes a side to zero (`rescale(x, 0.0)`) previously died- in `h / size[0]`; they now return an empty tensor of the requested shape, which is the answer- `warp_affine`, `warp_perspective` and `center_crop` already gave for the same request. The empty result- stays connected to the autograd graph, the way `_empty_warp_output_2d` builds it for the warping ops, so- a batch element that degenerates to a zero-sized output still contributes a zero gradient rather than- detaching.-- A degenerate *input* is a different question and is now rejected rather than divided by: resizing a- `(1, 3, 0, 4)` image to a positive size, or with an `int` size at all -- an `int` names one side and takes- the other from an aspect ratio a degenerate input does not have -- raises- `ValueError("Input image size must be positive. Got height=0, width=4.")`, the message the warping ops- already use, instead of the same bare `ZeroDivisionError`. Empty in and empty out is well defined and- still comes back empty. (#4140)--* `validate_bbox` and `validate_bbox3d` flatten rank-4 `(B, N, 4, 2)` / `(B, N, 8, 3)` input with `reshape`- instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an- `expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)--* `quaternion_exp_to_log` and `euler_from_quaternion` no longer return `nan`/`inf` gradients at their- respective rotation singularities (#4007). Both differentiate an inverse trig function (`acos`, `asin`)- whose own derivative is unbounded at its domain boundary (`w = +-1`, `sinp = +-1`); `quaternion_exp_to_log`- hits that boundary exactly at the identity quaternion `(1, 0, 0, 0)` -- the standard initialization for- pose optimization -- where the unbounded derivative used to multiply the identity's exactly-zero vector- part into `0 * inf = nan`, and `euler_from_quaternion`'s `pitch` hits it at gimbal lock. Both now guard the- argument fed to the differentiated `acos`/`asin` call away from the boundary while taking the returned- *value* from a detached copy of the real (possibly boundary) argument, so the forward result is unchanged- -- verified byte-identical against the previous implementation over 500 random inputs including several- forced onto the exact boundary -- while the gradient no longer depends on what a given torch version or- backend's own `acos`/`asin` derivative happens to return there. `quaternion_exp_to_log`'s antipode- `(-1, 0, 0, 0)` still returns a large but finite gradient (`~pi/eps`) from an unrelated, pre-existing- division by its clamped (zero) norm; that is unchanged and out of scope here.--* `infer_bbox_shape` and `bbox_to_mask` now reject rank-4 `(B, N, 4, 2)` inputs with `ShapeError`. Previously,- `N < 3` raised an incidental `IndexError`, while `N >= 3` silently returned `(B, 2)` extents computed from the- wrong vertices. (#4218)--* Fix `symmetric_transfer_error` returning `NaN` instead of `max_num` for singular homographies.- When `safe_inverse_with_mask` flags an input as non-invertible, the unshielded inverse matrix containing- non-finite values propagated `NaN` through `oneway_transfer_error` and the arithmetic mask- `(there + back) * mask + max_num * (~mask)`, poisoning both the forward error and autograd gradients.- Singular rows are now replaced by the identity *before* the differentiable inverse is taken, so the- gradients with respect to both the correspondences and `H` itself stay finite (zero on the singular- rows), and the final masking uses `torch.where` to cleanly assign `max_num`. Values for invertible- homographies are unchanged; for `squared=False` a singular row now scores `max_num` rather than the- previous `(max_num + eps).sqrt()`, matching the documented contract. (#4203)--* Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global- `torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)--* Fix `Boxes.merge` concatenating along the vertex axis instead of the box axis- for unbatched `(N, 4, 2)` input. The old `dim=1` was correct for batched- `(B, N, 4, 2)` data (where dim 1 is the box axis) but wrong for 3-D tensors- (where dim 1 is the vertex dimension); `dim=-3` is correct in both cases and- the behaviour of the batched path is byte-identical. For list-backed inputs,- each batch row is now repacked with its real boxes before all trailing padding,- and the combined per-image padding counts are retained. This makes ``to_tensor``- trim only padding instead of dropping merged boxes or exposing old padding as- real boxes (#4168, #4175).--* `normalize_quaternion` floors a positive `eps` at the smallest positive `float16` subnormal, so its default- `eps=1e-12` remains an active division guard and a zero quaternion returns finite zeros instead of NaNs without- changing non-zero representable `float16` magnitudes. An explicit `eps=0.0` still disables the guard. This also- keeps `Quaternion.normalize`, `quaternion_to_rotation_matrix`, and their downstream pose conversions finite for- that input, matching the existing `float32`, `float64`, and `bfloat16` behavior (#4162).--* `Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8- vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the- classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an- axis-aligned box has such a 4-way tie by construction, where PyTorch's `amin`/`amax` backward splits the- gradient evenly across the tied vertices (`1/4` each): a valid subgradient, usable for optimization, but- one that `torch.autograd.gradcheck`'s central-difference estimate does not match at that exact point --- the same non-uniqueness any reduction has at a kink (`torch.max`, `ReLU`). That mismatch was previously- taken for a genuine gradient bug and `to_tensor` raised `RuntimeError` whenever its input required grad,- unconditionally, including for the common case of a caller who never differentiates through a tie at all- (an oriented, non-axis-aligned box, or a loss that never reaches the tied component). The guard is- removed; the docstring documents the tie behavior instead of calling it a bug. `Boxes` (2D) uses the same- reduction and was never guarded, because an axis-aligned rectangle's ties are always 2-way, where the- `1/2` split happens to numerically coincide with the central-difference estimate -- the same kink, just- invisible to `gradcheck` there.-* The pinned-torch CI legs no longer run against the lockfile's `triton`. `uv sync` installs the locked torch's- dependency set, and each matrix leg then swaps torch alone for a `+cpu` build -- whose wheels declare no `triton` at- all -- so the lockfile's triton survived as an orphan of a torch that was no longer installed. torch guards its- inductor triton path on import availability rather than on version, so it dispatched onto that orphan and the- `2.6.0` leg died in `from triton.backends.compiler import AttrsDescriptor` on 32 dynamo and export tests, having- never been green. The install step now drops sidecar packages the installed torch does not declare, and the- verification step asserts the whole environment against that torch (`.github/scripts/check_torch_env.py`) so a- mis-provisioned venv fails at setup instead of as a wall of unrelated-looking test failures. The five- `tests/core/test_small_linalg.py` ONNX cases the import error was masking now export with `external_data=False`,- which torch 2.6's dynamo exporter requires when the destination is a `BytesIO`. (#4199, #4200)--* `find_homography_dlt(..., solver="lu")` now solves the minimal four-point system with an adaptive- homogeneous gauge instead of applying LU to its singular normal matrix. This is the estimator- `RANSAC(model_type="homography")` calls for every minimal sample, so homography RANSAC results- change on every platform, not only where the old formulation broke down: over 2048 minimal- samples the median transfer residual drops from 2.3e-5 to 1.9e-6 and the worst case from 4.2e+5- to 4.5e+2. It also fixes the all-NaN homographies seen for a four-point sample on Windows with- PyTorch 2.14, and removes the corresponding CPU half-precision known failures. A four-point- sample containing a zero weight now returns a finite homography instead of NaN. Samples of five- or more points keep the previous normal-equation formulation and are numerically unchanged.- (#4197)--* `add_weighted` now keeps Python scalar weights in operator math precision instead of rounding them to the input- dtype before arithmetic. This improves `float16` and `bfloat16` accuracy and makes fractional scalar weights on- integer inputs produce the correctly promoted floating-point result instead of being truncated. (#4154)--* `distance_transform` no longer silently returns a wrong or all-zero result when its `exp(-dist/h)` kernel- underflows (#4152). The kernel's axis-aligned tap, at distance `kernel_size // 2` along a single axis,- underflowing to exactly zero -- reachable from the documented default `h=0.35` at `kernel_size >= 15` in- `float16` -- used to make the convolution silently drop it, returning a plausible-looking but wrong distance- field or, with a smaller `h`, an all-zero one. Two changes: `float16`/`bfloat16` inputs now run the cascade in- `float32` and cast the result back (the default `h=0.35` case is fixed by this alone, matching `float32`'s own- working range); and an `h`/`kernel_size`/dtype combination whose axis-aligned tap still underflows- `torch.finfo(dtype).tiny` now raises instead of guessing. This also catches a case that is not itself- numerically wrong on CPU (`h=0.01` at `kernel_size=3` in `float32` tracks the analytic reference to ~2e-4,- carried through the subnormal range) but where MPS flushes subnormals to zero while CPU does not, so the same- call used to silently disagree across backends; raising there rules out that disagreement rather than trusting- which backend a caller happens to run on. Concretely, at the documented default `h=0.35` in `float32`,- `kernel_size >= 63` now raises: CPU used to return a usable-looking answer there while MPS silently returned- something else for the same call.--* Fix `Boxes3D.from_tensor(..., mode="xyzwhd")` to preserve width, height, and depth field order for asymmetric- boxes. (#4189)--* `RandomTransplantation` and `RandomTransplantation3D` transplanted nothing on MPS when no `excluded_labels`- were given: PyTorch's MPS backend evaluates `all()` over the empty excluded-label axis to an undefined value,- usually `False`, so every donor label was filtered out and the output equalled the input. The filter is now skipped when there is- nothing to exclude. (#4160)--* `VisualPrompter.predict()` called without any prompt (the "run the prediction without prompts" example on the- Segment Anything page) raised `TypeError: object of type 'NoneType' has no len()` from the prompt augmentation- container; it now predicts from the image embedding alone, as documented. (#4178)--* Preserve empty color tensors on accelerator backends instead of asking `reshape` to infer an ambiguous batch- dimension. This lets the YUV420 and YUV422 empty-input conversions return their documented empty RGB output on- MPS, matching CPU behavior (#4185).--* Follow-up fixes to the documentation revamp (#4155): the landing page's filtering card quoted the combined- `filters`/`color`/`enhance`/`morphology` count next to a `kornia.filters` label, the "Why Kornia?" hero carousel- resumed after a visitor picked a tab, the Community page linked to the now-unregistered `librecv.org`, and the- GPU page promised CUDA measurements the committed benchmark runs do not yet contain. `pydata-sphinx-theme` is now- version-bounded, since the site's CSS and JS target theme internals. (#4173)-* Reset an automatic augmentation policy's cached transformation matrix before applying it again, both for a- sub-policy inside `TrivialAugment`, `RandAugment` and `AutoAugment` and for those policies nested inside- `AugmentationSequential`. Consecutive calls that selected the same geometric policy could transform the input with- the latest parameters while exposing the previous call's matrix through `transform_matrix`, the sub-policy- accumulated one matrix per call for the lifetime of the module, and a nested policy never recorded its parameters- or matrix at all. `transform_matrix` on a policy that has not run yet now returns `None` instead of raising- `AttributeError` (#4171).--* `MultiResolutionDetector.detect` apportions `num_features` across pyramid levels with largest-remainder- (Hamilton) apportionment instead of flooring each level's fractional share independently (#4101). The floors- used to discard every fractional part, so a small `num_features` could round the whole apportionment down: with- the default configuration the six shares are `0.508 .. 0.016`, and every level but the finest lost its entire- quota to truncation, so the detector effectively searched a single scale. The shortfall -- `num_features` minus- the sum of the floors -- is now handed to the levels with the largest fractional remainder, one slot each, so- the quotas always sum to exactly `num_features` and stay spread across scales. #4098's narrower `num_features=1`- fallback, which handed the request's one slot to the largest-share level when every quota floored to zero, is- the special case where the shortfall equals `num_features` and is superseded by the general apportionment.- The apportionment was then removed again by #4222 below, inside this same unreleased window, so no release- ever carries it; the `num_features=1` behaviour it fixed still holds.--* `MultiResolutionDetector.detect` now returns the `num_features` highest responses in the image (#4222). Each- pyramid level used to be asked only for its own share of the budget, so a level could contribute at most- `quotas[0]` (the upscaled level) or `sum(quotas[: i + 1 + up_levels])` (pyramid level `i`) -- both well under- `num_features` for the finer levels. When an image's strongest maxima concentrated on one level, which is the- common case rather than a corner case, the excess was never requested and so could not be ranked in by the- final global `topk`: the detector silently returned something other than the top-k, and the sorted responses of- `detect(k)` were not a prefix of those of `detect(k')`. Every level is now searched for `num_features` candidates, which is exactly sufficient- because the detections a level contributes to the global top-k are that level's own strongest. The per-level- apportionment, including #4101's largest-remainder rounding, is removed with it. This changes which keypoints- are returned for a given image: callers get strictly better-ranked detections, and any result that depended on- the old per-level spread will differ. The prefix is on the sorted responses, not on which detection carries a- given response: `topk` breaks a tie by position, so exactly equal maxima can come back in a different order for- a different `num_features`. It carries about 1.2x the candidates through the concatenation, which is not- measurable next to the response function and the non-maxima suppression.--* Make YUV and XYZ transformations compute integer inputs in `float32` instead of truncating their kernels, and- preserve directly constructed `float64` coefficients. This makes `rgb_to_yuv(uint8)` return `float32` on the- input's original 0--255 scale, fixes signed-integer YUV results, and removes the existing float32 coefficient loss- from float64 XYZ conversions. The two private linear-transformation helpers are now one implementation, whose CPU- path uses its dtype/device-aligned compute operands (#4053).-* Fix 2-D, 3-D, and mix augmentations raising a cross-device `RuntimeError` when their random parameters are generated- on the default CPU device and their input is on MPS or CUDA (#4164). Since #3722, four branchless `torch.where`- blends used the CPU `batch_prob` mask directly with accelerator outputs or transformation matrices. The selection- mask now moves to the output device at each blend boundary, preserving CPU random-number generation and the- ONNX/fullgraph-friendly blend. Calling `augmentation(x_accelerator)` therefore works again without first moving the- augmentation module or its RNG to the accelerator (#4151).--* Keep `extract_patches_simple` and `extract_patches_from_pyramid` off a broken reduced-precision CPU kernel: for a- `float16`/`bfloat16` CPU image, the `grid_sample` kernels in torch <= 2.9 read out of bounds when a rotated patch- straddles the image border and return NaN or garbage values far outside the image's range. Both extractors now- sample reduced-precision inputs in `float32` on every device and cast the patches back. This fixes the CPU kernel- bug and avoids normalized-coordinate precision loss on large images; half-precision patches change on every- backend, with the CUDA cost described under **Breaking changes** above. Both extractors also replace their- per-image Python loop with a folded batched `grid_sample` over a `(B, N*PS, PS, 2)` grid, split along `N` when- needed to bound its workspace. Both forms compile under `fullgraph=True`, but the loop was unrolled at trace time- into one `grid_sample` per batch element, so the graph grew with the batch and was recompiled for every new batch- size: tracing `extract_patches_simple` over batches of 2, 3, 5 and 7 built four graphs of 2/3/5/7 `grid_sample`- nodes before and builds two graphs with one node each now.--* `extract_patches_simple` and `extract_patches_from_pyramid` return an all-zero patch and a zero LAF gradient for a- non-finite LAF frame instead of handing `grid_sample` an invalid grid. A frame holding a NaN or an infinity- anywhere -- including only in its center -- is detected and sanitized before any grid arithmetic, and finite frames- in the same batch are untouched. Such a frame previously produced a finite-looking border-sampled patch, and its- backward pass could terminate the process inside torch's CPU `grid_sampler_2d_backward` kernel with- `padding_mode="border"`; a training-time detector that emits a degenerate LAF hits exactly that path through- `LAFOrienter`, `LAFAffNetShapeEstimator` and `LAFDescriptor`.--* `normalize_laf`, `denormalize_laf` and `generate_patch_grid_from_normalized_LAF` count a singleton image axis as- one pixel of extent instead of dividing by `size - 1 == 0`. `normalize_laf` raised `ZeroDivisionError` for a- 1-pixel-wide or 1-pixel-tall image -- and with it both patch extractors on their default- `normalize_lafs_before_extraction=True` path -- while `denormalize_laf` silently collapsed every LAF to zero.- The conversions are now finite and round-trip, and both extractors return finite patches for such an image.--* Replace the batched `torch.inverse` in `ellipse_to_laf` with the closed-form inverse of its lower-triangular- 2x2 matrix. Results agree with the previous implementation to ~1.6e-7 relative in `float32` (machine epsilon in- `float64`). Reproducible numbers via `benchmarks/feature/ellipse_to_laf.py` (float32, N=1e3..1e5, torch 2.9.1,- Linux/WSL2, base `2009933e`): throughput improves ~2.4-5.3x eager / ~3-6.5x compiled on CPU (i7-14700K) and- ~1.4-1.7x eager / ~4.2-5.5x compiled on CUDA (RTX 4090). The largest win is MPS, where the batched inverse hit a- pathological `linalg` path, emitted a deprecated-resize `UserWarning` on every call, and failed to `torch.compile`- (~1500x once measured ad hoc at N=20000 on Apple Silicon; rerun the benchmark there for a citable number). The- function now compiles with `fullgraph=True` on every backend and accepts `float16`/`bfloat16` on CPU, where the- raw `.inverse()` call raised for low-precision dtypes (`_torch_inverse_cast` would have lifted that restriction- too; the closed form is for speed). The off-diagonal divides `a21 = b / (a11 + a22)` by the product of the- diagonal square roots, which can neither overflow nor round to zero: every ordering of the reciprocal product- overflows to `inf` (or flushes a representable value to `0`) on a sufficiently lopsided or subnormal diagonal,- and when that product is subnormal the division loses precision but never corrupts a representable result to a- zero, `inf`, or `nan`.--* Drop the constant homogeneous row from `laf_to_boundary_points`. The function appended a `[0, 0, 1]` row to every- LAF so that it could divide the result by a homogeneous coordinate that is always exactly `1`; it now multiplies- by the `(2, 3)` LAF directly, and moves its 3-column basis to the LAF's device and dtype before broadcasting it- instead of after (the previous order materialized, and on an accelerator transferred, one copy per LAF -- ~12 MiB- per call at `N = 20000` for a tensor with `n_pts` distinct rows). The win is not the transfer: torch's CPU- batched gemm falls off a fast path at the third row, so `bmm` on a `(B, 3, 3)` operand costs 23x a `(B, 2, 3)` one- for 1.5x the arithmetic. Quiet back-to-back A/B against base `8db1499a` via `benchmarks/feature/laf_ops.py`- (Apple M1, torch 2.14.0, 4 threads, B=1 N=20000): `laf_to_boundary_points` 1.07M -> 29.6M LAFs/s eager on CPU and- 1.77M -> 4.27M on MPS; `laf_is_inside_image`, which calls it with `n_pts=12` on every detector forward,- 9.75M -> 29.0M on CPU and 2.70M -> 8.53M on MPS. Results are bitwise identical on CPU `float16` and `bfloat16`- and shift by at most 1.42 machine epsilon elsewhere, relative to the largest coordinate of the call -- the two- gemm shapes round differently. Mean error against a `float64` reference is slightly lower than before, and- `laf_is_inside_image`'s boolean masks were bitwise identical across a 126-case device/dtype/shape sweep. (#4217)--* Make `load_pointcloud_ply` and `load_pointcloud_ply_binary` parse the PLY header instead of skipping a fixed- number of lines. Both loaders skipped `header_size=8` lines and read everything after them as `x y z` triples, so a- minimal PLY file (seven header lines, no `comment`) lost its first point to a header line -- the binary reader- returned header bytes decoded as doubles -- and any file with extra vertex properties (normals, colours) or a- `face` element after the vertices was rejected or misread. The readers now stop at `end_header`, take the point- count from `element vertex N`, select `x`, `y`, `z` by property name whatever their scalar type, skip trailing- elements, and read big-endian payloads. `header_size` is deprecated and ignored (a `DeprecationWarning` is- emitted when it is passed). Files without a proper PLY header, which the old line-skipping loader could read- by accident, are now rejected with a `ValueError`, and so is a file that declares a `list` property among the- vertex properties -- a list has no statically known length, so the columns after it cannot be located. The- binary reader additionally rejects a `list` property in an element that *precedes* the vertices, whose byte- length it would have to know to reach the vertex data; the ASCII reader reads such a file, since every ASCII- element instance is one line whatever it contains.--* Make `guided_blur` / `GuidedBlur` work in `float16` and `bfloat16` when the guidance has more than one channel.- Multi-channel guidance solves a per-pixel `C x C` system, and `torch.linalg.solve` has no half-precision LU- kernel, so every such call failed: on CPU with `NotImplementedError: "lu_cpu" not implemented for 'Half'`, and on- MPS with a hard `Only MPSDataTypeFloat32 is supported` assertion that aborted the process rather than raising.- The system is now solved in `float32` and cast back. A tensor `eps` also takes part in dtype promotion, so- the common `eps=torch.tensor(0.1)` (float32) widened the matrix past the right-hand side and made `solve`- reject the pair; both operands are now solved in one dtype. Single-channel guidance never reached the solver- and is unaffected. `float32` and `float64` results are bit-identical to before, and the op still compiles with- `fullgraph=True` in one graph. This takes `tests/filters/test_guided.py` from 98 failed / 67 passed to- 169 passed under `--dtype=float16,bfloat16`.--* Raise `NotImplementedError` instead of `RuntimeError` for an integral `src` on the empty-`dsize` paths of- `warp_affine`, `warp_perspective`, `remap`, `warp_affine3d` and `warp_perspective3d`, matching what the non-empty- path already raises from `grid_sample` (#4031). The degenerate path had its own explicit guard that fired first- with a different exception type, so the exception a caller saw for the same invalid input depended on whether- `dsize` had a zero dimension. The message is unchanged. `NotImplementedError` derives from `RuntimeError`, so- `except RuntimeError` around these functions still catches it; only code matching on the exact type sees a- difference.--* Validate the chroma plane height in `yuv422_to_rgb`, so a chroma plane whose height does not match the luma now- raises `ShapeError` instead of reaching `torch.cat` and dying there with a bare `RuntimeError` (#4050). 4:2:2- subsamples width only, so chroma keeps the full luma height; the guard checked only the width ratio, where the- 4:2:0 twin `yuv420_to_rgb` checks both axes. This is observable to callers on the error path: `ShapeError` derives- from `BaseError`, not `RuntimeError`, so code catching `RuntimeError` around `yuv422_to_rgb` to handle a malformed- chroma plane will stop catching it. No previously working input changes behaviour β `torch.cat` already rejected- every mismatched height. A zero-width chroma plane whose height *also* differs now reaches the guard, since the new- clause short-circuits the width division; the matching-height case still raises- `ZeroDivisionError` and remains open as #4056.--* Make `yuv_to_rgb` the exact inverse of `rgb_to_yuv`, so an RGB β YUV β RGB round trip is now limited only by the- input dtype instead of losing up to `1.36e-3` (in B, at `rgb = (1, 1, 0)`) at every precision, `float64` included- (#4044). The inverse kernel was a separately rounded copy of the published BT.470-5 M/PAL inverse relations rather- than the inverse of the rounded forward kernel kornia actually ships, and one of its literals β `2.029`, where the- inverse of kornia's forward kernel is `2.03199968` β carried most of the error. `yuv_to_rgb` output therefore moves- by up to `1.23e-4` in R, `9.13e-4` in G and `1.60e-3` in B over the documented YUV domain, and `yuv420_to_rgb` and- `yuv422_to_rgb` move with it. The forward direction (`rgb_to_yuv`, `rgb_to_yuv420`, `rgb_to_yuv422`) is unchanged.- Agreement of the inverse with the standard's own relations improves overall, from `1.54e-3` to `5.24e-4`, though R- alone moves the other way (`1.54e-4` to `2.77e-4`). The `.. warning::` blocks that documented the defect on the six- affected functions and classes are gone.--* Fix the inverted `SigLip2` attention-mask polarity, so every call that passes an `attention_mask` changes (#4043).- All three mask branches of `SigLip2Attention` (2-D `(B, N)`, 3-D `(B, N, N)` and 4-D `(B, 1, N, N)`) negated the- mask before handing it to `torch.nn.functional.scaled_dot_product_attention`, whose boolean form reads `True` as- *attend*, not as *mask out*. Every position the caller asked to attend to was masked out and every padded position- attended to, so an all-ones mask left every query row fully masked. The symptom is version-dependent because a- fully masked row returns `0` from SDPA on PyTorch 2.5 and later and `nan` on PyTorch 2.4 and earlier:- `SigLip2.get_text_features(..., attention_mask=...)` has been returning a zeroed attention output on current- PyTorch and `nan` text features on the declared `torch>=2.0` floor. 2-D padding masks are now broadcast over the- key axis only, matching `SiglipTextTransformer.create_bidirectional_mask` in Hugging Face `transformers`, so a- partially padded sequence no longer produces a fully masked row. A row whose mask is entirely zero β an empty- caption in a batch β is still fully masked and still follows the SDPA behavior above.--* Fix `find_essential` and `run_5point` raising `TypeError: all() received an invalid combination of arguments` on- PyTorch before 2.2 (#4043). `run_5point`, `_solve_2x2_tikhonov_safe` and the scripted Nister helper each reduced- over two axes at once with `Tensor.any(dim=(-2, -1))` / `Tensor.all(dim=(-1, -2))`, and multi-dimension `any`/`all`- only landed in PyTorch 2.2, so the whole five-point solver was unusable on the declared `torch>=2.0` floor. The- reductions now flatten the two trailing axes first, which is equivalent on every version.--* Fix `torch.jit.script` of `rgb_to_yuv`, `yuv_to_rgb`, `rgb_to_xyz` and `xyz_to_rgb` on older PyTorch (#4043). Their- shared `kornia.color.utils._apply_linear_transformation` helper annotated its optional argument with the PEP 604- `torch.Tensor | None` form, which the TorchScript compiler on the declared floor does not accept (reproduced on- PyTorch 2.1.2, while PyTorch 2.9.1 compiles it), so scripting any of the four conversions failed. The annotation is- `Optional[torch.Tensor]` now, which every supported version accepts.--* Define singleton pixel axes at normalized center, reject non-positive normalization sizes, preserve empty warp- destinations, and deprecate the now-unused `eps` normalization parameters (#4006). The four- `{de,}normalize_pixel_coordinates{,3d}` helpers and `normal_transform_pixel{,3d}` now derive their scale from the- size directly instead of rounding the size into the coordinate dtype first, so results at non-degenerate sizes can- move toward the exact value: by up to one ulp in `float32`/`float64`, but materially more in `float16`/`bfloat16`,- where the old code could not represent the size at all (`denormalize_pixel_coordinates` at `bfloat16` and size 3000- returns 1496 where it returned 1504).-- A singleton axis previously divided by zero (or by the `eps` substituted for it), so the change is not confined to- those helpers: it reaches every operation that normalizes a coordinate frame with a size-1 dimension.- `create_meshgrid(1, 4, normalized_coordinates=True)` returned `nan` in the singleton component and now returns `0`;- `warp_perspective`, `crop_by_transform_mat`, `homography_warp` and `warp_image_tps` onto a 1-pixel-high destination- returned all-`nan` and now return the finite row the 2-pixel control produces; `spatial_soft_argmax2d` and- `spatial_expectation2d` on a 1-pixel-high input returned `nan` and now return `0`; and `conv_soft_argmax2d`,- `conv_soft_argmax3d` and their `ConvSoftArgmax*` module forms shift by one normalized unit when a kernel or input- axis is `1` (`conv_soft_argmax2d` with a `(3, 1)` kernel returned `[-1.6667, -1.0, ...]` and now returns- `[-1.0, -0.3333, ...]`).--* Restore the YUV test coverage that #3539 deleted, and fix the `kornia.color` YUV docstring examples (#4045).- `rgb_to_yuv422` and `yuv422_to_rgb` both documented an example that called the 4:2:0 function instead of- themselves, so a reader copying either got the wrong conversion and the wrong chroma shapes; several other- examples stated a shape in a trailing comment that disagreed with what the function returns- (`RgbToYuv420` said `2x1x2x3` for a `(2, 2, 2, 3)` chroma plane). Every example in `kornia/color/yuv.py` now- asserts its output shape as a doctest instead of stating it in a comment. The 4:2:2 docstrings also claimed- the input only had to be divisible by 2 "vertical" while the guard rejects odd height *and* odd width, so a- reader padding one axis hit a `ShapeError`, and `yuv422_to_rgb` labelled its chroma argument "UV (luma)".- The four `ShapeError` messages those guards raise said "evenly disible by 2" and now say "divisible", as do- the two identical messages in `kornia/color/raw.py`. `yuv422_to_rgb`/`Yuv422ToRgb` also gained a- `.. warning::` naming a known defect: they validate only the chroma *width*, so a wrong chroma height- surfaces as a bare `RuntimeError` from `torch.cat` (#4050). The same entry gave every YUV-to-RGB form a- second warning, for the round trip that #4044 has since fixed; those blocks are gone, see the entry- above. On the test side, both gradcheck skips now cover the XLA/TPU fixture as well as MPS, since XLA- lowers a float64 request to float32, where gradcheck's default `eps=1e-6`- makes the numerical Jacobian invalid: the name-based marker in `conftest.py` for tests called `*gradcheck*`,- and the device guard in `BaseTester.gradcheck` for the six callers named something else. No runtime- behavior changed.--* Fix `SIFTDescriptor.gk`, `PatchDominantGradientOrientation.weighting` and `PatchAffineShapeEstimator.weighting`- being plain attributes, so `nn.Module.to()` left them behind on the original device and dtype (#4069). They are- now non-persistent buffers: `.to()`, `.cuda()`, `.half()` and friends move them, and because they are fully- determined by `patch_size` they stay out of `state_dict()`, so existing checkpoints still load with- `strict=True`. The three `forward` methods also cast into a local instead of rebinding the attribute, so a call- no longer leaves the module's kernel in whatever dtype and device the last input happened to have. Numerical- output is unchanged: the kernels were already cast to the input's dtype and device inside `forward`.-* Fix patch extraction on MPS returning darkened patches for any LAF that touches an image border (#4063).- MPS has no `padding_mode="border"` for `torch.nn.functional.grid_sample`, so `extract_patches_simple` and- `extract_patches_from_pyramid` emulate it with zero padding and a clamped grid. The clamp was `grid.clamp(-1, 1)`,- but with `align_corners=False` normalized coordinate `Β±1` is the outer *edge* of the border pixel, not its center,- so bilinear sampling blended the border pixel with the zero padding and returned roughly half its value. The grid- is now clamped to the outermost pixel centers, `Β±(1 - 1/size)` per axis, which reproduces `padding_mode="border"`- exactly. On a patch overlapping the image corner the maximum deviation from the CPU result drops from `0.395` to- `2.5e-6` on a `[0, 1]` image, with 64.7% of the patch's pixels previously off by more than `1e-3`. Every descriptor- built on these patches β `get_laf_descriptors`, `LAFDescriptor`, `SIFTFeature`, `KeyNetAffNetHardNet` and the rest β- moves with them for keypoints near the border. The CPU and CUDA paths never took this branch and are byte-identical- to before.-* Fix `match_fginn`'s geometric consistency check comparing every query's candidates against **query 0**'s- candidates instead of against the query's own 1st nearest neighbor, which changes every `match_fginn` and- `GeometryAwareDescriptorMatcher("fginn")` result -- the latter being that class's *default* mode (#4062). The distance- `kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[0, k]] ||` was measured from a slice of dim 0 that broadcast query 0's- whole candidate list over the batch; it is now `candidates_xy[:, 0:1]`, i.e.- `kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[i, 0]] ||`. Three consequences disappear with it. The geometric term- was inert -- an unrelated query's candidates are almost always farther apart than `spatial_th`, so nothing was- penalized and the raw 2nd nearest neighbor was used, making `match_fginn` behave as `match_snn`: on a 300x300- descriptor set with planted near-duplicates, 15 of the 15 matches shared with `match_snn` had an identical ratio- before and 14 of 15 after. Query 0 always matched, since `candidates_xy[0] - candidates_xy[0]` is identically zero,- so all of its candidates were penalized and its ratio collapsed to ~0. And a query's ratio depended on the other- queries in the batch: with only query 0 changed, one query's ratio moved between `0.9005` and `2.8e-08`. The seven- existing FGINN tests pass unchanged on both sides, which is how this survived; two tests that discriminate it were- added. `match_fginn`'s docstring now also records the saturation corner, where every candidate falls within- `spatial_th` of the 1st nearest neighbor, the ratio collapses towards zero and the match is accepted.-* Fix `DenseSIFTDescriptor` registering a process-global cached tensor as its `_poolingconv_weight` buffer, so that- one instance's `load_state_dict` silently corrupted every other instance and every instance constructed later- (#4068). `_get_reshape_kernel` memoises `torch.eye(numel)` per `numel` and used to return a *view* of the cached- tensor; `.float()` on an already-float tensor returns the same object, so no copy happened between the cache and- the buffer, and `load_state_dict` copies into buffers in place. Loading a checkpoint into one `DenseSIFTDescriptor`- therefore overwrote the shared identity matrix, with no error raised and every descriptor built from it wrong from- then on. The cache is removed rather than made safe: cloning on the way out is what a safe cache requires, and a- clone costs more than rebuilding the identity at every size measured (2.6 us against 2.0 us at the default- `numel = 8 * 4 * 4`; 3.9 ms against 2.8 ms at the former 4096 bound, which also retained 67 MB for the lifetime of- the process). Descriptor output is byte-identical to before.-* Fix `laf_is_inside_image` treating the image extent as `(w, h)` rather than `(w - 1, h - 1)`, which made its- bounds asymmetric: the lower bound rejected anything left of `x = 0`, but the upper bound accepted `x = w`, a- full pixel past the last valid column `w - 1` (#4064). Valid pixel coordinates run `0 .. w-1` and `0 .. h-1` --- the convention `get_laf_center` documents and the one `normalize_laf`/`denormalize_laf` already use -- so the- upper bound is now `w - 1 - border` and `h - 1 - border`. A LAF whose boundary points reach past the last valid- pixel coordinate is now reported as outside; anything strictly inside is unchanged. The equivalent inlined check- in `ScaleSpaceDetector._process_octave` moved with it, so detections within one pixel of the right or bottom edge- that used to survive its `border=5` filter are now discarded. That inlined check also computed its `max |sin|`- constant with the wrong angular spacing (`2*pi/11` instead of the `2*pi/10` that `laf_to_boundary_points(n_pts=12)`- actually samples), inflating the tested x-extent by 4% and making the inline check stricter than the reference it- claims to reproduce; the two now agree exactly. That correction is a loosening in x, so it can change- `ScaleSpaceDetector` output on its own: a detection whose x-extent falls between the two constants used to be- discarded and is now kept. It is rare -- the detection has to land in a band of width `0.039 * half_s` against the- x bound -- but when it fires it can promote the strongest response in the image, so it is not output-neutral.-* Fix the empty-result paths in `kornia.feature.integrated` disagreeing with the corresponding non-empty ones- (#4065). `get_laf_descriptors` returned a hardcoded width of 128 with the *LAF's* dtype and device when it was- handed no keypoints, so an empty batch through, say, a 256-d descriptor produced a `(B, 0, 128)` result that could- not be concatenated with a real one; it now runs the descriptor once on a zero patch and returns its actual width- (the flattened per-patch output, matching the non-empty path's `.view(B, N, -1)`), dtype and device. That is a- widening of the empty path's failure surface: a third-party descriptor that raises on a zero input now raises here- where it previously returned quietly. `LocalFeatureMatcher.no_match_output` returned `lafs0`/`lafs1` of shape- `(0, 0, 2, 3)` where the success path returns `(1, NC, 2, 3)`, so `lafs0[0]` raised `IndexError` exactly when- nothing matched; the empty tensors now keep the leading batch of 1. That is a shape change on a public return- value -- code using `out["lafs0"].shape[0] == 0` as its no-match signal now sees `1` and should test- `out["keypoints0"].shape[0] == 0`, which was already the consistent signal. `LocalFeatureMatcher.forward`'s- docstring also stops claiming `confidence` is in `[0, 1]`: it is `1 - distance`, which for the raw-distance- matchers `nn` and `mnn` goes at least down to -1 on unit-norm descriptors, and is unbounded below for arbitrary- ones.--* Stop `MultiResolutionDetector` (and therefore `KeyNetDetector`) fabricating detections, honour its `mask` argument,- and keep its LAFs in the input dtype (#4089, #4090, #4091).-- **Padded slots are zero, and the shape is always `num_features`.** `detect_features_on_single_level` masked every- non-candidate position to `torch.finfo(dtype).min / 2` and then ran `topk` with `k` clamped against the *pixel- count* rather than the number of surviving candidates. Once a pyramid level ran out of above-threshold maxima,- `topk` could no longer rank -- every remaining position carried the same sentinel -- so it returned an arbitrary- tie-break subset, in practice the low flat indices, which is exactly the border strip `remove_borders` had just- zeroed. `MultiResolutionDetector(BlobHessian(), num_features=100)` on a plain `64x64` image returned 70 of its 100- features that way, each with a response of `-1.7e38` and a real-looking coordinate. Those slots are now padded- with a zero response and a zero LAF, which is what `ScaleSpaceDetector.detect` already does for a short result,- and `forward` re-applies that padding after the affine-shape and orientation modules, which would otherwise- normalise a zero frame into a finite one. `detect` also only ever *trimmed* an over-long result, so a level- capped at its own pixel count, or a per-level quota rounded down to zero, produced a short one: a one-level `8x8`- image asking for 100 features returned 64, and the default configuration asking for 1 feature returned **0**,- which made `lafs[0, 0]` raise. The result is now padded up to `num_features` with the same zero response and- zero LAF. Callers that tested for the sentinel (`resp < 0`) should test `resp == 0`; callers that consumed the- responses as scores no longer need to.-- **`num_features=1` returns a real detection.** The per-level quotas each truncate independently, and at- `num_features=1` the six default shares are `0.508 .. 0.016`, so every one of them rounded to zero and no level- was asked for a single candidate. The apportionment now hands its one slot to the level with the largest share- whenever truncation would otherwise lose every slot, so `num_features=1` returns the same best feature that- `num_features=2` returns first. An apportionment that already gives out a slot is untouched, which with the- default configuration is every `num_features >= 2` (verified byte-identical with `torch.equal` over 16 size/count- combinations).-- **The `mask` argument works, and means "where a detection may be".** `forward(img, mask)` and `detect(img, mask)`- accepted a `mask`, documented it as "a mask with weights where to apply the response function", and ignored it --- an all-zero mask returned bit-identical output. Anyone who was passing a mask and silently getting unmasked- detections now gets masked ones. The semantics are the same in both detectors and are chosen from the caller's- side. A boolean or integer mask is binary: any non-zero value keeps a position, so a 0/1 mask, an OpenCV 0/255- mask and `img > 0` all mean the same thing (a raw cast would have multiplied the responses by 255 and defeated an- absolute `score_threshold`). A floating-point mask is used as weights on the detection scores: a weight in- `(0, 1]` scales a score toward the worst -- a non-negative score is multiplied by it, a negative one divided -- so- a down-weighted candidate never outranks a full-weight one with an at-least-as-good score (a plain multiply pulled- a negative score toward zero, i.e. *up* the ranking of a signed response), and a zero or negative weight- suppresses. The weights are cast to the image dtype, so a weight a half-precision image cannot hold rounds to- zero and suppresses, and clamped to one, so a float 0/255 mask (an OpenCV mask through `.astype(np.float32)`)- means what the integer one means rather than scaling every score by 255. The weighting runs in float32 for- half-precision input and is bounded at the dtype's most negative finite value, so a negative score divided by a- small weight cannot overflow to `-inf`; an unfilled slot is ranked with `-inf` (not a finite sentinel such as- `finfo.min / 2`, which a genuine extreme response could sort below, and did: four float32 maxima at `-2e38`- were returned for a single image and dropped for a batch), so every finite detection precedes the padding. The- mask is checked at the integer maximum and again at the sub-pixel-refined centre, conservatively (every octave- pixel the centre touches), so the refinement cannot carry a detection into the zero region. A NaN weight- suppresses rather than winning the ranking. The mask must be `(1 or B, 1, H, W)` with the- image's spatial size. It is resampled onto every pyramid level or octave with a- min-pool rather than an interpolation, so a zero region suppresses every level pixel it touches and a two-pixel- zero stripe does not vanish at a factor-four level. And it is applied to the non-maxima-suppression output, not- to the response the suppression reads: multiplying the response first carves an edge into it, and the bilinear- ramp of that edge was a "maximum" on the suppressed side, so a blob wholly inside the zero region was still- detected (#4102). `ScaleSpaceDetector`, which did multiply its response per octave, takes the same path; its- detections inside the region kept by a binary mask are unchanged. A *floating-point* mask used to weight the- response before the non-maxima suppression and the sub-pixel refinement, so a graded mask moved maxima and- their refined positions; it now weights only the score of a maximum found in the unweighted response, so the- set of candidates and their positions are those of the unmasked image and the weight decides their rank.-- `LocalFeatureMatcher` now carries those masks through the full extraction-and-matching path. It documented- `mask0`/`mask1` as `(B, H, W)` inputs but never passed either to its local feature module; that historical shape is- accepted by adding the singleton channel, and the detectors' `(B, 1, H, W)` form is also accepted directly.-- **A mask no longer changes the response dtype.** It is resampled *and cast* onto the response map, where the- multiplication used to promote it, so a `float16` image with a `float32` mask returned `float32` responses beside- `float16` LAFs. This also applies to `ScaleSpaceDetector`, which shares the resampling helper: a `float32` image- with a `float64` mask used to return `float64` and now returns `float32`, i.e. the image dtype, in both detectors.- `ScaleSpaceDetector` gains the same shape check, and accepts a boolean or integer mask through the same helper- (it raised on one before). It resampled a mask of any size onto its octaves without complaint, so a stale mask- from before a resize, or a transposed one, was silently stretched onto the wrong geometry, and a multi-channel- mask was broadcast over the scale levels rather than the channels -- an error when the counts differed, the wrong- weighting when they matched. Both detectors now require `(1 or B, 1, H, W)`.-- **`ScaleSpaceDetector` no longer leaks its own top-K sentinel for a batch.** For `B > 1` the per-octave top-K- ranks over the whole scale-space volume with non-candidates masked to `torch.finfo(dtype).min / 2`, and an image- with fewer maxima than requested got those sentinels back as detections: `ScaleSpaceDetector()` on- `torch.zeros(2, 1, 32, 32)` returned 70 slots per image with a response of `-1.7e38` and an arbitrary LAF, where- the same input at `B = 1` returned 500 zeros. Which slots a detection filled is now tracked through the top-K- rather than inferred from the response, and an unfilled one -- the sentinel, the padding that tops a short- result up to `num_features`, or a candidate whose frame reached outside the image -- carries a zero response and- a zero LAF, in `detect` and, after the affine-shape and orientation modules have run, in `forward`, and sorts- after every real detection, including a negative one. The mask is deliberately *not* `response == 0`: the- response function is pluggable and may be signed, so an exact zero can be a genuine maximum and keeps its frame.- The border-rejected candidate is the one visible change at `B = 1`: it used to keep its coordinates beside a- zero response, i.e. a keypoint that was never detected, and its scale was often the largest in the result. Both- detectors' `forward` read occupancy off the zero LAF, so a subclass overriding `detect` is honoured whole.-- **Half-precision input yields half-precision LAFs.** `detect_features_on_single_level` hardcoded `.float()` on the- pixel coordinates, so a `float16`/`bfloat16` image came back with `float32` LAFs beside half-precision responses.- The index-to-coordinate arithmetic runs in float32 (float64 for a float64 image) and only the finished coordinate- is cast to the input dtype; `float32` and `float64` output is unchanged. A half-precision LAF centre carries the- dtype's integer resolution: exact up to 256 in `bfloat16` and up to 2048 in `float16`, then on a 2 px grid up to- twice that, 4 px up to four times, and so on -- where the old `float32` LAFs were exact.-- **A detector model must return one spatial response map.** `detect_features_on_single_level` flattened the- whole response tensor and decoded the flat top-K index with the width alone, so a candidate from channel `c`- landed at `y + c * H`; `BlobHessian` on an RGB image put 56 of 100 LAFs outside a `64x64` frame, up to- `y = 179.9`. Merely decoding the channel would still spend the budget on duplicate LAFs -- a grayscale image- repeated into RGB returned three copies of almost every feature, whose grayscale descriptors are identical.- `MultiResolutionDetector` and `ScaleSpaceDetector` now require their detector model to emit one response channel- and fail with a named error otherwise. This does not restrict the model input: a learned detector may consume RGB- (or any other channel count) and collapse it to one response map itself, which is the intended color-image path.- Single-channel input and response output are unchanged.-- **`score_threshold` must be non-negative**, and `MultiResolutionDetector.__init__` raises `ValueError` otherwise:- non-maxima suppression writes an exact zero at every suppressed position, so a negative threshold admitted all of- them as detections (with `score_threshold=-1.0` on a `64x64` image, 70 of 100 returned features were suppressed- border pixels) and would now also be indistinguishable from the zero response that marks an unfilled slot.-- **`detect` enforces its documented `(1, C, H, W)`.** It is public, and a larger batch was flattened across the- batch axis and silently returned coordinates for the wrong image. `forward` already had that guard, so only- direct `detect` callers see a difference.-- **A short result is sorted.** `MultiResolutionDetector.detect` only ran its final top-K when the levels had- produced *more* slots than `num_features`, so a short result came back in level order with each level's own- padding left in place: with `pyramid_levels=2, up_levels=0, num_features=6000` on a `48x48` image the three real- detections sat at flat indices 0, 1 and 2304. The ranking is now unconditional, as it is in- `ScaleSpaceDetector.detect`, and the zero-response padding sorts to the end.-- **Padding is not a correspondence.** `LocalFeatureMatcher` used to describe and match every fixed-shape slot, so- `DescriptorMatcher("nn")` returned every padded origin frame and `mnn` returned one false origin match even when- neither image contained a detection. Zero LAFs are honest, but they are also identical, and identical descriptors- match each other at zero distance -- with plain nearest-neighbour matching the padded block became the largest- consistent set of "correspondences" and captured RANSAC (`SIFTFeature(400)` on two crops of one image: 0.09 px- mean reprojection error on `main`, 31 px with the zero LAFs matched, 0.09 px with them dropped). The matcher now- filters zero LAFs before matching, and skips a pair when either side has nothing left (`matcher` is an arbitrary- module with no obligation to accept a `(0, D)` input); the ratio tests `match_snn` and `match_smnn` reject the- block on their own (`match_mnn` and `match_nn` do not: identical zero descriptors are mutual nearest neighbours- at distance zero), and- `LocalFeature.forward` documents the one-line filter for a hand-rolled `match_nn` pipeline. The feature benchmark- does the same before affine/orientation/description, avoiding meaningless descriptor work and the quadratic- distance-matrix cost of padded rows; its CUDA timers also synchronize around the measured detector and full- matching regions.--* `SIFTDescriptor`, `DenseSIFTDescriptor`, `HardNet` and `HardNet8` return NaN for a constant patch in `float16`,- and the SIFT descriptors' backward is NaN in `float16` wherever two neighbouring pixels are equal.-- `F.normalize`'s default `eps` of 1e-12 is not representable in `float16` and rounds to zero, so the- `norm.clamp_min(eps)` that exists to stop a zero-norm input becoming `0 / 0` was itself zero in exactly that- dtype: an all-zero patch normalised to NaN, while `bfloat16`, `float32` and `float64` were fine. A detector that- pads a short result hands the descriptor a zero LAF, which samples one image point repeatedly and produces- exactly that patch -- `ScaleSpaceDetector(400)` on a random `64x64` `float16` image gave 365 NaN descriptor rows- -- and a NaN descriptor is worse than a meaningless one, because it propagates through `torch.cdist` and poisons- the whole matching. The nine `F.normalize` calls in those four modules now go through one helper that- normalises a `float16` input in float32 and casts back (an `eps` representable in `float16` is safe but not- neutral: a norm in the subnormal window came back as 0.5). `bfloat16`, `float32` and `float64` results are- unchanged: they keep the 1e-12 default.-- The forward pass was only half of it. `SIFTDescriptor` and `DenseSIFTDescriptor` guard `sqrt(gx^2 + gy^2 + eps)`- and `atan2(gy, gx + eps)` with `eps = 1e-10`, which is zero in `float16` -- and a squared `float16` gradient- underflows long before that -- so at every pixel with a zero gradient both sat on their singular point and the- input gradient came back NaN (9 of 4096 on ordinary random `32x32` patches). The gradient magnitude and- orientation are now computed in float32 for `float16` input and cast back, and the RootSIFT `sqrt` is computed- in float32 for `float16` as well. An *exactly* flat patch -- what a zero-LAF padding slot samples -- was the- remaining case: the guard gave every zero-gradient pixel a magnitude of `sqrt(eps)`, so a flat patch's- descriptor was a unit vector built from `eps` (float32) or a subnormal one (float16) whose `1 / norm` gradient,- together with `atan2`'s `1 / eps`, overflowed through the float16 cast into an all-NaN input gradient (and was- a meaningless ~1e8 in float32). A zero-gradient pixel now contributes a zero magnitude, a zero vector normalises- to zero with a zero gradient (the `eps` clamp's `1 / eps` was never meaningful), and- `PatchDominantGradientOrientation` skips its parabolic refinement on an empty or uniform histogram instead of- dividing `0 / 0`; a flat patch has a zero SIFT descriptor and a zero input gradient in every dtype. `bfloat16`,- whose exponent range holds both the guard and the squares, and the wider dtypes are byte-identical at every- pixel whose gradient is not exactly zero; a patch with such pixels (a saturated region) loses their `sqrt(eps)`- contribution, a change of at most `1e-5` per pixel before normalisation.+<!-- towncrier release notes start -->## :rocket: [0.6.11] - 2022-03-28### :new: New Featuresdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 883e0df24..173af3bda 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -336,6 +336,22 @@ This section provides guidance for contributing to kornia, with a focus on Pytho3. **Update Documentation**: When adding new features or changing behavior, update docstrings for public APIs. For documentation contributions, see [Contributing to Documentation](#contributing-to-documentation).+### Changelog entries++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 Quality1. **Performance Considerations**:diff --git a/changelog.d/+migration-001.added.md b/changelog.d/+migration-001.added.mdnew file mode 100644index 000000000..631e4f42c--- /dev/null+++ b/changelog.d/+migration-001.added.md@@ -0,0 +1,3 @@+Optional-dependency extra `kornia[image]` installs Pillow for PIL-backed image input/output,+display helpers and `kornia.io.sample`; missing-Pillow errors now name the extra to install, and the unused+`DinoVisionTransformer.forward_features_list` list path has been removed. (#4464)diff --git a/changelog.d/+migration-001.breaking.md b/changelog.d/+migration-001.breaking.mdnew file mode 100644index 000000000..c101ee7f7--- /dev/null+++ b/changelog.d/+migration-001.breaking.md@@ -0,0 +1,10 @@+`PatchSequential` now preserves the batch size in both padding modes. `same` preserves the input+spatial size and `valid` keeps only the complete, centred grid region. Previously, a `(2,3,8,8)`+input on a `(3,3)` grid produced `(2,3,7,7)` with `same` (now `(2,3,8,8)`) and `(2,3,8,8)` with+`valid` (now `(2,3,6,6)`). With `valid`, a `(2,3,6,8)` input on a `(4,4)` grid changed the batch+size to produce `(3,3,6,6)`; it now produces `(2,3,4,8)`. Geometric children may move temporarily+padded zeroes into the retained image. `restore_from_patches` now defaults to `self.grid_size`+instead of `(4,4)` and raises `ValueError` for a mismatched patch count instead of inferring a+different batch size or failing later in reshape. `forward_parameters` accepts both image+`(B,C,H,W)` and patch `(B,N,C,h,w)` shapes; parameter generation now covers `B*N` patch rows rather+than `B*C`, so fixed-seed outputs and RNG consumption can change. Refs #4421. (#4460)diff --git a/changelog.d/+migration-001.fixed.md b/changelog.d/+migration-001.fixed.mdnew file mode 100644index 000000000..bc661b36a--- /dev/null+++ b/changelog.d/+migration-001.fixed.md@@ -0,0 +1,2 @@+Made uncompiled `RandomGaussianIllumination` instances serializable with `pickle` and `torch.save`,+preserving parameter replay and the `compile()` execution path after restoring the module. (#4457)diff --git a/changelog.d/+migration-002.added.md b/changelog.d/+migration-002.added.mdnew file mode 100644index 000000000..349e2f7c2--- /dev/null+++ b/changelog.d/+migration-002.added.md@@ -0,0 +1,12 @@+Documented the shared 2D contract of `kornia.augmentation` β the `(B, C, H, W)` float working layout+and `keepdim`, `p` / `p_batch` / `same_on_batch`, where random parameters are drawn and how `torch.manual_seed`+and `params=` replay them, what a module serializes, and what `AugmentationSequential` does with each data key+(layouts, the inclusive `xyxy_plus` boxes and integer-centre flips, nearest masks, `extra_args`, `inverse`) β+as Convention blocks on the base classes and containers, with the canonical randomness and serialization+statements on the Conventions & Pitfalls page and executable pins. The contracts distinguish sampler and+returned-parameter placement, trainable range parameters, application-time replay exceptions, padding labels,+information lost by rotated tensor boxes, mask-list gates, mixed mask dtypes, dictionary-key exceptions,+and the transplantation constructors. Scope corrections and regression tests cover mix-specific contracts,+inverse support, mask erasing/filtering/precision, nested matrices, serialization and sampler limitations;+the container, `p_batch`,+`set_rng_device_and_dtype`, `state_dict` and `B = 0` defects are tracked in dedicated issues. (#4452)diff --git a/changelog.d/+migration-002.breaking.md b/changelog.d/+migration-002.breaking.mdnew file mode 100644index 000000000..d86cda142--- /dev/null+++ b/changelog.d/+migration-002.breaking.md@@ -0,0 +1 @@+Removed the unused `preprocess_boxes` helper, which had no public export or caller. (#4181, #4321)diff --git a/changelog.d/+migration-002.fixed.md b/changelog.d/+migration-002.fixed.mdnew file mode 100644index 000000000..d8d779aec--- /dev/null+++ b/changelog.d/+migration-002.fixed.md@@ -0,0 +1,5 @@+The `Args` blocks of `ColorJitter`, `RandomBrightness` and `RandomGaussianBlur` no longer document a+`silence_instantiation_warning` argument that none of them accepts, and `ColorJitter` now documents its+`order` argument: a fixed (sub)set of brightness/contrast/saturation/hue indices that makes the transform+`torch.compile` fullgraph-safe, with the drawn `_params["order"]` entry ignored when it is set.+(#4437, #4490)diff --git a/changelog.d/+migration-003.added.md b/changelog.d/+migration-003.added.mdnew file mode 100644index 000000000..e73092651--- /dev/null+++ b/changelog.d/+migration-003.added.md@@ -0,0 +1,2 @@+Implemented the exported Brown-Conrady, Kannala-Brandt K3, and Orthographic sensor camera models,+including distortion/projection plumbing, intrinsic matrices, and batched project/unproject support. (#4284, #4377)diff --git a/changelog.d/+migration-003.breaking.md b/changelog.d/+migration-003.breaking.mdnew file mode 100644index 000000000..b3be5049e--- /dev/null+++ b/changelog.d/+migration-003.breaking.md@@ -0,0 +1,4 @@+`kornia_rs>=0.1.14` is required; the floor used to be 0.1.9. kornia_rs 0.1.11 relocated its image I/O+and 0.1.12/0.1.13 lack the libjpeg-turbo reader, so no single call site works across 0.1.9-0.1.14;+rather than dispatch per version, kornia calls the current layout. `pip install -U kornia_rs` on an+environment that pins an older one. (#4326)diff --git a/changelog.d/+migration-003.fixed.md b/changelog.d/+migration-003.fixed.mdnew file mode 100644index 000000000..c94f9f859--- /dev/null+++ b/changelog.d/+migration-003.fixed.md@@ -0,0 +1,7 @@+`kornia.enhance.equalize`, `equalize3d`, `RandomEqualize` and `RandomEqualize3D` raise a `RuntimeError` naming+the `[0, 1]` input range for values the 256-bin lookup cannot index, instead of a raw+`index 259 is out of bounds for dimension 1 with size 256` from the gather. The check uses+`torch._assert_async`, so it adds no device sync and `torch.compile` fullgraph still works, and inputs that+equalized before (including values a hair above 1) are unchanged. The docstrings now state the range, the+256-bin histogram, and that a 3D volume of at most 255 voxels per channel comes back unchanged.+(#4431, #4432, #4489)diff --git a/changelog.d/+migration-004.added.md b/changelog.d/+migration-004.added.mdnew file mode 100644index 000000000..d9953d4e2--- /dev/null+++ b/changelog.d/+migration-004.added.md@@ -0,0 +1,4 @@+New "Camera and world conventions across the ecosystem" page cataloguing the pixel-centre, axis+and extrinsics conventions of OpenCV, COLMAP, OpenGL, ARKit, ARCore, PyTorch3D and Direct3D with the+kornia converter for each, plus the baked `align_corners` rows for the depth and undistortion warps on+the Conventions & Pitfalls page. (#4315)diff --git a/changelog.d/+migration-004.breaking.md b/changelog.d/+migration-004.breaking.mdnew file mode 100644index 000000000..a0671dae9--- /dev/null+++ b/changelog.d/+migration-004.breaking.md@@ -0,0 +1,8 @@+`kornia.contrib.BoxMotTracker` is removed, together with the `kornia.contrib.boxmot_tracker` module.+It wrapped the [boxmot](https://github.com/mikel-brostrom/boxmot) tracker zoo around a kornia detector,+but called the boxmot 10.x API (`boxmot.DeepOCSORT(model_weights=..., device=..., fp16=...)`), and no+boxmot release that installs alongside the torch versions kornia supports (`torch>=2.5.1`) provides+it, so the class could not be instantiated on any supported stack (see+[#4320](https://github.com/kornia/kornia/issues/4320)). Track with boxmot directly, feeding it the+output of a kornia detector such as `RTDETRDetectorBuilder`. `kornia.core.external.boxmot` is gone+with it. (#4301)diff --git a/changelog.d/+migration-004.fixed.md b/changelog.d/+migration-004.fixed.mdnew file mode 100644index 000000000..4ba9dd585--- /dev/null+++ b/changelog.d/+migration-004.fixed.md@@ -0,0 +1,5 @@+`kornia.contrib.diamond_square` generates fractals with a spatial side below 3 px. A 1 px side raised+`ValueError: math domain error` and a 2 px side a `TypeError` from a float in the `torch.rand` size, so+`RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow` failed on such images. A small+side is now drawn on the 3 px grid and sliced; outputs for sides of 3 px and more are bit-identical.+(#4472, #4488)diff --git a/changelog.d/+migration-005.added.md b/changelog.d/+migration-005.added.mdnew file mode 100644index 000000000..879a47f7e--- /dev/null+++ b/changelog.d/+migration-005.added.md@@ -0,0 +1,5 @@+Documented the `kornia.sensors.camera` conventions (`Vector`-typed inputs, the per-model `params`+layout, the shared half-pixel `scale` rule, and the pinhole mapping shared with `kornia.geometry.camera`,+including its camera-axis broadcasting, projection rounding and zero/near-zero depth differences) and+added executable pins, with the unimplemented models tracked in a dedicated issue; the three non-pinhole+models now appear on the sensors documentation page. (#4318)diff --git a/changelog.d/+migration-005.breaking.md b/changelog.d/+migration-005.breaking.mdnew file mode 100644index 000000000..7cf2a1402--- /dev/null+++ b/changelog.d/+migration-005.breaking.md@@ -0,0 +1,13 @@+`SegmentationModelsBuilder.build()` no longer imports `segmentation_models_pytorch` (smp). It used+to take `model_name`, `encoder_name`, `encoder_weights`, `in_channels`, `classes`, `activation` and+`**kwargs`, import smp lazily, instantiate the smp architecture and look up the encoder's+preprocessing parameters itself. It now takes a constructed `nn.Module` and the encoder's+preprocessing-parameter dictionary (`build(model, preproc_params=None, name="segmentation_model")`),+where `preproc_params` is what `smp.encoders.get_preprocessing_params(encoder_name)` returns; build+the smp network and fetch its parameters yourself. Kornia no longer imports smp anywhere, and+`kornia.core.external.segmentation_models_pytorch` is gone. `SemanticSegmentation` gained the+`__init__(model, pre_processor, post_processor, name=None)` its siblings have, so the container the+builder returns can be instantiated (it was abstract before). The `input_range: [0, 255]`+preprocessing step is now `kornia.enhance.Rescale(255.0)`, a multiply by 255, instead of a+`Normalize` by a stored `1/255`: bfloat16 rounds that reciprocal to a ~254.0 multiplier (0.5 mapped+to 127.0 instead of 127.5), and float32 outputs of that step move by at most one ulp. (#4301)diff --git a/changelog.d/+migration-005.fixed.md b/changelog.d/+migration-005.fixed.mdnew file mode 100644index 000000000..9d26ba7bd--- /dev/null+++ b/changelog.d/+migration-005.fixed.md@@ -0,0 +1,5 @@+`RandomBoxBlur`'s `normalized` argument is documented as what it does. It was described as "if True, L1 norm+of the kernel is set to 1", but it was forwarded positionally into `kornia.filters.box_blur`'s `separable`+parameter: it chooses between the separable and the single 2D pass, and the kernel is L1-normalized either+way, so `normalized=False` returns window means, not sums. The call now passes `border_type` and+`separable` by keyword; outputs are unchanged. (#4433, #4486)diff --git a/changelog.d/+migration-006.added.md b/changelog.d/+migration-006.added.mdnew file mode 100644index 000000000..d29d05a17--- /dev/null+++ b/changelog.d/+migration-006.added.md@@ -0,0 +1,5 @@+Documented depth and stereo conventions (the two meanings of depth, the `(B, 3, H, W)` versus+`(B, H, W, 3)` layouts, the opposite source/destination naming of `warp_frame_depth` and+`DepthWarper`, the rectified stereo `Q` matrix) and added executable pins for `kornia.geometry.depth`+and `StereoCamera`, including dtype promotion, extra-axis broadcasting, subpixel border sampling,+and singular stereo reprojection. Remaining defects are tracked in dedicated issues. (#4317)diff --git a/changelog.d/+migration-006.breaking.md b/changelog.d/+migration-006.breaking.mdnew file mode 100644index 000000000..a39a9ea0f--- /dev/null+++ b/changelog.d/+migration-006.breaking.md@@ -0,0 +1,4 @@+`kornia.core.external.transformers` was removed; it was a `LazyLoader` handle no kornia code used.+Previously `from kornia.core.external import transformers` gave a lazy proxy that imported+`transformers` on first attribute access; that name no longer exists, so import `transformers`+directly instead. (#4301)diff --git a/changelog.d/+migration-006.fixed.md b/changelog.d/+migration-006.fixed.mdnew file mode 100644index 000000000..2d8f9d84b--- /dev/null+++ b/changelog.d/+migration-006.fixed.md@@ -0,0 +1,3 @@+`So3.exp`, `So3.log`, `Se3.exp`, `Se3.log` and `Se2.exp` return finite gradients at the identity,+and `So3.log` also at a half turn, instead of `nan` on every dtype. The forward values are unchanged;+`torch.where` was differentiating the singular branch it does not select. (#4405)diff --git a/changelog.d/+migration-007.added.md b/changelog.d/+migration-007.added.mdnew file mode 100644index 000000000..c4f51a198--- /dev/null+++ b/changelog.d/+migration-007.added.md@@ -0,0 +1,4 @@+Documented camera distortion and calibration conventions (normalized versus pixel inputs, the+coefficient layout, the `new_K`/`K` roles, the iterative inverses) and added executable pins for+`kornia.geometry.camera`'s distortion models and `kornia.geometry.calibration`, with the+tilt-projection, Kannala-Brandt Jacobian and float16 defects tracked in dedicated issues. (#4312)diff --git a/changelog.d/+migration-007.breaking.md b/changelog.d/+migration-007.breaking.mdnew file mode 100644index 000000000..22db55836--- /dev/null+++ b/changelog.d/+migration-007.breaking.md@@ -0,0 +1,8 @@+`KimiVLBuilder.from_pretrained_hf()` and `SigLip2Builder.from_pretrained_hf()` cache their+checkpoint where every other kornia checkpoint lives. `cache_dir=None` used to mean the HuggingFace+cache (`~/.cache/huggingface/hub/models--<owner>--<name>/snapshots/<sha>/model.safetensors`) and now+means torch's hub directory (`<torch hub dir>/checkpoints/<owner>--<name>--model.safetensors`); an+explicit `cache_dir` used to hold the same `models--<owner>--<name>/β¦` tree and now holds the flat+`<owner>--<name>--model.safetensors` file. Either way the first `from_pretrained_hf()` call after+upgrading re-downloads the checkpoint (854 MB for KimiVL, ~1.5 GB for SigLIP2) even for users who+already had it. (#4293)diff --git a/changelog.d/+migration-007.fixed.md b/changelog.d/+migration-007.fixed.mdnew file mode 100644index 000000000..6b942591b--- /dev/null+++ b/changelog.d/+migration-007.fixed.md@@ -0,0 +1,3 @@+`ycbcr_to_rgb` now uses the exact inverse of the `rgb_to_ycbcr` coefficients, so an+`rgb -> ycbcr -> rgb` round trip is lossless to floating-point precision instead of drifting+by ~2.7e-4. The forward transform is unchanged. (#4378)diff --git a/changelog.d/+migration-008.added.md b/changelog.d/+migration-008.added.mdnew file mode 100644index 000000000..5c340e317--- /dev/null+++ b/changelog.d/+migration-008.added.md@@ -0,0 +1,4 @@+Documented camera projection-core conventions (`PinholeCamera` frames, integer pixel centres, the two+meanings of depth, the `z = 0` policies) and added executable pins for `kornia.geometry.camera`'s+projection core, with the known scale-rule, aliasing, guard and legacy-API limitations tracked in+dedicated issues. (#4294)diff --git a/changelog.d/+migration-008.breaking.md b/changelog.d/+migration-008.breaking.mdnew file mode 100644index 000000000..25b998451--- /dev/null+++ b/changelog.d/+migration-008.breaking.md@@ -0,0 +1,10 @@+Non-maxima suppression applies one border rule at every window size. `NonMaximaSuppression2d` /+`nms2d` with a window larger than `(7, 7)`, and `NonMaximaSuppression3d` / `nms3d`, no longer report+maxima inside the `(k - 1) // 2` border strip. Previously the general path replicate-padded its input,+so a position whose window ran off an edge was judged against duplicated copies of the edge values,+which both fabricated plateaus that suppressed genuine maxima and hid genuine neighbours that should+have suppressed spurious ones; the `(3, 3)`, `(5, 5)` and `(7, 7)` paths meanwhile rejected the strip+outright, so the two disagreed about the same pixel. The explicit paths' rule is now the rule+everywhere. Every kornia detector already rejects that strip -- ALIKED by hand after calling `nms2d`,+DISK and XFeat by using `k = 5`, `MultiResolutionDetector` by zeroing 15 px before the call -- so no+detector output changes. (#4239, #4242)diff --git a/changelog.d/+migration-008.fixed.md b/changelog.d/+migration-008.fixed.mdnew file mode 100644index 000000000..d5ea2bbb4--- /dev/null+++ b/changelog.d/+migration-008.fixed.md@@ -0,0 +1,4 @@+`bbox_to_mask3d` now preserves the input dtype in the returned mask, matching `bbox_to_mask`+and the `Boxes3D.to_mask` contract: the earlier implementation downcast every result to+`float32`, so a `float64` or half-precision box produced a mask that silently lost precision.+The mask keeps the input box's dtype end to end. (#4376)diff --git a/changelog.d/+migration-009.added.md b/changelog.d/+migration-009.added.mdnew file mode 100644index 000000000..3346a8f8a--- /dev/null+++ b/changelog.d/+migration-009.added.md@@ -0,0 +1,5 @@+API reference entries now carry a **Try in browser** badge that links a function, its+`nn.Module` counterpart or a browser model to its interactive page on the kornia.org+playground, so readers can run the operator on a sample image without installing anything.+The set of linked APIs is a snapshot of the playground in `docs/source/_playground_links.json`,+refreshed by `docs/generate_playground_links.py`. (#4333)diff --git a/changelog.d/+migration-009.breaking.md b/changelog.d/+migration-009.breaking.mdnew file mode 100644index 000000000..1274e19ba--- /dev/null+++ b/changelog.d/+migration-009.breaking.md@@ -0,0 +1,3 @@+`nms2d(x, (1, 1))` and `nms3d(x, (1, 1, 1))` return `x` unchanged. A unit window has no neighbours,+so nothing can be suppressed; the old 2-D result was an artifact of the zeroed centre tap of the+convolution kernel summing to `0.0`, while the old 3-D path raised because of #4241. (#4242)diff --git a/changelog.d/+migration-009.fixed.md b/changelog.d/+migration-009.fixed.mdnew file mode 100644index 000000000..abb2c9220--- /dev/null+++ b/changelog.d/+migration-009.fixed.md@@ -0,0 +1 @@+Fixed `RandomPlasmaBrightness`, `RandomPlasmaContrast`, and `RandomPlasmaShadow` to replay deterministically from stored `params=`. (#4462)diff --git a/changelog.d/+migration-010.added.md b/changelog.d/+migration-010.added.mdnew file mode 100644index 000000000..c0460c78b--- /dev/null+++ b/changelog.d/+migration-010.added.md@@ -0,0 +1,4 @@+Optional-dependency extras `kornia[onnx]` and `kornia[sd]` declare the third-party packages that+the ONNX and Stable-Diffusion-dissolving wrappers lazily import, and are documented on the+installation page. Missing-dependency errors now name the extra to install, and `dev` no longer+pulls `diffusers` and `transformers`. (#4301)diff --git a/changelog.d/+migration-010.breaking.md b/changelog.d/+migration-010.breaking.mdnew file mode 100644index 000000000..e8ff24a81--- /dev/null+++ b/changelog.d/+migration-010.breaking.md@@ -0,0 +1,5 @@+Kornia's minimum supported PyTorch version rises to 2.5.1. Previously the declared floor was+2.0.0; PR-time CI has only ever exercised 2.5.1 and newer, and this same change retires the+scheduled-CI legs that tested anything older.+Installing kornia now requires `torch>=2.5.1`; a `torch` install below that version no longer+satisfies the dependency, and `pip`/`uv` will refuse to resolve it. (#4197)diff --git a/changelog.d/+migration-010.fixed.md b/changelog.d/+migration-010.fixed.mdnew file mode 100644index 000000000..63afec009--- /dev/null+++ b/changelog.d/+migration-010.fixed.md@@ -0,0 +1,3 @@+`ManyToManyAugmentationDispather` now rejects mismatched numbers of input bundles and+augmentations before applying any transformation, instead of silently dropping surplus inputs+or skipping augmentations. (#4461)diff --git a/changelog.d/+migration-011.added.md b/changelog.d/+migration-011.added.mdnew file mode 100644index 000000000..b1d3f85f0--- /dev/null+++ b/changelog.d/+migration-011.added.md@@ -0,0 +1,7 @@+KimiVL and SigLIP2 builders load their safetensors checkpoints with kornia's own downloader+(`kornia.core.download_hf_file`/`download_file_from_url`, which share the retrying, rate-limit-aware+cache every other checkpoint uses) and a pure-torch reader (`kornia.core.load_safetensors`);+`huggingface_hub` and `safetensors` are no longer needed. Both were imported without ever being+declared as dependencies, so `KimiVLBuilder.from_pretrained_hf()` and+`SigLip2Builder.from_pretrained_hf()` used to raise `ImportError` on a plain `pip install kornia`.+The checkpoints move to torch's hub cache as a result; see *Breaking changes*. (#4293)diff --git a/changelog.d/+migration-011.breaking.md b/changelog.d/+migration-011.breaking.mdnew file mode 100644index 000000000..79fb52533--- /dev/null+++ b/changelog.d/+migration-011.breaking.md@@ -0,0 +1,11 @@+Removed `kornia.to_tensorflow()`, `kornia.to_jax()` and `kornia.to_numpy()`, along with the+multi-framework-support advertising in the README and the docs landing page. These functions used+to lazily transpile the library to TensorFlow, JAX or NumPy through the third-party `ivy` package+(an optional `dev`/`docs` dependency, now also removed). Testing in September 2026 found the+integration unreliable across all three targets β a checkout-path crash in Ivy's module walker, a+torch/triton segfault when `transformers` is also installed, an undocumented `flax` requirement for+JAX, and a `jaxlib`/`numpy` API-compatibility break β against Ivy's latest release (1.0.0.5, June+2025), with the upstream project showing little ongoing maintenance. Reaching for any of the three+functions, at the top level or under `kornia.transpiler`, now raises an `AttributeError` that says+what was removed and links the page below, rather than a bare "has no attribute". See+`get-started/multi-framework-support` for what was tested and why. (#4196)diff --git a/changelog.d/+migration-011.fixed.md b/changelog.d/+migration-011.fixed.mdnew file mode 100644index 000000000..12a915b21--- /dev/null+++ b/changelog.d/+migration-011.fixed.md@@ -0,0 +1,3 @@+`PatchSequential` now augments every patch of every image and runs the complete selected sequence.+The padding, reconstruction and parameter-generation behaviour changes are listed under+*Breaking changes*. Refs #4421. (#4460)diff --git a/changelog.d/+migration-012.added.md b/changelog.d/+migration-012.added.mdnew file mode 100644index 000000000..c7457a5dd--- /dev/null+++ b/changelog.d/+migration-012.added.md@@ -0,0 +1 @@+`kornia.models.RRDBNet`, a vendored Real-ESRGAN generator; `RRDBNetBuilder` no longer needs `basicsr`. (#4292)diff --git a/changelog.d/+migration-012.breaking.md b/changelog.d/+migration-012.breaking.mdnew file mode 100644index 000000000..5aab3961f--- /dev/null+++ b/changelog.d/+migration-012.breaking.md@@ -0,0 +1,36 @@+`extract_patches_from_pyramid` now samples ordinary-sized inputs once from a packed pyramid atlas instead of+sampling every LAF at every pyramid level. A statically selected levelwise fallback keeps atlases larger than+128 MiB from becoming a memory hazard. LAFs whose nominal level is coarser than the last usable pyramid level now+sample that actual coarsest level; they previously returned an all-zero patch. For `float16` and `bfloat16` inputs+the whole pyramid -- padding, `pyrdown`, coordinate arithmetic and sampling -- runs in `float32` and the patches+are cast back, on every device: this avoids the normalized-coordinate precision loss caused by the wider atlas,+keeps the extraction off `replication_pad2d`/`grid_sampler_2d` kernels that old torch builds lack for half dtypes+on the CPU (torch <= 2.5.1 would otherwise crash), and avoids recasting the full atlas on every sampling chunk.+`extract_patches_simple` computes its sampling grid in `float32` for reduced-precision inputs on every device for+the same reason -- its output matches the pyramid extractor's level-0 output again. Half-precision patches+therefore change on CUDA and MPS as well as the CPU, and floating-point results are not byte-identical to the+former levelwise implementation.+The universal `float32` sampling is a real cost where the native half kernels were fine: on CUDA, `float16`+`extract_patches_simple` is roughly 2x slower at high N, and peak CUDA memory rises at moderate N (the atlas plus+the one-time upcast copy) even though the high-N peaks drop.+Both extractors now reject an image/LAF batch-size mismatch at the boundary with a clear error: former releases+raised an internal `grid_sample` error for most batch mixes, except a smaller LAF batch, where both extractors+silently returned patches for only the first `min(B_img, B_laf)` images. A LAF on another device is moved once to+the image, while a different LAF dtype is promoted with the image dtype for grid arithmetic rather than rejected or+rounded down; this preserves mixed-precision autocast pipelines and subpixel LAF coordinates. Patches still return+with the image's dtype and device. Both extractors chunk their sampling along N, in the spirit of `batched_forward`, so+the folded `(B, N*PS, PS, 2)` grid and channel-scaled sampled chunk each stay within a fixed 64 MiB budget (remap+intermediates can still make the total peak a multiple of that). Batched high-N extraction now peaks below even the+pre-batching per-image loop (468 MiB+against 495 MiB on `main` for B=8,+N=4000, PS=32 on a 512x512 float32 image, where the unchunked atlas peaked at 1.24 GiB), eager throughput stays+within ~5% of the unchunked atlas, and float32/float64 patches are bitwise identical to it; a `torch.compile`d+call whose grid exceeds the budget splits into several `grid_sample` calls (~1.5x the unbounded atlas latency at+B=8, N=2000 on CPU inductor, still ~10x faster than the per-level loop it replaces). Both extractors return an+empty `(B, N, CH, PS, PS)` tensor for `B == 0` or `N == 0` instead of raising from inside `affine_grid` --+`extract_patches_from_pyramid` with `B == 0` returned the empty result before the batched rewrite described under **Bug fixes**+regressed it; every other empty combination raised on all prior releases. `extract_patches_from_pyramid` now+also accepts a LAF on a different device than the image, as `extract_patches_simple` always has, and returns+patches on the image's device; both extractors move the LAF to the image's device up front, so a cross-device+call now samples on the image's device and matches the same-device result (`extract_patches_simple` previously+built the full sampling grid on the LAF's device).diff --git a/changelog.d/+migration-012.fixed.md b/changelog.d/+migration-012.fixed.mdnew file mode 100644index 000000000..1c560a241--- /dev/null+++ b/changelog.d/+migration-012.fixed.md@@ -0,0 +1,3 @@+`RandomMosaic` now preserves `(H, W)` for non-square inputs when `output_size=None`; it previously+returned `(W, H)`. `start_ratio_range` now scales x by width and y by height; it previously scaled+x by height and y by width. (#4459)diff --git a/changelog.d/+migration-013.added.md b/changelog.d/+migration-013.added.mdnew file mode 100644index 000000000..b2f5eb3f0--- /dev/null+++ b/changelog.d/+migration-013.added.md@@ -0,0 +1,3 @@+Repeatable Oxford affine local-feature benchmarks for SIFT, SIFT-AffNet-HardNet, and+KeyNet-HardNet, with eager/compiled median/IQR speed, homography corner error, and JSON output;+historical scale-space SIFT CPU/CUDA batch-runtime comparisons and plotting. (#4254)diff --git a/changelog.d/+migration-013.breaking.md b/changelog.d/+migration-013.breaking.mdnew file mode 100644index 000000000..2aa342b3c--- /dev/null+++ b/changelog.d/+migration-013.breaking.md@@ -0,0 +1,5 @@+`AUTUMN` is dropped from `kornia.color.__all__` (#4143). The class was deprecated in 0.7.2 in favour of+`ColorMap(base='autumn')` and removed by #3432, which left the `__all__` entry behind. Since that removal+`from kornia.color import AUTUMN` has raised `AttributeError` and `from kornia.color import *` has failed on+it, so nothing that works today stops working β the entry named a binding that no longer existed. Callers+still reaching for the class should use `ColorMap(base='autumn')`.diff --git a/changelog.d/+migration-013.fixed.md b/changelog.d/+migration-013.fixed.mdnew file mode 100644index 000000000..707aee729--- /dev/null+++ b/changelog.d/+migration-013.fixed.md@@ -0,0 +1,2 @@+`RandomThinPlateSpline(scale=0.0)` now generates zero control-point displacement instead of+raising an error when constructing a degenerate uniform distribution. (#4463)diff --git a/changelog.d/+migration-014.added.md b/changelog.d/+migration-014.added.mdnew file mode 100644index 000000000..3a2d3468b--- /dev/null+++ b/changelog.d/+migration-014.added.md@@ -0,0 +1,2 @@+Documented bbox/Boxes geometry-operation conventions and added executable pins for transforms,+NMS, padding, clipping, and area filtering, including known unbatched-input limitations. (#4245)diff --git a/changelog.d/+migration-014.breaking.md b/changelog.d/+migration-014.breaking.mdnew file mode 100644index 000000000..9f5f71215--- /dev/null+++ b/changelog.d/+migration-014.breaking.md@@ -0,0 +1,12 @@+The shape guards of `normalize_homography` and `denormalize_homography` now reject everything but a+`(3, 3)`/`(B, 3, 3)` matrix, and `normalize_homography3d`'s everything but a `(4, 4)`/`(B, 4, 4)` one (#3999).+A rank-4 input used to pass the guard and come back with its rank unchanged β+`normalize_homography(eye(3).expand(2, 4, 3, 3), (4, 5), (8, 9))` returned a `(2, 4, 3, 3)` matrix and now raises+`ValueError`. A wrong-sized input, such as a `(B, 4, 4)` to the 2-D functions, used to pass the guard and fail+later inside `matmul`; it now raises at the guard, and `normalize_homography3d`'s message names `Bx4x4` instead of+`Bx3x3`. Unbatched `(3, 3)`/`(4, 4)` matrices are still accepted and still promoted to a leading batch of 1.++One side effect reaches tracing callers: the rewritten guard evaluates its shape comparison unconditionally, where+the old `or`-form short-circuited past it for a rank-3 input, so `torch.jit.trace` of any of the three functions+now emits a `TracerWarning` about converting a tensor to a Python boolean that it did not emit before. The guard+is a static check and the traced graph is unchanged β the warning is noise, not a correctness signal.diff --git a/changelog.d/+migration-014.fixed.md b/changelog.d/+migration-014.fixed.mdnew file mode 100644index 000000000..57cd8f3ca--- /dev/null+++ b/changelog.d/+migration-014.fixed.md@@ -0,0 +1,2 @@+`unproject_meshgrid` now requires camera intrinsics of shape `(B, 3, 3)`, rejecting extra+camera axes before they can broadcast across pixel columns and reporting the caller's original shape. (#4383)diff --git a/changelog.d/+migration-015.added.md b/changelog.d/+migration-015.added.mdnew file mode 100644index 000000000..b724e90e1--- /dev/null+++ b/changelog.d/+migration-015.added.md@@ -0,0 +1,2 @@+Documentation pages now provide search-specific titles and descriptions, canonical tutorial links, and a+canonicalized redirect from the retired highlighted-features page. (#4226)diff --git a/changelog.d/+migration-015.breaking.md b/changelog.d/+migration-015.breaking.mdnew file mode 100644index 000000000..deb98e3a6--- /dev/null+++ b/changelog.d/+migration-015.breaking.md@@ -0,0 +1,22 @@+`MultiResolutionDetector` and `KeyNetDetector` change their output: padded slots now read as a zero response and+a zero LAF instead of `torch.finfo(dtype).min / 2` and an arbitrary border coordinate; the previously inert `mask`+argument now suppresses detections, and must be `(1 or B, 1, H, W)` at the image size -- a `(B, H, W)` mask+passed directly to either detector, which was accepted only because it went unread, is rejected; half-precision+input yields half-precision LAFs; the returned shape is always `num_features`; a multi-channel response is rejected instead of+producing invalid or duplicate LAFs; a negative `score_threshold` is rejected with `ValueError`; and `detect`+enforces its documented `(1, C, H, W)` input. The `mask` of both detectors is now "where a detection may be": a+boolean or integer mask is binary (a 0/255 mask no longer scales the responses by 255), a floating-point mask+weights the scores, it is resampled conservatively so a thin zero region survives the coarse levels, and it is+applied to the non-maxima-suppression output, so its edge cannot manufacture maxima (#4102). A mask whose dtype+differs from the image no longer promotes the response dtype, and a mask that is not `(1 or B, 1, H, W)` for the+image is rejected instead of stretched or broadcast onto the wrong axis -- that includes an image-shaped+`(1, C, H, W)` mask and a coarse `(N, H/8, W/8)` one, which `LocalFeatureMatcher` used to accept and silently+ignore (the old docstring said "same shape as the input image") and now forwards to the detector's check.+`ScaleSpaceDetector` additionally stops returning its own top-K sentinel as a detection for a batch, no longer+returns a frame for a candidate its border check rejected, and re-checks a sub-pixel-refined centre against the+mask; a short result is sorted in both detectors. `detect_features_on_single_level`'s new `mask` parameter is+keyword-only, and it now requires the response map to have the level's spatial size: a valid-convolution+response net that returned a smaller map had every keypoint decoded one pixel off its peak, since a response+index is read as a level pixel with no offset, and is rejected with a message rather than silently misplaced.+See the entry under **Bug fixes** (#4089, #4090, #4091) for the details and the+migration.diff --git a/changelog.d/+migration-015.fixed.md b/changelog.d/+migration-015.fixed.mdnew file mode 100644index 000000000..894c972ee--- /dev/null+++ b/changelog.d/+migration-015.fixed.md@@ -0,0 +1,2 @@+Correct non-zero sensor tilt in `tilt_projection` and `distort_points` to match OpenCV,+restoring forward/inverse round trips and correcting `undistort_image` sampling. (#4384)diff --git a/changelog.d/+migration-016.added.md b/changelog.d/+migration-016.added.mdnew file mode 100644index 000000000..a239a7f81--- /dev/null+++ b/changelog.d/+migration-016.added.md@@ -0,0 +1,7 @@+`kornia.feature.laf_is_filled(laf)` returns the `(B, N)` mask of the slots a detection filled, the complement+of a detector's zero-LAF padding. Fixed-shape detectors pad the slots no detection filled with an all-zero LAF,+and those slots must be dropped before matching -- their descriptors are identical to one another, so they match+each other at zero distance and a mutual nearest-neighbour test does not reject them. `LocalFeature.forward`'s+docstring already required callers of a hand-rolled pipeline to do this and gave them the expression to copy;+they can now call the function instead. It replaces the same expression at four internal sites in+`kornia/feature`. (#4223)diff --git a/changelog.d/+migration-016.breaking.md b/changelog.d/+migration-016.breaking.mdnew file mode 100644index 000000000..b3c85ad64--- /dev/null+++ b/changelog.d/+migration-016.breaking.md@@ -0,0 +1,9 @@+`MKDDescriptor` runs in `float16` and `bfloat16`. Its gradient-embedding and spatial-encoding stages were held in+a plain `dict`, so `.to(device, dtype)` never reached their buffers and a half-precision input failed at the+whitening matmul with `expected m1 and m2 to have the same dtype`. They are now an `nn.ModuleDict`; float32 and+float64 outputs are byte-identical, and `state_dict()` gains the stages' buffer keys (`feats.<parametrization>.*`).+A state dict saved by an earlier release still loads with `strict=True`: those buffers are derived from the+constructor arguments, and when a state dict has no `feats.*` key at all they are filled in from the module being+loaded into (one that has some and lost one is reported by `strict=True`, as for any other missing key). The+reverse is not covered: a state dict saved by this release carries the `feats.*` keys and fails `strict=True` on+an earlier kornia, which does not know them; load it with `strict=False` there.diff --git a/changelog.d/+migration-016.fixed.md b/changelog.d/+migration-016.fixed.mdnew file mode 100644index 000000000..2e470d8ef--- /dev/null+++ b/changelog.d/+migration-016.fixed.md@@ -0,0 +1,14 @@+`reproject_disparity_to_3D` (the `StereoCamera` method and the module-level function, which share+one body) no longer transposes the two pixel indices. The pixel meshgrid was unbound as+`v, u = torch.unbind(uv, dim=-1)`, but `create_meshgrid(normalized_coordinates=False)` returns+`(x, y)`, so the column fed `v` and the row fed `u`: `X` was computed from the row and `Y` from+the column. Every returned point was the value belonging to its transposed pixel -- kornia's+answer at `(row, col)` was what `cv2.reprojectImageTo3D` puts at `(col, row)`, the OpenCV+semantics this function was added to provide (#2042). A square rig with `fx == fy` and+`cx == cy` agrees only on the diagonal, so the error was silent rather than absent. Output+changes at every pixel with `row != col`, square inputs included. The real-data regression+fixture stored ten points as ten rows of one column while its own comment and its ground truth+describe one row of ten columns,+which is why it passed against the swapped code; it is now laid out as the comment says, and+the fixed code reproduces the unchanged ground-truth values. #4317's two wart pins for this defect+are retired and its strict-xfail convention test is now an ordinary passing regression. (#4269, #4366)diff --git a/changelog.d/+migration-017.added.md b/changelog.d/+migration-017.added.mdnew file mode 100644index 000000000..1a1db4841--- /dev/null+++ b/changelog.d/+migration-017.added.md@@ -0,0 +1,10 @@+`benchmarks/feature/laf_ops.py` microbenchmarks seven public LAF operations+(`laf_from_center_scale_ori`, `make_upright`, `ellipse_to_laf`, `laf_to_boundary_points`,+`laf_is_inside_image`, `extract_patches_simple`, `extract_patches_from_pyramid`) as kornia eager vs+`torch.compile`, and its CPU and CUDA runs are the first committed non-Apple result set, so the docs+performance page now shows CUDA numbers. The page labels its throughput column from a new optional+`units` metadata key (`LAFs/s` here, `items/s` when absent) and identifies a row by every config field+that varies within a result file rather than by `(op, batch)` alone, which a suite sweeping a second+axis at a fixed batch would otherwise collapse onto one row. `run_batch_sweep` gained `label_fn`,+`items_fn` and `units` so such a suite can use the shared sweep; the existing callers are unchanged.+(#4119)diff --git a/changelog.d/+migration-017.breaking.md b/changelog.d/+migration-017.breaking.mdnew file mode 100644index 000000000..a7156b249--- /dev/null+++ b/changelog.d/+migration-017.breaking.md@@ -0,0 +1,11 @@+`DescriptorMatcherWithSteerer(normalize=True)`, `DiscreteSteerer.steer_descriptions(normalize=True)` and the+`MKD` descriptors, like `SIFTDescriptor` and `HardNet`, L2-normalise a float16 input in float32 and cast back,+so an all-zero float16 descriptor normalises to zero instead of NaN (the 1e-12 guard underflows in float16) and a+descriptor whose norm sits below the smallest float16 normal still normalises to one rather than being clamped.+`PatchDominantGradientOrientation`, and with it `LAFOrienter`, take the gradient magnitude and orientation of a+float16 patch through the same float32 step `SIFTDescriptor` uses, so a flat patch yields a finite angle instead+of a NaN LAF -- which reached a *filled* detection slot in a float16 `SIFTFeature` pipeline and poisoned that+descriptor row. `SIFTDescriptor(rootsift=True)` and `DenseSIFTDescriptor(rootsift=True)`+compute the RootSIFT square root in float32 for a float16 input: the float16-representable guard would have+read every empty bin as `sqrt(6.1e-5)` and biased the descriptor norm to ~1.004. Float32 and float64 outputs are+unchanged.diff --git a/changelog.d/+migration-017.fixed.md b/changelog.d/+migration-017.fixed.mdnew file mode 100644index 000000000..4d13086b6--- /dev/null+++ b/changelog.d/+migration-017.fixed.md@@ -0,0 +1 @@+`RandomRain` with `same_on_batch=True` now samples the same number of rain drops for all samples in the batch. (#4453)diff --git a/changelog.d/+migration-018.added.md b/changelog.d/+migration-018.added.mdnew file mode 100644index 000000000..3cb718ad6--- /dev/null+++ b/changelog.d/+migration-018.added.md@@ -0,0 +1,2 @@+Linux CPU half-precision CI now uses explicit reproducible profiles, exact phase/exception manifests, complete+lifecycle verification, and guarded candidate-only baseline regeneration. (#4154)diff --git a/changelog.d/+migration-018.breaking.md b/changelog.d/+migration-018.breaking.mdnew file mode 100644index 000000000..bf8a00b61--- /dev/null+++ b/changelog.d/+migration-018.breaking.md@@ -0,0 +1,7 @@+`LocalFeatureMatcher` no longer matches the zero-LAF slots with which a fixed-shape detector pads an under-filled+result, and now forwards its documented `mask0`/`mask1` inputs to feature extraction. `nn` and `mnn` callers can+therefore receive fewer correspondences: identical descriptors sampled at padded origin frames are no longer+reported as matches. Three-dimensional `(B, H, W)` masks keep working and are promoted to the detectors'+`(B, 1, H, W)` form; four-dimensional masks are forwarded unchanged. Because the masks now reach the detector,+they are subject to its check: a mask that is not at the image's spatial size, which used to be ignored, is+rejected. A floating-point mask changes meaning in `ScaleSpaceDetector`-based pipelines too; see the mask semantics entry under **Bug fixes**.diff --git a/changelog.d/+migration-018.fixed.md b/changelog.d/+migration-018.fixed.mdnew file mode 100644index 000000000..8020e0459--- /dev/null+++ b/changelog.d/+migration-018.fixed.md@@ -0,0 +1,3 @@+`RandomRain` now rejects drop heights equal to the image height and absolute drop widths equal to the image+width with the documented validation error, instead of allowing boundary-sized drops to reach an internal+`IndexError`. (#4451)diff --git a/changelog.d/+migration-019.added.md b/changelog.d/+migration-019.added.mdnew file mode 100644index 000000000..8c1c3e5f9--- /dev/null+++ b/changelog.d/+migration-019.added.md@@ -0,0 +1,7 @@+The documentation site was rebuilt on `pydata-sphinx-theme` with a top navigation bar+(Learn / API / Models plus Ecosystem, About and Support menus), a redesigned landing page, a+restructured API reference with per-topic subpages, and a long list of fixed doc examples and+removed dead interactive demos. Old deep links into the split module pages+(e.g. `augmentation.module.html#kornia.augmentation.RandomAffine`) are forwarded to the subpage+that now documents the object, so existing links keep resolving. The furo layout stayed available+behind `KORNIA_DOCS_THEME=furo` until #4304 removed that fallback. (#4155)diff --git a/changelog.d/+migration-019.breaking.md b/changelog.d/+migration-019.breaking.mdnew file mode 100644index 000000000..7dd4287ad--- /dev/null+++ b/changelog.d/+migration-019.breaking.md@@ -0,0 +1,13 @@+`ellipse_to_laf` no longer raises on a degenerate ellipse. One whose `a` or `c` is `0` after rounding to the input+dtype makes the matrix being inverted singular; the batched `torch.inverse` it now replaces (see **Bug fixes**) failed the+whole call with `linalg.LinAlgError`, and the closed form returns non-finite values in that LAF instead, leaving+the other rows of the batch usable. Callers that relied on the exception to reject bad input -- reading+Oxford-format `.ellipse` files, say -- should test the result with `kornia.feature.laf_is_valid`, since an invalid+LAF otherwise propagates silently through `get_laf_scale` and into matching. Detecting the degenerate rows up front+would cost a device synchronisation and the `fullgraph=True` capture, so it is left to the caller. The in-repo+affine estimators handle invalid candidates before nonlinear LAF operations. `PatchAffineShapeEstimator` computes+half-precision gradients, Gaussian weights, moments, and normalization in `float32`, preserving valid anisotropic+shapes that would otherwise underflow; `LAFAffineShapeEstimator` sanitizes non-positive-definite ellipse+coefficients before conversion; and both it and `LAFAffNetShapeEstimator` use a finite fallback with finite+backward. The fallback is the input LAF when `preserve_orientation=True` and its upright form otherwise; a finite+zero-scale input keeps its center and zero affine block.diff --git a/changelog.d/+migration-019.fixed.md b/changelog.d/+migration-019.fixed.mdnew file mode 100644index 000000000..b59c47342--- /dev/null+++ b/changelog.d/+migration-019.fixed.md@@ -0,0 +1,3 @@+`depth_to_normals` now raises `ShapeError` when `H < 2` or `W < 2`, since surface normals need two+tangent directions. Previously, singleton axes could yield zero or non-finite normals, and empty+spatial dimensions failed inside padding. Inputs with both dimensions at least 2 are unchanged. (#4458)diff --git a/changelog.d/+migration-020.added.md b/changelog.d/+migration-020.added.mdnew file mode 100644index 000000000..a6beb6a50--- /dev/null+++ b/changelog.d/+migration-020.added.md@@ -0,0 +1,3 @@+An **Adoption** page (`community/adoption`) listing the most-starred GitHub repositories and+packages that depend on kornia, rendered at build time from `docs/source/_data/dependents.json`;+`docs/fetch_dependents.py` refreshes that snapshot from GitHub's dependency graph. (#4155)diff --git a/changelog.d/+migration-020.breaking.md b/changelog.d/+migration-020.breaking.mdnew file mode 100644index 000000000..7da311d98--- /dev/null+++ b/changelog.d/+migration-020.breaking.md@@ -0,0 +1,20 @@+`create_meshgrid` and `create_meshgrid3d` return different normalized coordinates at `float16`+and `bfloat16`. They used to evaluate `(xs / (size - 1) - 0.5) * 2` as three half-precision ops+in eager, rounding after each, and to materialize the half ramp before the graph-capture branch+widened it; `torch.compile` instead computed the chain in `float32` and rounded once, and folded+the narrow-then-widen round trip away so that above `2 ** p` the two paths divided different+numerators. A half-precision grid therefore changed the moment a model was wrapped in+`torch.compile` -- by up to 0.0117 in the `[-1, 1]` range at `bfloat16` width 300 and 0.0156 at+width 6000. A normalized half-precision grid is now built and normalized in `float32` and+narrowed once, so eager, traced and compiled grids agree; the eager values move onto the+correctly rounded side, which is the numeric change. `float32`, `float64` and integer grids and+the pixel ramp are bit-for-bit unchanged, since none of them widen. On CUDA at `float16` up to+one ulp of the coordinate dtype can still differ, because ATen's and triton's `float32` division+are not bit-identical; `bfloat16` absorbs it and the CPU kernels agree exactly. The Linux CPU+half-precision baselines move with it. `HomographyWarper` builds its precomputed grid in `float32`+and its on-the-fly grid in the input dtype, and the two now agree, which fixes+`test_homography_warper` at both dtypes and `test_translation[shape1]` at `float16`. At `bfloat16`+`test_translation[shape0]` and `[shape2]` join the `shape1` and `shape3` entries already recorded:+that test's `atol=1e-4` is out of reach for all four of its shapes there, and the two that passed+did so only because the old grid's larger error round-tripped through `grid_sample`'s `bfloat16`+unnormalize as an exact pixel index. Refs #4030. (#4231)diff --git a/changelog.d/+migration-020.fixed.md b/changelog.d/+migration-020.fixed.mdnew file mode 100644index 000000000..f2e6cb09d--- /dev/null+++ b/changelog.d/+migration-020.fixed.md@@ -0,0 +1,10 @@+`Boxes.pad`, `Boxes.unpad` and `Boxes.clamp` accept the unbatched `(N, 4, 2)` container the class+documents and constructs. All three assumed the batched `(B, N, 4, 2)` indexing: `pad` and `unpad`+broadcast the padding as `(B, 1, 1)`, which does not fit the unbatched `(N, 4)` coordinate view and+raised `RuntimeError: output with shape [1, 4] doesn't match the broadcast shape [1, 1, 4]`, and `clamp`+materialized its bounds with `repeat(1, _data.size(1), 4)` and raised `IndexError: too many indices for+tensor of dimension 2`. Adding a leading singleton batch axis to the same boxes made all three work.+They now broadcast against whichever rank the container holds and match the singleton-batch result;+an unbatched container carries one image, so a per-image tensor with more than one row is rejected.+Batched results are byte-identical, including for a non-finite bound: `clamp` stays comparison-based, so+a `NaN` bound leaves the coordinate alone rather than propagating into it (closes #4244). (#4372)diff --git a/changelog.d/+migration-021.added.md b/changelog.d/+migration-021.added.mdnew file mode 100644index 000000000..a63684fcf--- /dev/null+++ b/changelog.d/+migration-021.added.md@@ -0,0 +1,35 @@+Dynamo ONNX export (`torch.onnx.export(..., dynamo=True)`) now covers a much larger part of the+library: about 140 additional operator cases in the export survey capture, pass the ONNX checker+and match eager execution under onnxruntime. Operators that failed graph capture or had no ONNX+lowering gained an export-time path that returns the same values eagerly: matrix inverses up to+4x4 use a closed-form adjugate instead of `aten::linalg_inv` (`warp_perspective3d`,+`warp_affine3d`, `rotate3d`, `affine3d`, `get_projective_transform`, `invert_affine_transform`,+`denormalize_homography`, `symmetric_transfer_error`, `safe_inverse_with_mask`, `DepthWarper`,+`PinholeCamera`, `StereoCamera`, `NamedPose`, `ImageRegistrator`, `ParametrizedLine.intersect`+and the `Se2`/`Se3`/`So2` groups); `MedianBlur`/`median_blur` select the median through `sort`;+`HausdorffERLoss`/`HausdorffERLoss3D` pool through `amax` (which also makes the 3D loss run on MPS); `distance_transform` avoids `hypot`;+`match_nn`/`match_mnn`/`DescriptorMatcher` avoid `cdist`; the mutual-information losses, the+Bessel kernels, `solve_quadratic`, `matrix_cofactor_tensor`, `decompose_essential_matrix_no_svd`,+`distort_points`/`undistort_points`/`undistort_image`, `Boxes`/`Boxes3D` (`from_tensor`,+`to_mask`), `bbox_to_mask3d`, `mean_iou_bbox`, `conv_soft_argmax2d` with a tensor temperature,+`JPEGCodecDifferentiable`, `ZCAWhitening` (`transform`/`inverse_transform`), `BoxFiltering`,+`MotionBlur3D`, `center_crop`/`crop_and_resize`/`crop_by_transform_mat3d` and the+`OriNet`/`LAFOrienter`/`LAFAffNetShapeEstimator`/`HardNet`/`HardNet8`/`SIFTFeature`/+`LAFDescriptor`/`DeDoDe` feature stack are branch-free or guard their data-dependent checks with+`kornia.core.utils.is_exporting()`. Among augmentations, `LongestMaxSize`, `SmallestMaxSize`,+`RandomCrop`, `RandomResizedCrop`, `RandomAffine3D`, `RandomRotation3D`, `RandomMotionBlur3D`,+`RandomJPEG`, `RandomMedianBlur`, `RandomPlanckianJitter` and `AugmentationSequential` with+crops or boxes now export, and `LightGlue` exports once `depth_confidence`/`width_confidence`+pruning is disabled. Behavior notes: `Se2`/`Se3`/`So2`/`ParametrizedLine` built from a tensor+that already carries autograd history (`Se2.exp(v)`, `ParametrizedLine.through(p0, p1)`) keep+that history: the tensor is registered as a buffer instead of being re-rooted as an+`nn.Parameter`, so `.to()`, `state_dict()` and `load_state_dict()` still reach it under the same+key but it no longer appears in `parameters()`; `kornia.core.utils.is_exporting()` falls back to+`is_compiling()` on torch < 2.6, which has no export flag (inside a Dynamo trace newer torch+folds its flag to `True` for `torch.compile` as well, so the export-safe paths are what a+compiled graph contains on every supported version); under export `crop_by_indices` with a+`size` resamples the crop and without one keeps the eager path, `distort_points`/+`undistort_points` always apply the tilt term (a no-op when the coefficients are zero) and+`normalize`/`denormalize` accept a 1-D `(C,)` mean/std; `matrix_cofactor_tensor` returns exact+cofactors for singular matrices instead of raising when every matrix in the batch is singular.+(#4182)diff --git a/changelog.d/+migration-021.fixed.md b/changelog.d/+migration-021.fixed.mdnew file mode 100644index 000000000..01694b93a--- /dev/null+++ b/changelog.d/+migration-021.fixed.md@@ -0,0 +1,10 @@+`RandAugment`'s `m` guard is exclusive at both ends, but its docstring and its error message+both named the closed interval `[0, 30]`, so a user who asked for the maximum strength the+message advertised got an exception saying `30` was in range. Both now read `(0, 30)`; the+accepted values are unchanged. `n` was validated nowhere: `n=0` constructed a `RandAugment`+that applied nothing, and `n` above the policy length was silently clamped, because the+sampler draws without replacement. It is now checked against the policy. `AutoAugment`'s+magnitude bin indexes two adjacent points of an 11-point scale, so `9` is the last usable+bin; a larger one raised a raw `IndexError` naming an internal tensor, and a negative one+wrapped silently onto a reversed range. Out-of-range bins now name the operation and the+valid range. Operations that ignore the magnitude entirely keep accepting any bin. (#4447)diff --git a/changelog.d/+migration-022.added.md b/changelog.d/+migration-022.added.mdnew file mode 100644index 000000000..83ae38b3f--- /dev/null+++ b/changelog.d/+migration-022.added.md@@ -0,0 +1,6 @@+An **ONNX, torch.compile and torch.export support** page under Resources (`get-started/export-support`)+lists every surveyed public operator, grouped by package and section, with its dynamo ONNX export,+`torch.export` and `torch.compile` outcome, the cause of each failure and a search box with result+filters. It is rendered at build time from the committed snapshot+`docs/source/_data/export_support.json`; `docs/export_support/run.py` reruns the survey to refresh+it. (#4182)diff --git a/changelog.d/+migration-022.fixed.md b/changelog.d/+migration-022.fixed.mdnew file mode 100644index 000000000..80c19a515--- /dev/null+++ b/changelog.d/+migration-022.fixed.md@@ -0,0 +1,2 @@+`PinholeCamera.project` now reports rank-1 inputs with the same explicit `ValueError` used by the point-conversion+helpers instead of an internal `IndexError`. Refs #4266. (#4450)diff --git a/changelog.d/+migration-023.added.md b/changelog.d/+migration-023.added.mdnew file mode 100644index 000000000..30ad14147--- /dev/null+++ b/changelog.d/+migration-023.added.md@@ -0,0 +1,5 @@+Every page in the **Models** section of the docs now opens with the shortest script that runs the+model and a figure of its output on a real input, with the paper card moved to the bottom. The+figures are rendered by `docs/generate_model_examples.py` and committed under+`docs/source/_static/img/models/`, so the docs build needs neither the weights nor the sample+images. (#4178)diff --git a/changelog.d/+migration-023.fixed.md b/changelog.d/+migration-023.fixed.mdnew file mode 100644index 000000000..662dbd71e--- /dev/null+++ b/changelog.d/+migration-023.fixed.md@@ -0,0 +1,2 @@+`pixel2cam` now validates the full `Bx4x4` shape of `intrinsics_inv`, rejecting invalid matrix sizes+before they cause unrelated transformation errors or return the wrong number of coordinate components. (#4381)diff --git a/changelog.d/+migration-024.added.md b/changelog.d/+migration-024.added.mdnew file mode 100644index 000000000..1d1bcb928--- /dev/null+++ b/changelog.d/+migration-024.added.md@@ -0,0 +1,19 @@+The blocking MPS CI gate now runs on torch 2.14.0 instead of 2.9.1, on the `macos-15` image+instead of `macos-latest`, and its recorded failure baseline drops from 200 entries to 14.+torch 2.14.0 adds MPS kernels for `grid_sample`'s 2-D and 3-D backward passes, for+`padding_mode="border"` and 5-D `mode="nearest"` sampling, and for the eigen/QR/LU/SVD family+(`eigh`, `svd`, `svdvals`, `qr`, `lu_solve`, `lstsq`, `cholesky_solve`, `matrix_exp`), so most of+what used to fail on Apple silicon now runs there natively. What is still *pinned* in the+baseline: `torch.linalg.eigvals`, which has no MPS kernel and keeps the 5-point essential-matrix+solver off the device, and the `yuv420`/`yuv422` empty-input reshape defect. Separately,+`tests/geometry/test_ransac.py` is *skipped* rather than pinned β it aborts the process on the+runners' paravirtualized GPU, and a `SIGABRT` has no exception type to record+([#4204](https://github.com/kornia/kornia/issues/4204)); the skip costs 9 tests that pass on real+Apple hardware, and `--run-mps-process-abort` runs them locally. The underlying limit is that a+**batched** `torch.linalg.svd`/`svdvals`/`lstsq` fails to build a Metal pipeline once its input+holds 8192 elements or more, which keeps `RANSAC`'s batched minimal solvers off the device+([#4201](https://github.com/kornia/kornia/issues/4201)); a single unbatched matrix is unaffected+at any size. The image stays on `macos-15`: on `macos-latest` (macOS 26) the runner's *virtual*+GPU cannot compile the Metal 4 cooperative-tensor shaders torch 2.14 emits, which fails 664+tests β a physical M1 on macOS 26 compiles them fine. kornia still supports torch 2.5.1, so the+in-tree MPS workarounds stay. (#4202)diff --git a/changelog.d/+migration-024.fixed.md b/changelog.d/+migration-024.fixed.mdnew file mode 100644index 000000000..b6cb17bb8--- /dev/null+++ b/changelog.d/+migration-024.fixed.md@@ -0,0 +1,2 @@+`Boxes.to_mask` leaves list-padding channels empty, including after coordinate transforms,+instead of treating padding entries as real boxes. (#4390)diff --git a/changelog.d/+migration-025.fixed.md b/changelog.d/+migration-025.fixed.mdnew file mode 100644index 000000000..f901685e2--- /dev/null+++ b/changelog.d/+migration-025.fixed.md@@ -0,0 +1,2 @@+Fixed fixture teardown between files when running half-precision tests with+`--isolate-half-precision`, including reporting parent fixture finalizer errors. (#4388)diff --git a/changelog.d/+migration-026.fixed.md b/changelog.d/+migration-026.fixed.mdnew file mode 100644index 000000000..7450f1699--- /dev/null+++ b/changelog.d/+migration-026.fixed.md@@ -0,0 +1,4 @@+Corrected the matrix-shape checks shared by `PinholeCamera` and `PinholeCamerasList`, the+`pixel2cam` coordinate-shape check, and the `cam2pixel` coordinate/projection checks. Invalid+inputs now raise the intended `ValueError` instead of being accepted or failing later in tensor+operations. The rank-4 matrices used by `PinholeCamerasList` remain supported. (#4387)diff --git a/changelog.d/+migration-027.fixed.md b/changelog.d/+migration-027.fixed.mdnew file mode 100644index 000000000..84d778e11--- /dev/null+++ b/changelog.d/+migration-027.fixed.md@@ -0,0 +1 @@+Fixed `dx_distort_points_kannala_brandt` to return the true Jacobian of `distort_points_kannala_brandt`, including a finite affine Jacobian at the origin. (#4277, #4368)diff --git a/changelog.d/+migration-028.fixed.md b/changelog.d/+migration-028.fixed.mdnew file mode 100644index 000000000..cec8e693e--- /dev/null+++ b/changelog.d/+migration-028.fixed.md@@ -0,0 +1,10 @@+`Boxes3D.from_tensor(..., validate_boxes=True)` rejects non-finite coordinates, and `validate_bbox3d`+returns `False` for them instead of raising an `AssertionError` that names the wrong defect. This is the+3D counterpart of #4243. An `inf` passed the positive-extent checks outright, and a `NaN` passed them+because every comparison against `NaN` is `False`, so the box was constructed with non-finite vertices;+in `validate_bbox3d` the `NaN` instead reached the `allclose` extent comparisons and raised+"Boxes must have be cube, while get different widths". `validate_bbox3d`'s four internal callers use it+for its raise and discard the result, so they now convert the `False` themselves and keep raising the same+`AssertionError` they did before, with a message that now names the non-finite coordinates instead of+reporting mismatched cube extents. The `validate_boxes=False` opt-out and the export gate are unchanged+(closes #4258). (#4343)diff --git a/changelog.d/+migration-029.fixed.md b/changelog.d/+migration-029.fixed.mdnew file mode 100644index 000000000..afb58b9ad--- /dev/null+++ b/changelog.d/+migration-029.fixed.md@@ -0,0 +1,8 @@+`axis_angle_to_rotation_matrix` accepts the `(*, 3)` shape its own guard message promises, instead of+only `(N, 3)`. The body did `wxyz.unbind(dim=1)` and `.view(-1, 3, 3)`, so an unbatched `(3,)` raised+`IndexError: Dimension out of range` and any extra batch dimension raised `ValueError` out of the unbind,+three frames below kornia's own shape guard. Every sibling conversion in the module already accepted+`(*, 3)`, so `axis_angle_to_rotation_matrix(rotation_matrix_to_axis_angle(R))` composed for an `(N, 3, 3)`+rotation matrix and for nothing else, including for the shape `rotation_matrix_to_axis_angle`'s own+doctest returns. This is additive: `(N, 3)` output and gradients are byte-identical, and only shapes that+used to raise now return (closes #3955). (#4342)diff --git a/changelog.d/+migration-030.fixed.md b/changelog.d/+migration-030.fixed.mdnew file mode 100644index 000000000..5325170d5--- /dev/null+++ b/changelog.d/+migration-030.fixed.md@@ -0,0 +1,2 @@+Make calibration `distort_points` and `undistort_points` tilt checks compatible with+`torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)diff --git a/changelog.d/+migration-031.fixed.md b/changelog.d/+migration-031.fixed.mdnew file mode 100644index 000000000..f3aa6b77f--- /dev/null+++ b/changelog.d/+migration-031.fixed.md@@ -0,0 +1 @@+Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)diff --git a/changelog.d/+migration-032.fixed.md b/changelog.d/+migration-032.fixed.mdnew file mode 100644index 000000000..0c1dca13a--- /dev/null+++ b/changelog.d/+migration-032.fixed.md@@ -0,0 +1 @@+`PinholeCamera`, `StereoCamera`, and `warp_frame_depth` now support empty batches. (#4386)diff --git a/changelog.d/+migration-033.fixed.md b/changelog.d/+migration-033.fixed.mdnew file mode 100644index 000000000..801bc2cb8--- /dev/null+++ b/changelog.d/+migration-033.fixed.md@@ -0,0 +1,2 @@+`elastic_transform2d` now builds its identity sampling grid with the requested `align_corners`+convention, so a zero displacement field preserves the input image. (closes #4235). (#4382)diff --git a/changelog.d/+migration-034.fixed.md b/changelog.d/+migration-034.fixed.mdnew file mode 100644index 000000000..917e830d6--- /dev/null+++ b/changelog.d/+migration-034.fixed.md@@ -0,0 +1,3 @@+`rad2deg` and `deg2rad` now handle integer tensor inputs correctly and preserve+float64 precision. `angle_to_rotation_matrix` inherits the corrected conversion,+while the implementation preserves ONNX export compatibility. (#4358)diff --git a/changelog.d/+migration-035.fixed.md b/changelog.d/+migration-035.fixed.mdnew file mode 100644index 000000000..3130bd39c--- /dev/null+++ b/changelog.d/+migration-035.fixed.md@@ -0,0 +1,2 @@+`fft_conv` now accepts CPU float16 and bfloat16 inputs by computing the FFTs+in float32 and returning the input dtype. (#4394)diff --git a/changelog.d/+migration-036.fixed.md b/changelog.d/+migration-036.fixed.mdnew file mode 100644index 000000000..6293b5732--- /dev/null+++ b/changelog.d/+migration-036.fixed.md@@ -0,0 +1,2 @@+Corrected stereo disparity validation errors to describe the required channels-last+`(B, H, W, 1)` layout and report the received shape. (#4380)diff --git a/changelog.d/+migration-037.fixed.md b/changelog.d/+migration-037.fixed.mdnew file mode 100644index 000000000..4dd2a8091--- /dev/null+++ b/changelog.d/+migration-037.fixed.md@@ -0,0 +1,7 @@+`CameraModelBase.__init__` now validates `params` against the shape it documents, instead of storing+whatever it is given. The typed constructors (`PinholeModel`, `BrownConradyModel`, `KannalaBrandtK3`,+`Orthographic`) each apply the same two comparisons, so only the direct-construction path -- which is+public, and is what the class docstring's own example uses -- was unguarded. A short vector used to+construct and then fail with an `IndexError` from inside `AffineTransform.distort`, naming neither+`params` nor the camera; a rank-3 `(B, 1, N)` tensor used to construct, project, and silently return a+`(1, 1, 2)` result. Both now raise `ValueError` from the constructor. (#4316, #4369)diff --git a/changelog.d/+migration-038.fixed.md b/changelog.d/+migration-038.fixed.mdnew file mode 100644index 000000000..e130a885d--- /dev/null+++ b/changelog.d/+migration-038.fixed.md@@ -0,0 +1,4 @@+`undistort_points_kannala_brandt` no longer collapses representable `float16` points next to the principal point+to the origin, and the exact principal-point path now has finite autograd gradients. The zero-radius decision is+made from the unsquared normalized coordinates, and the `float16` radius uses `float32` intermediates so its+squared value does not underflow; nonzero radial rescaling remains epsilon-free. (#4308, #4370)diff --git a/changelog.d/+migration-039.fixed.md b/changelog.d/+migration-039.fixed.mdnew file mode 100644index 000000000..a7c23f07a--- /dev/null+++ b/changelog.d/+migration-039.fixed.md@@ -0,0 +1,7 @@+`solve_quartic` now validates Ferrari resolvent candidates with a dtype-aware scaled residual,+falls back to the smallest scaled residual when no candidate passes, and keeps the Ferrari `E`+factorization away from an ill-conditioned `R` division. Cancellation-level `R^2` is snapped to+zero relative to the coefficient scale, and all Ferrari compute dtypes choose between the linear-+and constant-term `E` forms by normalized coefficient error; float32 also refines the selected+resolvent root once. The gradient-safe zero-radicand path remains intact, preventing half-precision+non-finite or dropped roots and full-precision non-roots while preserving the public contract. (#4357)diff --git a/changelog.d/+migration-040.fixed.md b/changelog.d/+migration-040.fixed.mdnew file mode 100644index 000000000..5f6a1db73--- /dev/null+++ b/changelog.d/+migration-040.fixed.md@@ -0,0 +1,3 @@+`StereoCamera` now rejects projection matrices whose last two dimensions are not `(3, 4)` with a+`StereoException` naming the invalid camera. Previously, the shape guards never fired, so malformed+matrices could be accepted or fail later with an unrelated tensor error. (#4385)diff --git a/changelog.d/+migration-041.fixed.md b/changelog.d/+migration-041.fixed.mdnew file mode 100644index 000000000..9789e8a9b--- /dev/null+++ b/changelog.d/+migration-041.fixed.md@@ -0,0 +1,11 @@+`warp_affine`, `warp_perspective` and `remap` crashed on MPS for an empty destination -- a `dsize` with a+zero dimension, or zero-sized `remap` maps -- with an internal+`[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder tensor is empty!` from PyTorch. The MPS backend+rejects *any* zero-element `grid_sample` operand before torch 2.14, including a zero-element grid sampled+against a non-empty source, which is what the empty-destination path built. That path now samples a connected+1x1 stand-in and expands the result to the requested empty shape, so `grid_sample` never receives a+zero-element operand on any backend and an empty warp costs the same whatever the non-zero side of `dsize` is.+The empty path also resolves its output batch the way each operation's non-empty path does, so a singleton+transform or map batch broadcasts identically and a mismatched batch is rejected rather than silently+returning the wrong cardinality. Outputs, autograd links and the documented empty-source policy are unchanged+on CPU and CUDA. (#4032, #4354)diff --git a/changelog.d/+migration-042.fixed.md b/changelog.d/+migration-042.fixed.mdnew file mode 100644index 000000000..60e56ee58--- /dev/null+++ b/changelog.d/+migration-042.fixed.md@@ -0,0 +1,8 @@+`VideoBoxes.get_boxes_shape()` and `VideoBoxes.to_mask()` no longer raise `TypeError`. Both are+inherited from `Boxes` and pass `as_padded_sequence=True` to `to_tensor`, but the `VideoBoxes`+override declared only `mode`, so every call on a `VideoBoxes` failed -- including the containers+`AugmentationSequential` builds for video box inputs. The override now accepts and forwards the+keyword; it only changes a list-backed container, and a `VideoBoxes` built from a+`(B, T, N, 4, 2)` tensor is not one, so no working call changes its result. Indexing a+`VideoBoxes` still drops `temporal_channel_size`, which is the remaining half of #4249.+(#4176, #4365)diff --git a/changelog.d/+migration-043.fixed.md b/changelog.d/+migration-043.fixed.mdnew file mode 100644index 000000000..79d54ed1e--- /dev/null+++ b/changelog.d/+migration-043.fixed.md@@ -0,0 +1,2 @@+Fixed `unproject_points_z1` depth shape handling for singleton and multi-axis batches,+accepting both trailing-singleton and flat depth tensors. (#4355)diff --git a/changelog.d/+migration-044.fixed.md b/changelog.d/+migration-044.fixed.mdnew file mode 100644index 000000000..5febbfb0a--- /dev/null+++ b/changelog.d/+migration-044.fixed.md@@ -0,0 +1,7 @@+`solve_quartic` returns finite gradients for a pure biquadratic such as `x^4 - 16`. Its two+`torch.clamp(..., min=0.0).sqrt()` sites do not guard the gradient they look like they guard:+`d(sqrt)/dx` is unbounded at 0, and on torch below 2.14 `clamp` passes the incoming gradient+through at the bound rather than zeroing it, so on the older half of kornia's supported torch+range the backward returned `inf` and then `nan` (#4229). Both sites now substitute a safe+radicand under the `sqrt`, as `solve_quadratic` in the same module already did. Forward values+are unchanged. (#4339)diff --git a/changelog.d/+migration-045.fixed.md b/changelog.d/+migration-045.fixed.mdnew file mode 100644index 000000000..6e49f4445--- /dev/null+++ b/changelog.d/+migration-045.fixed.md@@ -0,0 +1,10 @@+`depth_from_plane_equation` returns a finite depth for a ray exactly parallel to the plane. The+near-singular guard was `eps * torch.sign(denom)`, and `torch.sign` is zero at zero, so at the exact+singularity the epsilon was multiplied away and the division still ran against zero, returning `inf`.+A grazing ray is not an exotic input: it is every pixel on the horizon of a ground plane. The guard+now picks its sign with a comparison, which has no such hole and keeps the sign the small non-zero+denominators already got. `torch.copysign` reads the same but is not exportable, and this function+is in the documented ONNX export surface, so the comparison form is pinned in+`tests/onnx/test_export_coverage.py`. The finite-depth promise is bounded by the dtype: the default+`eps=1e-8` is below float16 resolution, so half-precision callers must pass a representable `eps`.+(#4280, #4348)diff --git a/changelog.d/+migration-046.fixed.md b/changelog.d/+migration-046.fixed.mdnew file mode 100644index 000000000..0fa8eaab7--- /dev/null+++ b/changelog.d/+migration-046.fixed.md@@ -0,0 +1 @@+`depth_from_disparity` accepts Python integers and scalar tensors for the baseline and focal length. (#4392)diff --git a/changelog.d/+migration-047.fixed.md b/changelog.d/+migration-047.fixed.mdnew file mode 100644index 000000000..0abcc8176--- /dev/null+++ b/changelog.d/+migration-047.fixed.md@@ -0,0 +1,7 @@+`iterative_quad_interp3d`'s `max_candidates` cap is now a per-image budget rather than one shared+across the batch. The `topk` ranked the flattened `(B*C)` candidate list, so an image's refined+keypoints depended on which other images shared its batch: a quiet image next to a high-contrast+one got none. This also reaches `IterativeQuadInterp3d` and `AdaptiveQuadInterp3d` in `patch` mode.+The docstring already read as a per-image budget. A negative `max_candidates` now raises+`ValueError`; it previously raised a `topk` `RuntimeError`, and under the per-image ranking it+would otherwise have silently disabled refinement instead. (#4256, #4350)diff --git a/changelog.d/+migration-048.fixed.md b/changelog.d/+migration-048.fixed.mdnew file mode 100644index 000000000..42d38c9fa--- /dev/null+++ b/changelog.d/+migration-048.fixed.md@@ -0,0 +1,5 @@+`infer_bbox_shape3d` and `bbox_to_mask3d` reject rank-4 `(B, N, 8, 3)` input with a `ShapeError`,+the way `infer_bbox_shape` and `bbox_to_mask` have since #4218. `validate_bbox3d` accepts the rank-4+form and reshapes internally, but both callers index dim 1 as the vertex axis, so the box axis was+read as the vertices: an out-of-bounds error with one box, and three `(1, 3)` tensors -- one value+per coordinate rather than per box -- with eight. (#4248, #4351)diff --git a/changelog.d/+migration-049.fixed.md b/changelog.d/+migration-049.fixed.mdnew file mode 100644index 000000000..7e8bf54c2--- /dev/null+++ b/changelog.d/+migration-049.fixed.md@@ -0,0 +1,7 @@+`solve_cubic` and `solve_quartic` return finite gradients for a row whose neighbours in the+same batch take a different branch. The `D > 0` branch selected its rows with `abs(R) > 1e-16`+alone, so it evaluated `sqrt(D)` on `D < 0` rows too. Those rows are never read back, but the+resulting `-Q / nan` stays in the graph and its backward returns `nan`, which reaches every+coefficient: a three-real-root cubic differentiated correctly on its own and gave `nan` as soon+as a one-real-root cubic shared the batch, and `solve_quartic` inherited it through its+resolvent cubic. The forward values are unchanged. (#4334, #4338)diff --git a/changelog.d/+migration-050.fixed.md b/changelog.d/+migration-050.fixed.mdnew file mode 100644index 000000000..5e4a625d0--- /dev/null+++ b/changelog.d/+migration-050.fixed.md@@ -0,0 +1,9 @@+`Normalize`, `Denormalize` and `Rescale` register their constants (`mean`, `std`, `factor`) as+non-persistent buffers instead of plain attributes, so `.to(device)` moves them with the module.+Previously they stayed on the CPU: eager tolerates the mix, but `torch.export` traces with fake+tensors and refused it, so exporting a preprocessing pipeline from an accelerator failed while+the same pipeline exported fine from the CPU. `Denormalize` now coerces a scalar `mean`/`std` to+a 1-D tensor, as `Normalize` already did, which changes its `__repr__` to match `Normalize`'s and+lets a scalar `Denormalize` reach the ONNX export branch instead of raising `IndexError` there.+The buffers are non-persistent, so `state_dict()` is unchanged and existing checkpoints still+load. (#4323, #4330)diff --git a/changelog.d/+migration-051.fixed.md b/changelog.d/+migration-051.fixed.mdnew file mode 100644index 000000000..536d5a319--- /dev/null+++ b/changelog.d/+migration-051.fixed.md@@ -0,0 +1,7 @@+`download_file_from_url` and `download_hf_file` take an optional `validate=` callable, and+`kornia.core.check_safetensors` is the one the KimiVL and SigLIP2 builders pass. A transfer cut+short after a 2xx status leaves a truncated file in the cache, which was then returned as a cache+hit on every later call -- `from_pretrained_hf()` failed until the user deleted it by hand.+`validate` gives a download-only call the quarantine `load_state_dict_from_url` gets from its load+step: a rejected entry is moved aside, the next source is tried, and the discarded source is+re-fetched once. Without `validate` the behaviour is unchanged. (#4309, #4332)diff --git a/changelog.d/+migration-052.fixed.md b/changelog.d/+migration-052.fixed.mdnew file mode 100644index 000000000..f25202e06--- /dev/null+++ b/changelog.d/+migration-052.fixed.md@@ -0,0 +1,4 @@+`PinholeCamera.scale` no longer shares its `extrinsics` tensor with the source camera. The+intrinsics were cloned, the extrinsics were handed to the new object by reference, and the+constructor stores what it is given, so `scaled.tx = 7` moved the camera `scale()` was called on.+The returned camera's numbers are unchanged. (#4264, #4349)diff --git a/changelog.d/+migration-053.fixed.md b/changelog.d/+migration-053.fixed.mdnew file mode 100644index 000000000..b73ce0da5--- /dev/null+++ b/changelog.d/+migration-053.fixed.md@@ -0,0 +1,7 @@+A fresh transfer that `validate` rejects is now removed even when no other source could have used+the emptied path -- which is every `download_hf_file` caller, since it passes one URL. Those bytes+arrived during the call and were refused, so unlike the ambiguous load failures+`load_state_dict_from_url` weighs, keeping them would end the call having added a poisoned entry to+a cache that had none. An offline re-fetch also reports the validator's rejection rather than the+network error stacked on top of it, so the message names the file rather than an entry that is+intact and, by then, restored. (#4367)diff --git a/changelog.d/+migration-054.fixed.md b/changelog.d/+migration-054.fixed.mdnew file mode 100644index 000000000..d80447e96--- /dev/null+++ b/changelog.d/+migration-054.fixed.md@@ -0,0 +1,9 @@+`RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering+time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never+moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so+`RenderingDeFMO().half()` left `times` at `float32` and the first forward raised `RuntimeError: Input+type (torch.FloatTensor) and weight type (torch.HalfTensor) should be the same`. `times` is now a+non-persistent buffer (it is fully determined by `tsr_steps`, not learned, so `state_dict()` keys and+existing checkpoints are unaffected), and `forward` casts into a local variable rather than depending+on the caller having matched dtype. Same bug shape as #4069/#4079 in a different class; the normal+`float32` path is byte-identical to before. (#4319)diff --git a/changelog.d/+migration-055.fixed.md b/changelog.d/+migration-055.fixed.mdnew file mode 100644index 000000000..0027e41ae--- /dev/null+++ b/changelog.d/+migration-055.fixed.md@@ -0,0 +1,10 @@+`jpeg_codec_differentiable` no longer returns an all-`NaN` image at `jpeg_quality=0`, a value inside the+`[0, 100]` range it documents and validates. `_jpeg_quality_to_scale` divides `5000` by the quality on the+`< 50` branch, which is `inf` at `0`, and the polynomial floor of `inf` is `NaN`, poisoning the image and+its gradient. A quality of exactly `0` is now given the scale of quality `1`, which is the table libjpeg+gives quality `0`. The guard is that one point: a fractional quality in `(0, 1)` was already finite, keeps+its own larger scale, and is untouched, so this endpoint is not the limit of the formula from above.+Output and gradients for every quality `> 0` are byte-identical. The tests drew+the quality with `torch.randint(low=0, high=100)` unseeded at sixteen sites, so roughly one run in twenty of+`tests/enhance/test_jpeg.py` went red on any job; the draws now start at `1` and the boundary has pinned+cases of its own. (#4205)diff --git a/changelog.d/+migration-056.fixed.md b/changelog.d/+migration-056.fixed.mdnew file mode 100644index 000000000..2f60ffc02--- /dev/null+++ b/changelog.d/+migration-056.fixed.md@@ -0,0 +1,8 @@+`ModelBase.save` and `_save_outputs` write the visualizations they are given instead of raising.+They handed `visualize`'s float output to `write_image` under a hard-coded `.png` name, but PNG is+`uint8`/`uint16` only, so every container's `save` (`SemanticSegmentation`, `ObjectDetector`,+`EdgeDetector`, `DepthEstimation`) raised on its first write and left an empty directory behind.+Float images are now converted to `uint8`, clamped to `[0, 1]` first so an out-of-range+visualization does not wrap. A batched `(B, 3, H, W)` output -- the shape the containers document+-- is written as one file per item rather than passed whole to `write_image`, which takes+`(3, H, W)` and rejected the rank with a message naming neither. (#4322)diff --git a/changelog.d/+migration-057.fixed.md b/changelog.d/+migration-057.fixed.mdnew file mode 100644index 000000000..f86fbeb7e--- /dev/null+++ b/changelog.d/+migration-057.fixed.md@@ -0,0 +1,10 @@+`RandomChannelDropout.fill_value` and `RandomGaussianBlurGenerator.sigma` (when passed as a+Tensor) are registered as non-persistent buffers instead of plain attributes, so they move with+`Module.to()`/`.half()`/`.cuda()` and appear in `named_buffers()` like the rest of the module's+state; `state_dict()` keys are unchanged. Neither crashed before this change (both re-derived+device and dtype inline on every call), so this is a hygiene fix, not a bug fix for a crash.+One user-visible effect: after `.half()`/`.bfloat16()` the fill value is now held in that dtype,+so an input already in the module's dtype is unaffected, while a `float32` input fed to a+half-converted `RandomChannelDropout(fill_value=0.3)` is filled with `0.300048828125` (float16)+or `0.30078125` (bfloat16) rather than `0.3` -- the same buffer semantics as `Normalize`.+(#4337)diff --git a/changelog.d/+migration-058.fixed.md b/changelog.d/+migration-058.fixed.mdnew file mode 100644index 000000000..8ad1441d5--- /dev/null+++ b/changelog.d/+migration-058.fixed.md@@ -0,0 +1,3 @@+`Z1Projection.unproject` now materialises a python `int`/`float` `depth` on the device and+in the dtype of `points`; it used to build a CPU float32 tensor, which raised `RuntimeError`+on every accelerator and widened float16/bfloat16 results to float32. (#4340)diff --git a/changelog.d/+migration-059.fixed.md b/changelog.d/+migration-059.fixed.mdnew file mode 100644index 000000000..7398b4e54--- /dev/null+++ b/changelog.d/+migration-059.fixed.md@@ -0,0 +1,3 @@+`_cdist` replaces `dm.clamp(min=0.0).sqrt()` with a masked argument substitution, avoiding `NaN` gradients for+exact zero-distance pairs on PyTorch 2.5.1 and 2.9.1 where `clamp`'s boundary gradient passed through to `sqrt(0)`.+PyTorch 2.14.0 was already finite, and forward behavior and computed distances are unchanged. (#4233)diff --git a/changelog.d/+migration-060.fixed.md b/changelog.d/+migration-060.fixed.mdnew file mode 100644index 000000000..894ebb9f3--- /dev/null+++ b/changelog.d/+migration-060.fixed.md@@ -0,0 +1,5 @@+`bbox_to_mask` built its pixel-position grid in the box dtype. With `float16` boxes (and+`bfloat16` boxes) on images wider or taller than 2048 px (256 px for `bfloat16`) consecutive+pixel positions collapsed, so rows and columns near the collapse were mismasked; the grid is+now built in `float32` and `float16`/`bfloat16` results are byte-identical to `float32`/`float64`.+`RandomErasing` and `RandomCutMixV2` build their masks through it. (#4336)diff --git a/changelog.d/+migration-061.fixed.md b/changelog.d/+migration-061.fixed.mdnew file mode 100644index 000000000..016087178--- /dev/null+++ b/changelog.d/+migration-061.fixed.md@@ -0,0 +1,6 @@+`kornia.contrib.super_resolution` builders construct again. `SuperResolution` never implemented+`ModelBase`'s abstract `from_config` and defined no `__init__`, so `SmallSRBuilder.build()` and+`RRDBNetBuilder.build()` both raised `TypeError` at construction β the whole public+super-resolution entry point had been unreachable since the models refactor made `from_config`+abstract. It now has a `SuperResolutionConfig` and a `from_config` that dispatches to either+builder family, and both builders are covered by tests. Fixes #4291. (#4335)diff --git a/changelog.d/+migration-062.fixed.md b/changelog.d/+migration-062.fixed.mdnew file mode 100644index 000000000..d25d31928--- /dev/null+++ b/changelog.d/+migration-062.fixed.md@@ -0,0 +1,3 @@+`tilt_projection` preserves its documented leading batch dimensions, so `distort_points`,+`undistort_points`, and `undistort_image` no longer fail on multi-axis batches when tilt distortion+is applied. (#4345)diff --git a/changelog.d/+migration-063.fixed.md b/changelog.d/+migration-063.fixed.mdnew file mode 100644index 000000000..fe5c895a1--- /dev/null+++ b/changelog.d/+migration-063.fixed.md@@ -0,0 +1,11 @@+`kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`+resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into+`kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raised+`AttributeError` for every JPEG and every PNG that is not plain RGB, and `write_image` raised for+TIFF, 16-bit and float32 output (8-bit JPEG and PNG writes still worked); the lock's 0.1.10 kept CI+green. kornia now calls `kornia_rs.io` and requires kornia_rs 0.1.14 (see *Breaking changes*). That+decoder also reads 16-bit PNG/TIFF and float TIFF, which 0.1.10 rejected: `ImageLoadType.UNCHANGED`+returns them as `uint16`/`float32`, and the 8-bit load types raise a `NotImplementedError` that says+so instead of mislabelling the tensor. The nightly PyPI job now imports the installed wheel from+outside the checkout (it used to import the source tree) and round-trips an image instead of only+importing. (#4326)diff --git a/changelog.d/+migration-064.fixed.md b/changelog.d/+migration-064.fixed.mdnew file mode 100644index 000000000..01e7b86d6--- /dev/null+++ b/changelog.d/+migration-064.fixed.md@@ -0,0 +1,2 @@+`distance_transform` no longer returns NaN gradients when the cascade's convolution is exactly zero, including+sparse masks and all-zero inputs; the existing forward output is unchanged. (#4232)diff --git a/changelog.d/+migration-065.fixed.md b/changelog.d/+migration-065.fixed.mdnew file mode 100644index 000000000..3434b3d78--- /dev/null+++ b/changelog.d/+migration-065.fixed.md@@ -0,0 +1,8 @@+`SemanticSegmentation.visualize` works for CUDA, MPS and half-precision models. It indexed the+CPU-drawn colormap with the mask's `argmax`, which raises for CUDA and MPS masks, and recognised a+softmax head with `torch.allclose(sum, 1)` at float32-sized default tolerances, which a float16 or+bfloat16 sum of probabilities never meets; the tolerance now scales with the number of classes and the+dtype's epsilon, and the colormap follows the mask's device and dtype, so the visualization keeps the+model's dtype instead of coming back as float32. `OnnxLightGlue` without `onnxruntime` raises an+`ImportError` that names `pip install "kornia[onnx]"`, like the lazy-loader handles do, instead of a+bare `BaseError`. (#4301)diff --git a/changelog.d/+migration-066.fixed.md b/changelog.d/+migration-066.fixed.mdnew file mode 100644index 000000000..e3c147242--- /dev/null+++ b/changelog.d/+migration-066.fixed.md@@ -0,0 +1,4 @@+`PinholeCamera.from_parameters` now fills `height` and `width` for the whole batch. It built them with+`height_tmp[..., 0] += height` on a `(B,)` zero tensor, so every batch element after the first kept `0`+while `fx`, `fy`, `cx`, `cy`, `tx`, `ty` and `tz` were broadcast correctly, and the camera looked healthy+until something read its image size. `batch_size=1`, the only case that worked, is unchanged. (#4279)diff --git a/changelog.d/+migration-067.fixed.md b/changelog.d/+migration-067.fixed.mdnew file mode 100644index 000000000..a9fd722eb--- /dev/null+++ b/changelog.d/+migration-067.fixed.md@@ -0,0 +1,8 @@+`unproject_meshgrid` now returns the documented `(*, H, W, 3)` shape when `W` is 1. It squeezed the+meshgrid with a bare `.squeeze()`, which drops the width axis along with the leading batch axis whenever+`W == 1`, so `unproject_meshgrid(1, 3, K)` and `unproject_meshgrid(3, 1, K)` returned the same shape with+different values. The grid then broadcast across a phantom width in the two public functions built on it:+`depth_to_3d_v2` returned `(1, 3, 3, 3)` for a `W = 1` depth where `depth_to_3d` correctly returns+`(1, 3, 1, 3)`, and `warp_frame_depth` returned a 4-pixel-wide image for a 1-pixel-wide input. Only the+batch axis is dropped now. Output for every `W > 1` is byte-identical, and `depth_to_3d_v2` agrees with+`depth_to_3d` at `W = 1` as it already did everywhere else. (#4278)diff --git a/changelog.d/+migration-068.fixed.md b/changelog.d/+migration-068.fixed.mdnew file mode 100644index 000000000..a91eacccc--- /dev/null+++ b/changelog.d/+migration-068.fixed.md@@ -0,0 +1,9 @@+The generated example figures in the API reference are rendered from RGB input.+`docs/generate_examples.py` decoded the sample images with `cv2.imdecode` and wrote them with+`cv2.imwrite`, both BGR, so every tensor the examples fed to kornia held reversed channels. The two+swaps cancel in the written file for channel-agnostic operations, but 35 colour-dependent figures+change, and the ones that depend on which channel is which (`rgb_to_hsv`, `ColorJitter`,+`apply_colormap`, the bbox and keypoint colours of `AugmentationSequential`, ...) showed a blue cast+or swapped overlay colours. The generator now decodes and writes with PIL, draws the KeyNetAffNet+LAF figure with kornia's own `get_laf_pts_to_draw`, and `opencv-python` and `kornia_moons` leave+the `[docs]` extra. (#4306)diff --git a/changelog.d/+migration-069.fixed.md b/changelog.d/+migration-069.fixed.mdnew file mode 100644index 000000000..77fe7723a--- /dev/null+++ b/changelog.d/+migration-069.fixed.md@@ -0,0 +1,6 @@+`kornia.io.get_sample_images` and `kornia.onnx.ONNXLoader.list_operators` / `list_models` no longer need+`requests`, which `pip install kornia` never installed; they fetch with the standard library `urllib` instead.+The failure exceptions change with it, all still `OSError` subclasses: a sample-image URL that returns 404 now+raises `urllib.error.HTTPError` instead of `PIL.UnidentifiedImageError`, and an unreachable host raises+`urllib.error.URLError` instead of `requests.exceptions.ConnectionError`. A 404 from the Hugging Face listing+still raises the same `ValueError` (#4302)diff --git a/changelog.d/+migration-070.fixed.md b/changelog.d/+migration-070.fixed.mdnew file mode 100644index 000000000..aef9ff43c--- /dev/null+++ b/changelog.d/+migration-070.fixed.md@@ -0,0 +1,3 @@+`packaging` is no longer a runtime dependency; it was never imported. The `dev` extra no longer lists+`pytest-cov` (CI runs `coverage run -m pytest`), `ruff` (the pre-commit hook installs the pinned copy) or a+`numpy<3` cap, and `uv.lock` is regenerated to match (#4296).diff --git a/changelog.d/+migration-071.fixed.md b/changelog.d/+migration-071.fixed.mdnew file mode 100644index 000000000..f100aea12--- /dev/null+++ b/changelog.d/+migration-071.fixed.md@@ -0,0 +1 @@+`import kornia` no longer imports onnxruntime when it is installed (#4295)diff --git a/changelog.d/+migration-072.fixed.md b/changelog.d/+migration-072.fixed.mdnew file mode 100644index 000000000..52432df58--- /dev/null+++ b/changelog.d/+migration-072.fixed.md@@ -0,0 +1,2 @@+DeDoDe's vendored DINOv2 no longer probes for `xformers`; the pure-PyTorch path it always ran is the+only one. (#4288)diff --git a/changelog.d/+migration-073.fixed.md b/changelog.d/+migration-073.fixed.mdnew file mode 100644index 000000000..37924593e--- /dev/null+++ b/changelog.d/+migration-073.fixed.md@@ -0,0 +1,4 @@+`kornia.feature.LightGlue` no longer probes for `flash_attn`; the SDPA path it always used is now+the only one. `kornia.feature.lightglue.Attention.enable_flash`, the attribute that combined the+constructor argument with the probe result (and so always equalled the argument, because SDPA is+present on every supported torch), was renamed to `Attention.allow_flash`. (#4287)diff --git a/changelog.d/+migration-074.fixed.md b/changelog.d/+migration-074.fixed.mdnew file mode 100644index 000000000..b2bd18931--- /dev/null+++ b/changelog.d/+migration-074.fixed.md@@ -0,0 +1,8 @@+`bbox_to_mask3d` now returns the intersection of the three axis ranges for a box that covers or+overhangs a whole output axis, matching `Boxes3D.to_mask`, instead of filling the entire volume+(#4255, #4303). The old implementation `|`-ed the three broadcast axis slabs and tried to recover the+intersection with a three-way `all()` reduction; that recovery breaks the moment any one slab+covers a whole axis, since the union is then all-true on that axis and the reduction can no+longer see the other two slabs' bounds. Computing the intersection directly with `&` needs no+such recovery step. Interior boxes (the case the old reductions happened to recover correctly)+are unaffected and byte-identical.diff --git a/changelog.d/+migration-075.fixed.md b/changelog.d/+migration-075.fixed.mdnew file mode 100644index 000000000..5c8580fc6--- /dev/null+++ b/changelog.d/+migration-075.fixed.md@@ -0,0 +1,14 @@+`solve_cubic`'s `D <= 0` (three-real-roots) branch no longer returns `nan` gradients for a+repeated or near-repeated real root (#4290, #4299). It differentiates `acos(R / sqrt(-Q3))`, whose own+derivative `-1/sqrt(1-x^2)` is unbounded at `x = +-1`; the branch condition guarantees the ratio+lies in `[-1, 1]`, but a repeated or near-repeated root pushes it to exactly that boundary,+where the value is correct but the derivative diverges. A double-root quartic reaches this+through `solve_quartic`'s resolvent cubic routinely, not as an edge case: measured on 20,000+random real-rooted quartics, 10.7% hit a non-finite gradient or a disconnected graph overall,+35.3% for exact double-root pairs specifically. Same failure shape as the `acos`/`asin`+boundary in `quaternion_exp_to_log`/`euler_from_quaternion` (#4007, fixed in #4228) β this is a+different call site, not covered by that fix, using the same guard: differentiate a substituted+safe argument, take the value from a detached copy of the real (possibly boundary) argument.+Forward values are unchanged; re-running the same 20,000-trial search with the fix applied+drops the failure count to 1,269 β a real, separate residual (a disconnected-graph case with+two simultaneous double-root pairs) remains and is tracked in #4290, not fixed here.diff --git a/changelog.d/+migration-076.fixed.md b/changelog.d/+migration-076.fixed.mdnew file mode 100644index 000000000..6a9b6968e--- /dev/null+++ b/changelog.d/+migration-076.fixed.md@@ -0,0 +1,6 @@+`pixel2cam` now rejects depth tensors outside the documented `Bx1xHxW` shape. The guard's predicate+bound as `(ndim != 4) and (shape[1] == 1)`, so four-dimensional multi-channel depth bypassed the+channel check β a three-channel depth silently broadcast into separate camera coordinates β while+scalar and one-dimensional inputs raised `IndexError` from the guard itself. Code that passed those+shapes and relied on them being accepted now raises `ValueError`. Valid `Bx1xHxW` depth is unaffected+and its output is unchanged. (#4314)diff --git a/changelog.d/+migration-077.fixed.md b/changelog.d/+migration-077.fixed.mdnew file mode 100644index 000000000..f468caa5f--- /dev/null+++ b/changelog.d/+migration-077.fixed.md@@ -0,0 +1,8 @@+`ConvQuadInterp3d` / `conv_quad_interp3d` no longer return NaN gradients for `float16` input. The+Hessian determinant `_solve_cramer_sym3x3` divides by is a product of three second derivatives, so for+a `[0, 1]` response it lands around 1e-4 and below and still clears the `eps` gate. The forward divides+by it once and stays finite, but the backward scales by `1 / det**2`, which `float16` cannot represent+(`finfo(float16).tiny` is 6.1e-5), so the gradient overflowed and reduced to NaN over part of the+volume. The solve is now promoted to `float32` for `float16` input and the shifts cast back, as #4231+already does for the half-precision meshgrid. `bfloat16` keeps `float32`'s exponent range and was never+affected; `bfloat16` and `float32` outputs are unchanged. (#4305)diff --git a/changelog.d/+migration-078.fixed.md b/changelog.d/+migration-078.fixed.mdnew file mode 100644index 000000000..9b3fe3bdc--- /dev/null+++ b/changelog.d/+migration-078.fixed.md@@ -0,0 +1,11 @@+`RandAugment`, `AutoAugment`, `TrivialAugment` and `AugMix` no longer silently upcast half-precision+batches to `float32`. `OperationBase.forward` β the shared gate every auto-augment op routes through β+moved its `batch_prob` mask to `input.device` but not `input.dtype`, and since `batch_prob` is `float32`+the expression `batch_prob * op(x) + (1 - batch_prob) * x` promoted a `float16` / `bfloat16` input up to+`float32` (the op output and input are both low precision, only the gate was not). `float32` / `float64`+inputs are unaffected and their numeric output is byte-identical. The mask is now cast to `input.dtype`+as well. Partially addresses #4153: this clears the `RuntimeError` behind nineteen of that issue's Linux+CPU half-precision xfail lines for `tests/augmentation/test_auto_operation.py` (all ten `cpu_bfloat16`+entries, nine of the ten `cpu_float16`), which are removed from `testing/half_precision_xfails/`. The+tenth `float16` line is kept: `TestAutoAugment::test_reproduce[cpu-float16]` still fails, now on an+`AssertionError` rather than a `RuntimeError` β a smaller residual, not a fix. (#4210)diff --git a/changelog.d/+migration-079.fixed.md b/changelog.d/+migration-079.fixed.mdnew file mode 100644index 000000000..661af9749--- /dev/null+++ b/changelog.d/+migration-079.fixed.md@@ -0,0 +1,6 @@+Reduce local-feature extraction overhead by accumulating orientation histograms directly,+batching built-in DoG extrema refinement, selecting coordinates before combining response signs,+and using faster activation layouts in KeyNet and CPU HardNet. Detector settings and pretrained+checkpoint formats are preserved. On CUDA the orientation histogram now accumulates with atomics,+so identical inputs can differ at the ulp level between calls unless+`torch.use_deterministic_algorithms(True)` is set. (#4254)diff --git a/changelog.d/+migration-080.fixed.md b/changelog.d/+migration-080.fixed.mdnew file mode 100644index 000000000..3119be60f--- /dev/null+++ b/changelog.d/+migration-080.fixed.md@@ -0,0 +1,35 @@+`quaternion_to_axis_angle` returns the correct gradient at every identity-like quaternion, not only the+positive unit identity `(1, 0, 0, 0)` (#4237). Its zero-vector-part branch used the constant `k = 2.0`,+which is only the `w = 1` case of the true analytic limit `k = 2 / w` (`w` = the real component); every+other identity-like input got a wrong gradient. That included the negative unit identity `(-1, 0, 0, 0)`+-- the same physical rotation as `(1, 0, 0, 0)` under the double cover -- which got the **wrong sign**+(`+2` instead of `-2`), and any non-unit "identity" such as `(2, 0, 0, 0)` (a scale this function+explicitly permits), which got the **wrong magnitude** (`+2` instead of `+1`). This was a genuine+backward-correctness defect, not a missing edge case: a valid unit quaternion could produce the opposite+gradient direction in pose optimization depending purely on which sign of the identity it started from.+The prior regression test for the `#3949` NaN-gradient fix only exercised `w = 1`, the one point where+the wrong constant and the correct formula happen to agree, and so could not have caught this. The+division needed for `2 / w` is guarded at `w = 0` the same way the function's existing `sin_theta`+division already is. That gate is `~pos` -- the mask that actually selects the branch -- and not merely+`w != 0`: `2.0 / t` lowers to `t.reciprocal() * 2`, whose backward is `-grad * result**2`, and for a+rotation just short of a half turn `w` is small but non-zero, so `(1 / w)**2` overflows to `inf` and+meets the exact `0.0` that the unselected branch receives as `0 * inf` -> `nan`. In `float16` that+would have been every rotation within ~0.45 degrees of 180 -- ordinary inputs, not degenerate ones.+The `2 / w` coefficient is also detached, because on the branch that selects it the vector part is+zero, so `d(out)/dw` is exactly zero there and computing it through `-2 / w**2` only reintroduces the+same overflow.++The fully degenerate all-zero quaternion `(0, 0, 0, 0)` -- not a valid rotation -- keeps its+`(0, 0, 0)` forward value. Its gradient there changes, and improves: it was `(0, 2, 2, 2)` on torch+2.14 but already `(nan, 2, 2, 2)` on torch <= 2.9.1, where `atan2(0, 0)`'s derivative with respect to+its second argument -- a `0 / 0` -- returns `nan`. `atan2` is now shielded across that whole masked+branch, which also clears a pre-existing `nan` for a zero vector part whose `w**2` underflows+(`w = 1e-30` in `float32`, `|w| < 2.4e-4` in `float16`). No gradient is analytically correct at a point+with no well-defined limit, so the changed value is not a regression.++The forward value is unaffected everywhere: the `atan2` shield deliberately takes its value from the+unshielded expression, because routing `cos_theta` through `torch.where` hands `atan2` a contiguous+tensor instead of a stride-4 view and can select a different kernel. Verified byte-identical against+the previous implementation over 2000 random inputs in `float64`, `float32`, `float16` and `bfloat16`,+including forced unit, negative-unit, scaled, all-zero and near-half-turn quaternions, with no+non-finite gradient row remaining at any of those dtypes.diff --git a/changelog.d/+migration-081.fixed.md b/changelog.d/+migration-081.fixed.mdnew file mode 100644index 000000000..4a9ee8e24--- /dev/null+++ b/changelog.d/+migration-081.fixed.md@@ -0,0 +1,9 @@+Non-maxima suppression with a window larger than `(7, 7)` no longer builds a `(k*k, 1, k, k)` one-hot+convolution to gather each neighbour into its own channel. On CPU in half precision that convolution+has no vectorized kernel and falls back to `_slow_conv2d_forward`, where it accounted for 99% of a+`MultiResolutionDetector.detect` call. The window minus its centre is now covered by rectangular+`max_pool2d` regions whose full-width slabs share one column pass, costing `O(ky + kx)` taps per+position rather than `ky * kx - 1`, with the centre excluded by construction so the suppression stays+strict. `detect` on a 240x240 image drops from 5757 ms to 27 ms in float16 and from 73.8 ms to 13.8 ms+in float32; a 353x353 `k = 15` suppression drops from 3150 ms to 10.5 ms in float16 and from 42.6 ms to+8.7 ms in float32, and from 12.1 ms to 0.15 ms for 1024x1024 `k = 21` on CUDA. (#4242)diff --git a/changelog.d/+migration-082.fixed.md b/changelog.d/+migration-082.fixed.mdnew file mode 100644index 000000000..e97c602d0--- /dev/null+++ b/changelog.d/+migration-082.fixed.md@@ -0,0 +1,3 @@+`nms2d` accepts a non-square `kernel_size`. It used to raise `RuntimeError: shape '[1, 1, -1, H, W]' is+invalid for input of size ...`, because the neighbourhood kernel was built with its two extents swapped+and the padding was applied to the wrong pair of edges. (#4240, #4242)diff --git a/changelog.d/+migration-083.fixed.md b/changelog.d/+migration-083.fixed.mdnew file mode 100644index 000000000..a94344438--- /dev/null+++ b/changelog.d/+migration-083.fixed.md@@ -0,0 +1,3 @@+`nms3d` accepts any `kernel_size`. Every size other than `(3, 3, 3)`, the one served by a hand-written+branch, used to raise: `_compute_zero_padding3d` defined a `(k - 1) // 2` helper and then returned the+full kernel sizes, so the padded volume did not match the kernel it was convolved with. (#4241, #4242)diff --git a/changelog.d/+migration-084.fixed.md b/changelog.d/+migration-084.fixed.mdnew file mode 100644index 000000000..ebfefd1cf--- /dev/null+++ b/changelog.d/+migration-084.fixed.md@@ -0,0 +1,3 @@+Eager bbox validation now rejects NaN and infinite coordinates: `validate_bbox` returns `False` and+`Boxes.from_tensor(..., validate_boxes=True)` raises `ValueError` for the `xyxy`, `xyxy_plus` and `xywh`+modes, instead of accepting them as valid geometry (closes #4238). (#4243)diff --git a/changelog.d/+migration-085.fixed.md b/changelog.d/+migration-085.fixed.mdnew file mode 100644index 000000000..c00363441--- /dev/null+++ b/changelog.d/+migration-085.fixed.md@@ -0,0 +1,20 @@+`HyNet` and `SOSNet` now run in half precision, on CPU and on GPU, and no longer return NaN for a+degenerate patch (closes #4224). Two defects sat on the same line. On CPU both raised+`NotImplementedError: "avg_pool3d_out_frame" not implemented for 'Half'` (and the `'BFloat16'` spelling):+their final `LocalResponseNorm` is handed a 4-D `(B, C, 1, 1)` tensor, which routes+`torch.nn.functional.local_response_norm` through `avg_pool3d`, and that kernel has no CPU+`float16`/`bfloat16` implementation. Separately, in `float16` on a device where the kernel does exist+(MPS, CUDA), the descriptors came back all-NaN for any patch the network maps to exactly zero: the `eps`+that keeps the normalisation's division defined (`SOSNet.forward`'s `eps`, `HyNet`'s `eps_l2_norm`, both+`1e-10`) is not representable in `float16` and flushes to `0.0`, leaving `0/0`. Every `Conv2d` in `SOSNet`+has `bias=False` and every `BatchNorm2d` is `affine=False`, so any constant patch reaches the+normalisation as exactly zero; `HyNet` reaches it only with `is_bias=False`. `bfloat16` keeps `float32`'s+exponent range, so the guard survives there and only the CPU kernel gap applied to it. Both models now+take that one normalisation step in `float32` for either half-precision input and cast the result back --+a wider lift than the `float16`-only one `kornia.feature.siftdesc` gives its own `1e-10` guards, because+the CPU kernel gap covers both dtypes. `float32` and `float64` take the original expression and are+bitwise unchanged on CPU, CUDA and MPS. Half-precision output does change, by 0.25-2.25 eps, and where it+moves most it moves towards the `float64` reference rather than merely away from NaN: `SOSNet` `float16`+goes from 2.15e-03 to 2.28e-04 of maximum absolute error against a `float64` model carrying the same+weights, and the configurations that do not improve stay within one eps of where they were.+Half-precision descriptors are therefore not comparable bit-for-bit across this release. (#4225)diff --git a/changelog.d/+migration-086.fixed.md b/changelog.d/+migration-086.fixed.mdnew file mode 100644index 000000000..0a27ad4b8--- /dev/null+++ b/changelog.d/+migration-086.fixed.md@@ -0,0 +1,8 @@+The `Import Surface` CI check accepts deliberate public-name removals recorded in the same change.+Edits to `tests/api_surface.json` must correspond to actual export removals and acknowledge only the exact+recorded module/name. Submodule APIs recorded only under an ancestor, and APIs outside the inventory, use+exact module/name entries in `tests/api_surface_removals.json`; only new entries matching a current+`__all__` removal count. Malformed records, deleted inventory module keys, unrelated Python edits, and+acknowledgements staged in earlier changes cannot authorize removals. Both record files trigger the workflow.+The export resolver includes implicit submodule bindings and rejects unsupported dynamic binding expressions+as evidence of removal. Deprecation windows and release notes still apply. (#4190, #4230)diff --git a/changelog.d/+migration-087.fixed.md b/changelog.d/+migration-087.fixed.mdnew file mode 100644index 000000000..c74e3678f--- /dev/null+++ b/changelog.d/+migration-087.fixed.md@@ -0,0 +1,15 @@+`resize` and `rescale` return an empty image for a zero-sized output instead of raising+`ZeroDivisionError` out of the scale-factor computation (#4115). `resize(x, (0, 4))`, `resize(x, 0)`,+`Resize((0, 4))`, and any `rescale` factor that takes a side to zero (`rescale(x, 0.0)`) previously died+in `h / size[0]`; they now return an empty tensor of the requested shape, which is the answer+`warp_affine`, `warp_perspective` and `center_crop` already gave for the same request. The empty result+stays connected to the autograd graph, the way `_empty_warp_output_2d` builds it for the warping ops, so+a batch element that degenerates to a zero-sized output still contributes a zero gradient rather than+detaching.++A degenerate *input* is a different question and is now rejected rather than divided by: resizing a+`(1, 3, 0, 4)` image to a positive size, or with an `int` size at all -- an `int` names one side and takes+the other from an aspect ratio a degenerate input does not have -- raises+`ValueError("Input image size must be positive. Got height=0, width=4.")`, the message the warping ops+already use, instead of the same bare `ZeroDivisionError`. Empty in and empty out is well defined and+still comes back empty. (#4140)diff --git a/changelog.d/+migration-088.fixed.md b/changelog.d/+migration-088.fixed.mdnew file mode 100644index 000000000..16fba0939--- /dev/null+++ b/changelog.d/+migration-088.fixed.md@@ -0,0 +1,3 @@+`validate_bbox` and `validate_bbox3d` flatten rank-4 `(B, N, 4, 2)` / `(B, N, 8, 3)` input with `reshape`+instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an+`expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)diff --git a/changelog.d/+migration-089.fixed.md b/changelog.d/+migration-089.fixed.mdnew file mode 100644index 000000000..2f6589a0c--- /dev/null+++ b/changelog.d/+migration-089.fixed.md@@ -0,0 +1,13 @@+`quaternion_exp_to_log` and `euler_from_quaternion` no longer return `nan`/`inf` gradients at their+respective rotation singularities (#4007). Both differentiate an inverse trig function (`acos`, `asin`)+whose own derivative is unbounded at its domain boundary (`w = +-1`, `sinp = +-1`); `quaternion_exp_to_log`+hits that boundary exactly at the identity quaternion `(1, 0, 0, 0)` -- the standard initialization for+pose optimization -- where the unbounded derivative used to multiply the identity's exactly-zero vector+part into `0 * inf = nan`, and `euler_from_quaternion`'s `pitch` hits it at gimbal lock. Both now guard the+argument fed to the differentiated `acos`/`asin` call away from the boundary while taking the returned+*value* from a detached copy of the real (possibly boundary) argument, so the forward result is unchanged+-- verified byte-identical against the previous implementation over 500 random inputs including several+forced onto the exact boundary -- while the gradient no longer depends on what a given torch version or+backend's own `acos`/`asin` derivative happens to return there. `quaternion_exp_to_log`'s antipode+`(-1, 0, 0, 0)` still returns a large but finite gradient (`~pi/eps`) from an unrelated, pre-existing+division by its clamped (zero) norm; that is unchanged and out of scope here.diff --git a/changelog.d/+migration-090.fixed.md b/changelog.d/+migration-090.fixed.mdnew file mode 100644index 000000000..2a73b6375--- /dev/null+++ b/changelog.d/+migration-090.fixed.md@@ -0,0 +1,3 @@+`infer_bbox_shape` and `bbox_to_mask` now reject rank-4 `(B, N, 4, 2)` inputs with `ShapeError`. Previously,+`N < 3` raised an incidental `IndexError`, while `N >= 3` silently returned `(B, 2)` extents computed from the+wrong vertices. (#4218)diff --git a/changelog.d/+migration-091.fixed.md b/changelog.d/+migration-091.fixed.mdnew file mode 100644index 000000000..566fcaa73--- /dev/null+++ b/changelog.d/+migration-091.fixed.md@@ -0,0 +1,9 @@+Fix `symmetric_transfer_error` returning `NaN` instead of `max_num` for singular homographies.+When `safe_inverse_with_mask` flags an input as non-invertible, the unshielded inverse matrix containing+non-finite values propagated `NaN` through `oneway_transfer_error` and the arithmetic mask+`(there + back) * mask + max_num * (~mask)`, poisoning both the forward error and autograd gradients.+Singular rows are now replaced by the identity *before* the differentiable inverse is taken, so the+gradients with respect to both the correspondences and `H` itself stay finite (zero on the singular+rows), and the final masking uses `torch.where` to cleanly assign `max_num`. Values for invertible+homographies are unchanged; for `squared=False` a singular row now scores `max_num` rather than the+previous `(max_num + eps).sqrt()`, matching the documented contract. (#4203)diff --git a/changelog.d/+migration-092.fixed.md b/changelog.d/+migration-092.fixed.mdnew file mode 100644index 000000000..7e2ffbd85--- /dev/null+++ b/changelog.d/+migration-092.fixed.md@@ -0,0 +1,2 @@+Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global+`torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)diff --git a/changelog.d/+migration-093.fixed.md b/changelog.d/+migration-093.fixed.mdnew file mode 100644index 000000000..1b3d912aa--- /dev/null+++ b/changelog.d/+migration-093.fixed.md@@ -0,0 +1,9 @@+Fix `Boxes.merge` concatenating along the vertex axis instead of the box axis+for unbatched `(N, 4, 2)` input. The old `dim=1` was correct for batched+`(B, N, 4, 2)` data (where dim 1 is the box axis) but wrong for 3-D tensors+(where dim 1 is the vertex dimension); `dim=-3` is correct in both cases and+the behaviour of the batched path is byte-identical. For list-backed inputs,+each batch row is now repacked with its real boxes before all trailing padding,+and the combined per-image padding counts are retained. This makes ``to_tensor``+trim only padding instead of dropping merged boxes or exposing old padding as+real boxes (#4168, #4175).diff --git a/changelog.d/+migration-094.fixed.md b/changelog.d/+migration-094.fixed.mdnew file mode 100644index 000000000..6ed4ba96d--- /dev/null+++ b/changelog.d/+migration-094.fixed.md@@ -0,0 +1,5 @@+`normalize_quaternion` floors a positive `eps` at the smallest positive `float16` subnormal, so its default+`eps=1e-12` remains an active division guard and a zero quaternion returns finite zeros instead of NaNs without+changing non-zero representable `float16` magnitudes. An explicit `eps=0.0` still disables the guard. This also+keeps `Quaternion.normalize`, `quaternion_to_rotation_matrix`, and their downstream pose conversions finite for+that input, matching the existing `float32`, `float64`, and `bfloat16` behavior (#4162).diff --git a/changelog.d/+migration-095.fixed.md b/changelog.d/+migration-095.fixed.mdnew file mode 100644index 000000000..b8db3d2d9--- /dev/null+++ b/changelog.d/+migration-095.fixed.md@@ -0,0 +1,14 @@+`Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8+vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the+classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an+axis-aligned box has such a 4-way tie by construction, where PyTorch's `amin`/`amax` backward splits the+gradient evenly across the tied vertices (`1/4` each): a valid subgradient, usable for optimization, but+one that `torch.autograd.gradcheck`'s central-difference estimate does not match at that exact point --+the same non-uniqueness any reduction has at a kink (`torch.max`, `ReLU`). That mismatch was previously+taken for a genuine gradient bug and `to_tensor` raised `RuntimeError` whenever its input required grad,+unconditionally, including for the common case of a caller who never differentiates through a tie at all+(an oriented, non-axis-aligned box, or a loss that never reaches the tied component). The guard is+removed; the docstring documents the tie behavior instead of calling it a bug. `Boxes` (2D) uses the same+reduction and was never guarded, because an axis-aligned rectangle's ties are always 2-way, where the+`1/2` split happens to numerically coincide with the central-difference estimate -- the same kink, just+invisible to `gradcheck` there.diff --git a/changelog.d/+migration-096.fixed.md b/changelog.d/+migration-096.fixed.mdnew file mode 100644index 000000000..acc95521f--- /dev/null+++ b/changelog.d/+migration-096.fixed.md@@ -0,0 +1,10 @@+The pinned-torch CI legs no longer run against the lockfile's `triton`. `uv sync` installs the locked torch's+dependency set, and each matrix leg then swaps torch alone for a `+cpu` build -- whose wheels declare no `triton` at+all -- so the lockfile's triton survived as an orphan of a torch that was no longer installed. torch guards its+inductor triton path on import availability rather than on version, so it dispatched onto that orphan and the+`2.6.0` leg died in `from triton.backends.compiler import AttrsDescriptor` on 32 dynamo and export tests, having+never been green. The install step now drops sidecar packages the installed torch does not declare, and the+verification step asserts the whole environment against that torch (`.github/scripts/check_torch_env.py`) so a+mis-provisioned venv fails at setup instead of as a wall of unrelated-looking test failures. The five+`tests/core/test_small_linalg.py` ONNX cases the import error was masking now export with `external_data=False`,+which torch 2.6's dynamo exporter requires when the destination is a `BytesIO`. (#4199, #4200)diff --git a/changelog.d/+migration-097.fixed.md b/changelog.d/+migration-097.fixed.mdnew file mode 100644index 000000000..ee59b5893--- /dev/null+++ b/changelog.d/+migration-097.fixed.md@@ -0,0 +1,10 @@+`find_homography_dlt(..., solver="lu")` now solves the minimal four-point system with an adaptive+homogeneous gauge instead of applying LU to its singular normal matrix. This is the estimator+`RANSAC(model_type="homography")` calls for every minimal sample, so homography RANSAC results+change on every platform, not only where the old formulation broke down: over 2048 minimal+samples the median transfer residual drops from 2.3e-5 to 1.9e-6 and the worst case from 4.2e+5+to 4.5e+2. It also fixes the all-NaN homographies seen for a four-point sample on Windows with+PyTorch 2.14, and removes the corresponding CPU half-precision known failures. A four-point+sample containing a zero weight now returns a finite homography instead of NaN. Samples of five+or more points keep the previous normal-equation formulation and are numerically unchanged.+(#4197)diff --git a/changelog.d/+migration-098.fixed.md b/changelog.d/+migration-098.fixed.mdnew file mode 100644index 000000000..4618c4ea0--- /dev/null+++ b/changelog.d/+migration-098.fixed.md@@ -0,0 +1,3 @@+`add_weighted` now keeps Python scalar weights in operator math precision instead of rounding them to the input+dtype before arithmetic. This improves `float16` and `bfloat16` accuracy and makes fractional scalar weights on+integer inputs produce the correctly promoted floating-point result instead of being truncated. (#4154)diff --git a/changelog.d/+migration-099.fixed.md b/changelog.d/+migration-099.fixed.mdnew file mode 100644index 000000000..c387b001c--- /dev/null+++ b/changelog.d/+migration-099.fixed.md@@ -0,0 +1,14 @@+`distance_transform` no longer silently returns a wrong or all-zero result when its `exp(-dist/h)` kernel+underflows (#4152). The kernel's axis-aligned tap, at distance `kernel_size // 2` along a single axis,+underflowing to exactly zero -- reachable from the documented default `h=0.35` at `kernel_size >= 15` in+`float16` -- used to make the convolution silently drop it, returning a plausible-looking but wrong distance+field or, with a smaller `h`, an all-zero one. Two changes: `float16`/`bfloat16` inputs now run the cascade in+`float32` and cast the result back (the default `h=0.35` case is fixed by this alone, matching `float32`'s own+working range); and an `h`/`kernel_size`/dtype combination whose axis-aligned tap still underflows+`torch.finfo(dtype).tiny` now raises instead of guessing. This also catches a case that is not itself+numerically wrong on CPU (`h=0.01` at `kernel_size=3` in `float32` tracks the analytic reference to ~2e-4,+carried through the subnormal range) but where MPS flushes subnormals to zero while CPU does not, so the same+call used to silently disagree across backends; raising there rules out that disagreement rather than trusting+which backend a caller happens to run on. Concretely, at the documented default `h=0.35` in `float32`,+`kernel_size >= 63` now raises: CPU used to return a usable-looking answer there while MPS silently returned+something else for the same call.diff --git a/changelog.d/+migration-100.fixed.md b/changelog.d/+migration-100.fixed.mdnew file mode 100644index 000000000..92fe13bb8--- /dev/null+++ b/changelog.d/+migration-100.fixed.md@@ -0,0 +1,2 @@+Fix `Boxes3D.from_tensor(..., mode="xyzwhd")` to preserve width, height, and depth field order for asymmetric+boxes. (#4189)diff --git a/changelog.d/+migration-101.fixed.md b/changelog.d/+migration-101.fixed.mdnew file mode 100644index 000000000..74615e29c--- /dev/null+++ b/changelog.d/+migration-101.fixed.md@@ -0,0 +1,4 @@+`RandomTransplantation` and `RandomTransplantation3D` transplanted nothing on MPS when no `excluded_labels`+were given: PyTorch's MPS backend evaluates `all()` over the empty excluded-label axis to an undefined value,+usually `False`, so every donor label was filtered out and the output equalled the input. The filter is now skipped when there is+nothing to exclude. (#4160)diff --git a/changelog.d/+migration-102.fixed.md b/changelog.d/+migration-102.fixed.mdnew file mode 100644index 000000000..5ab93621a--- /dev/null+++ b/changelog.d/+migration-102.fixed.md@@ -0,0 +1,3 @@+`VisualPrompter.predict()` called without any prompt (the "run the prediction without prompts" example on the+Segment Anything page) raised `TypeError: object of type 'NoneType' has no len()` from the prompt augmentation+container; it now predicts from the image embedding alone, as documented. (#4178)diff --git a/changelog.d/+migration-103.fixed.md b/changelog.d/+migration-103.fixed.mdnew file mode 100644index 000000000..ccbb16f14--- /dev/null+++ b/changelog.d/+migration-103.fixed.md@@ -0,0 +1,3 @@+Preserve empty color tensors on accelerator backends instead of asking `reshape` to infer an ambiguous batch+dimension. This lets the YUV420 and YUV422 empty-input conversions return their documented empty RGB output on+MPS, matching CPU behavior (#4185).diff --git a/changelog.d/+migration-104.fixed.md b/changelog.d/+migration-104.fixed.mdnew file mode 100644index 000000000..0be751ad0--- /dev/null+++ b/changelog.d/+migration-104.fixed.md@@ -0,0 +1,5 @@+Follow-up fixes to the documentation revamp (#4155): the landing page's filtering card quoted the combined+`filters`/`color`/`enhance`/`morphology` count next to a `kornia.filters` label, the "Why Kornia?" hero carousel+resumed after a visitor picked a tab, the Community page linked to the now-unregistered `librecv.org`, and the+GPU page promised CUDA measurements the committed benchmark runs do not yet contain. `pydata-sphinx-theme` is now+version-bounded, since the site's CSS and JS target theme internals. (#4173)diff --git a/changelog.d/+migration-105.fixed.md b/changelog.d/+migration-105.fixed.mdnew file mode 100644index 000000000..832df68e6--- /dev/null+++ b/changelog.d/+migration-105.fixed.md@@ -0,0 +1,7 @@+Reset an automatic augmentation policy's cached transformation matrix before applying it again, both for a+sub-policy inside `TrivialAugment`, `RandAugment` and `AutoAugment` and for those policies nested inside+`AugmentationSequential`. Consecutive calls that selected the same geometric policy could transform the input with+the latest parameters while exposing the previous call's matrix through `transform_matrix`, the sub-policy+accumulated one matrix per call for the lifetime of the module, and a nested policy never recorded its parameters+or matrix at all. `transform_matrix` on a policy that has not run yet now returns `None` instead of raising+`AttributeError` (#4171).diff --git a/changelog.d/+migration-106.fixed.md b/changelog.d/+migration-106.fixed.mdnew file mode 100644index 000000000..7b656dee3--- /dev/null+++ b/changelog.d/+migration-106.fixed.md@@ -0,0 +1,11 @@+`MultiResolutionDetector.detect` apportions `num_features` across pyramid levels with largest-remainder+(Hamilton) apportionment instead of flooring each level's fractional share independently (#4101). The floors+used to discard every fractional part, so a small `num_features` could round the whole apportionment down: with+the default configuration the six shares are `0.508 .. 0.016`, and every level but the finest lost its entire+quota to truncation, so the detector effectively searched a single scale. The shortfall -- `num_features` minus+the sum of the floors -- is now handed to the levels with the largest fractional remainder, one slot each, so+the quotas always sum to exactly `num_features` and stay spread across scales. #4098's narrower `num_features=1`+fallback, which handed the request's one slot to the largest-share level when every quota floored to zero, is+the special case where the shortfall equals `num_features` and is superseded by the general apportionment.+The apportionment was then removed again by #4222, inside this same unreleased window, so no release+ever carries it; the `num_features=1` behaviour it fixed still holds.diff --git a/changelog.d/+migration-107.fixed.md b/changelog.d/+migration-107.fixed.mdnew file mode 100644index 000000000..d824aa3a6--- /dev/null+++ b/changelog.d/+migration-107.fixed.md@@ -0,0 +1,14 @@+`MultiResolutionDetector.detect` now returns the `num_features` highest responses in the image (#4222). Each+pyramid level used to be asked only for its own share of the budget, so a level could contribute at most+`quotas[0]` (the upscaled level) or `sum(quotas[: i + 1 + up_levels])` (pyramid level `i`) -- both well under+`num_features` for the finer levels. When an image's strongest maxima concentrated on one level, which is the+common case rather than a corner case, the excess was never requested and so could not be ranked in by the+final global `topk`: the detector silently returned something other than the top-k, and the sorted responses of+`detect(k)` were not a prefix of those of `detect(k')`. Every level is now searched for `num_features` candidates, which is exactly sufficient+because the detections a level contributes to the global top-k are that level's own strongest. The per-level+apportionment, including #4101's largest-remainder rounding, is removed with it. This changes which keypoints+are returned for a given image: callers get strictly better-ranked detections, and any result that depended on+the old per-level spread will differ. The prefix is on the sorted responses, not on which detection carries a+given response: `topk` breaks a tie by position, so exactly equal maxima can come back in a different order for+a different `num_features`. It carries about 1.2x the candidates through the concatenation, which is not+measurable next to the response function and the non-maxima suppression.diff --git a/changelog.d/+migration-108.fixed.md b/changelog.d/+migration-108.fixed.mdnew file mode 100644index 000000000..715dd26ed--- /dev/null+++ b/changelog.d/+migration-108.fixed.md@@ -0,0 +1,5 @@+Make YUV and XYZ transformations compute integer inputs in `float32` instead of truncating their kernels, and+preserve directly constructed `float64` coefficients. This makes `rgb_to_yuv(uint8)` return `float32` on the+input's original 0--255 scale, fixes signed-integer YUV results, and removes the existing float32 coefficient loss+from float64 XYZ conversions. The two private linear-transformation helpers are now one implementation, whose CPU+path uses its dtype/device-aligned compute operands (#4053).diff --git a/changelog.d/+migration-109.fixed.md b/changelog.d/+migration-109.fixed.mdnew file mode 100644index 000000000..06343e682--- /dev/null+++ b/changelog.d/+migration-109.fixed.md@@ -0,0 +1,6 @@+Fix 2-D, 3-D, and mix augmentations raising a cross-device `RuntimeError` when their random parameters are generated+on the default CPU device and their input is on MPS or CUDA (#4164). Since #3722, four branchless `torch.where`+blends used the CPU `batch_prob` mask directly with accelerator outputs or transformation matrices. The selection+mask now moves to the output device at each blend boundary, preserving CPU random-number generation and the+ONNX/fullgraph-friendly blend. Calling `augmentation(x_accelerator)` therefore works again without first moving the+augmentation module or its RNG to the accelerator (#4151).diff --git a/changelog.d/+migration-110.fixed.md b/changelog.d/+migration-110.fixed.mdnew file mode 100644index 000000000..86dc56b0a--- /dev/null+++ b/changelog.d/+migration-110.fixed.md@@ -0,0 +1,11 @@+Keep `extract_patches_simple` and `extract_patches_from_pyramid` off a broken reduced-precision CPU kernel: for a+`float16`/`bfloat16` CPU image, the `grid_sample` kernels in torch <= 2.9 read out of bounds when a rotated patch+straddles the image border and return NaN or garbage values far outside the image's range. Both extractors now+sample reduced-precision inputs in `float32` on every device and cast the patches back. This fixes the CPU kernel+bug and avoids normalized-coordinate precision loss on large images; half-precision patches change on every+backend, with the CUDA cost described under **Breaking changes**. Both extractors also replace their+per-image Python loop with a folded batched `grid_sample` over a `(B, N*PS, PS, 2)` grid, split along `N` when+needed to bound its workspace. Both forms compile under `fullgraph=True`, but the loop was unrolled at trace time+into one `grid_sample` per batch element, so the graph grew with the batch and was recompiled for every new batch+size: tracing `extract_patches_simple` over batches of 2, 3, 5 and 7 built four graphs of 2/3/5/7 `grid_sample`+nodes before and builds two graphs with one node each now.diff --git a/changelog.d/+migration-111.fixed.md b/changelog.d/+migration-111.fixed.mdnew file mode 100644index 000000000..bc3192e92--- /dev/null+++ b/changelog.d/+migration-111.fixed.md@@ -0,0 +1,7 @@+`extract_patches_simple` and `extract_patches_from_pyramid` return an all-zero patch and a zero LAF gradient for a+non-finite LAF frame instead of handing `grid_sample` an invalid grid. A frame holding a NaN or an infinity+anywhere -- including only in its center -- is detected and sanitized before any grid arithmetic, and finite frames+in the same batch are untouched. Such a frame previously produced a finite-looking border-sampled patch, and its+backward pass could terminate the process inside torch's CPU `grid_sampler_2d_backward` kernel with+`padding_mode="border"`; a training-time detector that emits a degenerate LAF hits exactly that path through+`LAFOrienter`, `LAFAffNetShapeEstimator` and `LAFDescriptor`.diff --git a/changelog.d/+migration-112.fixed.md b/changelog.d/+migration-112.fixed.mdnew file mode 100644index 000000000..60876bad4--- /dev/null+++ b/changelog.d/+migration-112.fixed.md@@ -0,0 +1,5 @@+`normalize_laf`, `denormalize_laf` and `generate_patch_grid_from_normalized_LAF` count a singleton image axis as+one pixel of extent instead of dividing by `size - 1 == 0`. `normalize_laf` raised `ZeroDivisionError` for a+1-pixel-wide or 1-pixel-tall image -- and with it both patch extractors on their default+`normalize_lafs_before_extraction=True` path -- while `denormalize_laf` silently collapsed every LAF to zero.+The conversions are now finite and round-trip, and both extractors return finite patches for such an image.diff --git a/changelog.d/+migration-113.fixed.md b/changelog.d/+migration-113.fixed.mdnew file mode 100644index 000000000..5637638c2--- /dev/null+++ b/changelog.d/+migration-113.fixed.md@@ -0,0 +1,14 @@+Replace the batched `torch.inverse` in `ellipse_to_laf` with the closed-form inverse of its lower-triangular+2x2 matrix. Results agree with the previous implementation to ~1.6e-7 relative in `float32` (machine epsilon in+`float64`). Reproducible numbers via `benchmarks/feature/ellipse_to_laf.py` (float32, N=1e3..1e5, torch 2.9.1,+Linux/WSL2, base `2009933e`): throughput improves ~2.4-5.3x eager / ~3-6.5x compiled on CPU (i7-14700K) and+~1.4-1.7x eager / ~4.2-5.5x compiled on CUDA (RTX 4090). The largest win is MPS, where the batched inverse hit a+pathological `linalg` path, emitted a deprecated-resize `UserWarning` on every call, and failed to `torch.compile`+(~1500x once measured ad hoc at N=20000 on Apple Silicon; rerun the benchmark there for a citable number). The+function now compiles with `fullgraph=True` on every backend and accepts `float16`/`bfloat16` on CPU, where the+raw `.inverse()` call raised for low-precision dtypes (`_torch_inverse_cast` would have lifted that restriction+too; the closed form is for speed). The off-diagonal divides `a21 = b / (a11 + a22)` by the product of the+diagonal square roots, which can neither overflow nor round to zero: every ordering of the reciprocal product+overflows to `inf` (or flushes a representable value to `0`) on a sufficiently lopsided or subnormal diagonal,+and when that product is subnormal the division loses precision but never corrupts a representable result to a+zero, `inf`, or `nan`.diff --git a/changelog.d/+migration-114.fixed.md b/changelog.d/+migration-114.fixed.mdnew file mode 100644index 000000000..e6d31d88a--- /dev/null+++ b/changelog.d/+migration-114.fixed.md@@ -0,0 +1,13 @@+Drop the constant homogeneous row from `laf_to_boundary_points`. The function appended a `[0, 0, 1]` row to every+LAF so that it could divide the result by a homogeneous coordinate that is always exactly `1`; it now multiplies+by the `(2, 3)` LAF directly, and moves its 3-column basis to the LAF's device and dtype before broadcasting it+instead of after (the previous order materialized, and on an accelerator transferred, one copy per LAF -- ~12 MiB+per call at `N = 20000` for a tensor with `n_pts` distinct rows). The win is not the transfer: torch's CPU+batched gemm falls off a fast path at the third row, so `bmm` on a `(B, 3, 3)` operand costs 23x a `(B, 2, 3)` one+for 1.5x the arithmetic. Quiet back-to-back A/B against base `8db1499a` via `benchmarks/feature/laf_ops.py`+(Apple M1, torch 2.14.0, 4 threads, B=1 N=20000): `laf_to_boundary_points` 1.07M -> 29.6M LAFs/s eager on CPU and+1.77M -> 4.27M on MPS; `laf_is_inside_image`, which calls it with `n_pts=12` on every detector forward,+9.75M -> 29.0M on CPU and 2.70M -> 8.53M on MPS. Results are bitwise identical on CPU `float16` and `bfloat16`+and shift by at most 1.42 machine epsilon elsewhere, relative to the largest coordinate of the call -- the two+gemm shapes round differently. Mean error against a `float64` reference is slightly lower than before, and+`laf_is_inside_image`'s boolean masks were bitwise identical across a 126-case device/dtype/shape sweep. (#4217)diff --git a/changelog.d/+migration-115.fixed.md b/changelog.d/+migration-115.fixed.mdnew file mode 100644index 000000000..2d3eb2309--- /dev/null+++ b/changelog.d/+migration-115.fixed.md@@ -0,0 +1,13 @@+Make `load_pointcloud_ply` and `load_pointcloud_ply_binary` parse the PLY header instead of skipping a fixed+number of lines. Both loaders skipped `header_size=8` lines and read everything after them as `x y z` triples, so a+minimal PLY file (seven header lines, no `comment`) lost its first point to a header line -- the binary reader+returned header bytes decoded as doubles -- and any file with extra vertex properties (normals, colours) or a+`face` element after the vertices was rejected or misread. The readers now stop at `end_header`, take the point+count from `element vertex N`, select `x`, `y`, `z` by property name whatever their scalar type, skip trailing+elements, and read big-endian payloads. `header_size` is deprecated and ignored (a `DeprecationWarning` is+emitted when it is passed). Files without a proper PLY header, which the old line-skipping loader could read+by accident, are now rejected with a `ValueError`, and so is a file that declares a `list` property among the+vertex properties -- a list has no statically known length, so the columns after it cannot be located. The+binary reader additionally rejects a `list` property in an element that *precedes* the vertices, whose byte+length it would have to know to reach the vertex data; the ASCII reader reads such a file, since every ASCII+element instance is one line whatever it contains.diff --git a/changelog.d/+migration-116.fixed.md b/changelog.d/+migration-116.fixed.mdnew file mode 100644index 000000000..39982c648--- /dev/null+++ b/changelog.d/+migration-116.fixed.md@@ -0,0 +1,10 @@+Make `guided_blur` / `GuidedBlur` work in `float16` and `bfloat16` when the guidance has more than one channel.+Multi-channel guidance solves a per-pixel `C x C` system, and `torch.linalg.solve` has no half-precision LU+kernel, so every such call failed: on CPU with `NotImplementedError: "lu_cpu" not implemented for 'Half'`, and on+MPS with a hard `Only MPSDataTypeFloat32 is supported` assertion that aborted the process rather than raising.+The system is now solved in `float32` and cast back. A tensor `eps` also takes part in dtype promotion, so+the common `eps=torch.tensor(0.1)` (float32) widened the matrix past the right-hand side and made `solve`+reject the pair; both operands are now solved in one dtype. Single-channel guidance never reached the solver+and is unaffected. `float32` and `float64` results are bit-identical to before, and the op still compiles with+`fullgraph=True` in one graph. This takes `tests/filters/test_guided.py` from 98 failed / 67 passed to+169 passed under `--dtype=float16,bfloat16`.diff --git a/changelog.d/+migration-117.fixed.md b/changelog.d/+migration-117.fixed.mdnew file mode 100644index 000000000..424abad5d--- /dev/null+++ b/changelog.d/+migration-117.fixed.md@@ -0,0 +1,7 @@+Raise `NotImplementedError` instead of `RuntimeError` for an integral `src` on the empty-`dsize` paths of+`warp_affine`, `warp_perspective`, `remap`, `warp_affine3d` and `warp_perspective3d`, matching what the non-empty+path already raises from `grid_sample` (#4031). The degenerate path had its own explicit guard that fired first+with a different exception type, so the exception a caller saw for the same invalid input depended on whether+`dsize` had a zero dimension. The message is unchanged. `NotImplementedError` derives from `RuntimeError`, so+`except RuntimeError` around these functions still catches it; only code matching on the exact type sees a+difference.diff --git a/changelog.d/+migration-118.fixed.md b/changelog.d/+migration-118.fixed.mdnew file mode 100644index 000000000..f905e34bd--- /dev/null+++ b/changelog.d/+migration-118.fixed.md@@ -0,0 +1,9 @@+Validate the chroma plane height in `yuv422_to_rgb`, so a chroma plane whose height does not match the luma now+raises `ShapeError` instead of reaching `torch.cat` and dying there with a bare `RuntimeError` (#4050). 4:2:2+subsamples width only, so chroma keeps the full luma height; the guard checked only the width ratio, where the+4:2:0 twin `yuv420_to_rgb` checks both axes. This is observable to callers on the error path: `ShapeError` derives+from `BaseError`, not `RuntimeError`, so code catching `RuntimeError` around `yuv422_to_rgb` to handle a malformed+chroma plane will stop catching it. No previously working input changes behaviour β `torch.cat` already rejected+every mismatched height. A zero-width chroma plane whose height *also* differs now reaches the guard, since the new+clause short-circuits the width division; the matching-height case still raises+`ZeroDivisionError` and remains open as #4056.diff --git a/changelog.d/+migration-119.fixed.md b/changelog.d/+migration-119.fixed.mdnew file mode 100644index 000000000..bd2ac9464--- /dev/null+++ b/changelog.d/+migration-119.fixed.md@@ -0,0 +1,10 @@+Make `yuv_to_rgb` the exact inverse of `rgb_to_yuv`, so an RGB β YUV β RGB round trip is now limited only by the+input dtype instead of losing up to `1.36e-3` (in B, at `rgb = (1, 1, 0)`) at every precision, `float64` included+(#4044). The inverse kernel was a separately rounded copy of the published BT.470-5 M/PAL inverse relations rather+than the inverse of the rounded forward kernel kornia actually ships, and one of its literals β `2.029`, where the+inverse of kornia's forward kernel is `2.03199968` β carried most of the error. `yuv_to_rgb` output therefore moves+by up to `1.23e-4` in R, `9.13e-4` in G and `1.60e-3` in B over the documented YUV domain, and `yuv420_to_rgb` and+`yuv422_to_rgb` move with it. The forward direction (`rgb_to_yuv`, `rgb_to_yuv420`, `rgb_to_yuv422`) is unchanged.+Agreement of the inverse with the standard's own relations improves overall, from `1.54e-3` to `5.24e-4`, though R+alone moves the other way (`1.54e-4` to `2.77e-4`). The `.. warning::` blocks that documented the defect on the six+affected functions and classes are gone.diff --git a/changelog.d/+migration-120.fixed.md b/changelog.d/+migration-120.fixed.mdnew file mode 100644index 000000000..9fcdfbdd4--- /dev/null+++ b/changelog.d/+migration-120.fixed.md@@ -0,0 +1,11 @@+Fix the inverted `SigLip2` attention-mask polarity, so every call that passes an `attention_mask` changes (#4043).+All three mask branches of `SigLip2Attention` (2-D `(B, N)`, 3-D `(B, N, N)` and 4-D `(B, 1, N, N)`) negated the+mask before handing it to `torch.nn.functional.scaled_dot_product_attention`, whose boolean form reads `True` as+*attend*, not as *mask out*. Every position the caller asked to attend to was masked out and every padded position+attended to, so an all-ones mask left every query row fully masked. The symptom is version-dependent because a+fully masked row returns `0` from SDPA on PyTorch 2.5 and later and `nan` on PyTorch 2.4 and earlier:+`SigLip2.get_text_features(..., attention_mask=...)` has been returning a zeroed attention output on current+PyTorch and `nan` text features on the declared `torch>=2.0` floor. 2-D padding masks are now broadcast over the+key axis only, matching `SiglipTextTransformer.create_bidirectional_mask` in Hugging Face `transformers`, so a+partially padded sequence no longer produces a fully masked row. A row whose mask is entirely zero β an empty+caption in a batch β is still fully masked and still follows the SDPA behavior above.diff --git a/changelog.d/+migration-121.fixed.md b/changelog.d/+migration-121.fixed.mdnew file mode 100644index 000000000..b66782295--- /dev/null+++ b/changelog.d/+migration-121.fixed.md@@ -0,0 +1,5 @@+Fix `find_essential` and `run_5point` raising `TypeError: all() received an invalid combination of arguments` on+PyTorch before 2.2 (#4043). `run_5point`, `_solve_2x2_tikhonov_safe` and the scripted Nister helper each reduced+over two axes at once with `Tensor.any(dim=(-2, -1))` / `Tensor.all(dim=(-1, -2))`, and multi-dimension `any`/`all`+only landed in PyTorch 2.2, so the whole five-point solver was unusable on the declared `torch>=2.0` floor. The+reductions now flatten the two trailing axes first, which is equivalent on every version.diff --git a/changelog.d/+migration-122.fixed.md b/changelog.d/+migration-122.fixed.mdnew file mode 100644index 000000000..49c18014d--- /dev/null+++ b/changelog.d/+migration-122.fixed.md@@ -0,0 +1,5 @@+Fix `torch.jit.script` of `rgb_to_yuv`, `yuv_to_rgb`, `rgb_to_xyz` and `xyz_to_rgb` on older PyTorch (#4043). Their+shared `kornia.color.utils._apply_linear_transformation` helper annotated its optional argument with the PEP 604+`torch.Tensor | None` form, which the TorchScript compiler on the declared floor does not accept (reproduced on+PyTorch 2.1.2, while PyTorch 2.9.1 compiles it), so scripting any of the four conversions failed. The annotation is+`Optional[torch.Tensor]` now, which every supported version accepts.diff --git a/changelog.d/+migration-123.fixed.md b/changelog.d/+migration-123.fixed.mdnew file mode 100644index 000000000..55c5c5e36--- /dev/null+++ b/changelog.d/+migration-123.fixed.md@@ -0,0 +1,17 @@+Define singleton pixel axes at normalized center, reject non-positive normalization sizes, preserve empty warp+destinations, and deprecate the now-unused `eps` normalization parameters (#4006). The four+`{de,}normalize_pixel_coordinates{,3d}` helpers and `normal_transform_pixel{,3d}` now derive their scale from the+size directly instead of rounding the size into the coordinate dtype first, so results at non-degenerate sizes can+move toward the exact value: by up to one ulp in `float32`/`float64`, but materially more in `float16`/`bfloat16`,+where the old code could not represent the size at all (`denormalize_pixel_coordinates` at `bfloat16` and size 3000+returns 1496 where it returned 1504).++A singleton axis previously divided by zero (or by the `eps` substituted for it), so the change is not confined to+those helpers: it reaches every operation that normalizes a coordinate frame with a size-1 dimension.+`create_meshgrid(1, 4, normalized_coordinates=True)` returned `nan` in the singleton component and now returns `0`;+`warp_perspective`, `crop_by_transform_mat`, `homography_warp` and `warp_image_tps` onto a 1-pixel-high destination+returned all-`nan` and now return the finite row the 2-pixel control produces; `spatial_soft_argmax2d` and+`spatial_expectation2d` on a 1-pixel-high input returned `nan` and now return `0`; and `conv_soft_argmax2d`,+`conv_soft_argmax3d` and their `ConvSoftArgmax*` module forms shift by one normalized unit when a kernel or input+axis is `1` (`conv_soft_argmax2d` with a `(3, 1)` kernel returned `[-1.6667, -1.0, ...]` and now returns+`[-1.0, -0.3333, ...]`).diff --git a/changelog.d/+migration-124.fixed.md b/changelog.d/+migration-124.fixed.mdnew file mode 100644index 000000000..a4f6eb140--- /dev/null+++ b/changelog.d/+migration-124.fixed.md@@ -0,0 +1,18 @@+Restore the YUV test coverage that #3539 deleted, and fix the `kornia.color` YUV docstring examples (#4045).+`rgb_to_yuv422` and `yuv422_to_rgb` both documented an example that called the 4:2:0 function instead of+themselves, so a reader copying either got the wrong conversion and the wrong chroma shapes; several other+examples stated a shape in a trailing comment that disagreed with what the function returns+(`RgbToYuv420` said `2x1x2x3` for a `(2, 2, 2, 3)` chroma plane). Every example in `kornia/color/yuv.py` now+asserts its output shape as a doctest instead of stating it in a comment. The 4:2:2 docstrings also claimed+the input only had to be divisible by 2 "vertical" while the guard rejects odd height *and* odd width, so a+reader padding one axis hit a `ShapeError`, and `yuv422_to_rgb` labelled its chroma argument "UV (luma)".+The four `ShapeError` messages those guards raise said "evenly disible by 2" and now say "divisible", as do+the two identical messages in `kornia/color/raw.py`. `yuv422_to_rgb`/`Yuv422ToRgb` also gained a+`.. warning::` naming a known defect: they validate only the chroma *width*, so a wrong chroma height+surfaces as a bare `RuntimeError` from `torch.cat` (#4050). The same entry gave every YUV-to-RGB form a+second warning, for the round trip that #4044 has since fixed; those blocks are gone, see the entry+above. On the test side, both gradcheck skips now cover the XLA/TPU fixture as well as MPS, since XLA+lowers a float64 request to float32, where gradcheck's default `eps=1e-6`+makes the numerical Jacobian invalid: the name-based marker in `conftest.py` for tests called `*gradcheck*`,+and the device guard in `BaseTester.gradcheck` for the six callers named something else. No runtime+behavior changed.diff --git a/changelog.d/+migration-125.fixed.md b/changelog.d/+migration-125.fixed.mdnew file mode 100644index 000000000..2f129405b--- /dev/null+++ b/changelog.d/+migration-125.fixed.md@@ -0,0 +1,7 @@+Fix `SIFTDescriptor.gk`, `PatchDominantGradientOrientation.weighting` and `PatchAffineShapeEstimator.weighting`+being plain attributes, so `nn.Module.to()` left them behind on the original device and dtype (#4069). They are+now non-persistent buffers: `.to()`, `.cuda()`, `.half()` and friends move them, and because they are fully+determined by `patch_size` they stay out of `state_dict()`, so existing checkpoints still load with+`strict=True`. The three `forward` methods also cast into a local instead of rebinding the attribute, so a call+no longer leaves the module's kernel in whatever dtype and device the last input happened to have. Numerical+output is unchanged: the kernels were already cast to the input's dtype and device inside `forward`.diff --git a/changelog.d/+migration-126.fixed.md b/changelog.d/+migration-126.fixed.mdnew file mode 100644index 000000000..6b254e4d7--- /dev/null+++ b/changelog.d/+migration-126.fixed.md@@ -0,0 +1,11 @@+Fix patch extraction on MPS returning darkened patches for any LAF that touches an image border (#4063).+MPS has no `padding_mode="border"` for `torch.nn.functional.grid_sample`, so `extract_patches_simple` and+`extract_patches_from_pyramid` emulate it with zero padding and a clamped grid. The clamp was `grid.clamp(-1, 1)`,+but with `align_corners=False` normalized coordinate `Β±1` is the outer *edge* of the border pixel, not its center,+so bilinear sampling blended the border pixel with the zero padding and returned roughly half its value. The grid+is now clamped to the outermost pixel centers, `Β±(1 - 1/size)` per axis, which reproduces `padding_mode="border"`+exactly. On a patch overlapping the image corner the maximum deviation from the CPU result drops from `0.395` to+`2.5e-6` on a `[0, 1]` image, with 64.7% of the patch's pixels previously off by more than `1e-3`. Every descriptor+built on these patches β `get_laf_descriptors`, `LAFDescriptor`, `SIFTFeature`, `KeyNetAffNetHardNet` and the rest β+moves with them for keypoints near the border. The CPU and CUDA paths never took this branch and are byte-identical+to before.diff --git a/changelog.d/+migration-127.fixed.md b/changelog.d/+migration-127.fixed.mdnew file mode 100644index 000000000..b7e38c135--- /dev/null+++ b/changelog.d/+migration-127.fixed.md@@ -0,0 +1,15 @@+Fix `match_fginn`'s geometric consistency check comparing every query's candidates against **query 0**'s+candidates instead of against the query's own 1st nearest neighbor, which changes every `match_fginn` and+`GeometryAwareDescriptorMatcher("fginn")` result -- the latter being that class's *default* mode (#4062). The distance+`kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[0, k]] ||` was measured from a slice of dim 0 that broadcast query 0's+whole candidate list over the batch; it is now `candidates_xy[:, 0:1]`, i.e.+`kdist[i, k] = || xy2[idx[i, k]] - xy2[idx[i, 0]] ||`. Three consequences disappear with it. The geometric term+was inert -- an unrelated query's candidates are almost always farther apart than `spatial_th`, so nothing was+penalized and the raw 2nd nearest neighbor was used, making `match_fginn` behave as `match_snn`: on a 300x300+descriptor set with planted near-duplicates, 15 of the 15 matches shared with `match_snn` had an identical ratio+before and 14 of 15 after. Query 0 always matched, since `candidates_xy[0] - candidates_xy[0]` is identically zero,+so all of its candidates were penalized and its ratio collapsed to ~0. And a query's ratio depended on the other+queries in the batch: with only query 0 changed, one query's ratio moved between `0.9005` and `2.8e-08`. The seven+existing FGINN tests pass unchanged on both sides, which is how this survived; two tests that discriminate it were+added. `match_fginn`'s docstring now also records the saturation corner, where every candidate falls within+`spatial_th` of the 1st nearest neighbor, the ratio collapses towards zero and the match is accepted.diff --git a/changelog.d/+migration-128.fixed.md b/changelog.d/+migration-128.fixed.mdnew file mode 100644index 000000000..284cc738c--- /dev/null+++ b/changelog.d/+migration-128.fixed.md@@ -0,0 +1,10 @@+Fix `DenseSIFTDescriptor` registering a process-global cached tensor as its `_poolingconv_weight` buffer, so that+one instance's `load_state_dict` silently corrupted every other instance and every instance constructed later+(#4068). `_get_reshape_kernel` memoises `torch.eye(numel)` per `numel` and used to return a *view* of the cached+tensor; `.float()` on an already-float tensor returns the same object, so no copy happened between the cache and+the buffer, and `load_state_dict` copies into buffers in place. Loading a checkpoint into one `DenseSIFTDescriptor`+therefore overwrote the shared identity matrix, with no error raised and every descriptor built from it wrong from+then on. The cache is removed rather than made safe: cloning on the way out is what a safe cache requires, and a+clone costs more than rebuilding the identity at every size measured (2.6 us against 2.0 us at the default+`numel = 8 * 4 * 4`; 3.9 ms against 2.8 ms at the former 4096 bound, which also retained 67 MB for the lifetime of+the process). Descriptor output is byte-identical to before.diff --git a/changelog.d/+migration-129.fixed.md b/changelog.d/+migration-129.fixed.mdnew file mode 100644index 000000000..7ced7361c--- /dev/null+++ b/changelog.d/+migration-129.fixed.md@@ -0,0 +1,14 @@+Fix `laf_is_inside_image` treating the image extent as `(w, h)` rather than `(w - 1, h - 1)`, which made its+bounds asymmetric: the lower bound rejected anything left of `x = 0`, but the upper bound accepted `x = w`, a+full pixel past the last valid column `w - 1` (#4064). Valid pixel coordinates run `0 .. w-1` and `0 .. h-1` --+the convention `get_laf_center` documents and the one `normalize_laf`/`denormalize_laf` already use -- so the+upper bound is now `w - 1 - border` and `h - 1 - border`. A LAF whose boundary points reach past the last valid+pixel coordinate is now reported as outside; anything strictly inside is unchanged. The equivalent inlined check+in `ScaleSpaceDetector._process_octave` moved with it, so detections within one pixel of the right or bottom edge+that used to survive its `border=5` filter are now discarded. That inlined check also computed its `max |sin|`+constant with the wrong angular spacing (`2*pi/11` instead of the `2*pi/10` that `laf_to_boundary_points(n_pts=12)`+actually samples), inflating the tested x-extent by 4% and making the inline check stricter than the reference it+claims to reproduce; the two now agree exactly. That correction is a loosening in x, so it can change+`ScaleSpaceDetector` output on its own: a detection whose x-extent falls between the two constants used to be+discarded and is now kept. It is rare -- the detection has to land in a band of width `0.039 * half_s` against the+x bound -- but when it fires it can promote the strongest response in the image, so it is not output-neutral.diff --git a/changelog.d/+migration-130.fixed.md b/changelog.d/+migration-130.fixed.mdnew file mode 100644index 000000000..dc653a1c7--- /dev/null+++ b/changelog.d/+migration-130.fixed.md@@ -0,0 +1,14 @@+Fix the empty-result paths in `kornia.feature.integrated` disagreeing with the corresponding non-empty ones+(#4065). `get_laf_descriptors` returned a hardcoded width of 128 with the *LAF's* dtype and device when it was+handed no keypoints, so an empty batch through, say, a 256-d descriptor produced a `(B, 0, 128)` result that could+not be concatenated with a real one; it now runs the descriptor once on a zero patch and returns its actual width+(the flattened per-patch output, matching the non-empty path's `.view(B, N, -1)`), dtype and device. That is a+widening of the empty path's failure surface: a third-party descriptor that raises on a zero input now raises here+where it previously returned quietly. `LocalFeatureMatcher.no_match_output` returned `lafs0`/`lafs1` of shape+`(0, 0, 2, 3)` where the success path returns `(1, NC, 2, 3)`, so `lafs0[0]` raised `IndexError` exactly when+nothing matched; the empty tensors now keep the leading batch of 1. That is a shape change on a public return+value -- code using `out["lafs0"].shape[0] == 0` as its no-match signal now sees `1` and should test+`out["keypoints0"].shape[0] == 0`, which was already the consistent signal. `LocalFeatureMatcher.forward`'s+docstring also stops claiming `confidence` is in `[0, 1]`: it is `1 - distance`, which for the raw-distance+matchers `nn` and `mnn` goes at least down to -1 on unit-norm descriptors, and is unbounded below for arbitrary+ones.diff --git a/changelog.d/+migration-131.fixed.md b/changelog.d/+migration-131.fixed.mdnew file mode 100644index 000000000..1e7bf78c4--- /dev/null+++ b/changelog.d/+migration-131.fixed.md@@ -0,0 +1,132 @@+Stop `MultiResolutionDetector` (and therefore `KeyNetDetector`) fabricating detections, honour its `mask` argument,+and keep its LAFs in the input dtype (#4089, #4090, #4091).++**Padded slots are zero, and the shape is always `num_features`.** `detect_features_on_single_level` masked every+non-candidate position to `torch.finfo(dtype).min / 2` and then ran `topk` with `k` clamped against the *pixel+count* rather than the number of surviving candidates. Once a pyramid level ran out of above-threshold maxima,+`topk` could no longer rank -- every remaining position carried the same sentinel -- so it returned an arbitrary+tie-break subset, in practice the low flat indices, which is exactly the border strip `remove_borders` had just+zeroed. `MultiResolutionDetector(BlobHessian(), num_features=100)` on a plain `64x64` image returned 70 of its 100+features that way, each with a response of `-1.7e38` and a real-looking coordinate. Those slots are now padded+with a zero response and a zero LAF, which is what `ScaleSpaceDetector.detect` already does for a short result,+and `forward` re-applies that padding after the affine-shape and orientation modules, which would otherwise+normalise a zero frame into a finite one. `detect` also only ever *trimmed* an over-long result, so a level+capped at its own pixel count, or a per-level quota rounded down to zero, produced a short one: a one-level `8x8`+image asking for 100 features returned 64, and the default configuration asking for 1 feature returned **0**,+which made `lafs[0, 0]` raise. The result is now padded up to `num_features` with the same zero response and+zero LAF. Callers that tested for the sentinel (`resp < 0`) should test `resp == 0`; callers that consumed the+responses as scores no longer need to.++**`num_features=1` returns a real detection.** The per-level quotas each truncate independently, and at+`num_features=1` the six default shares are `0.508 .. 0.016`, so every one of them rounded to zero and no level+was asked for a single candidate. The apportionment now hands its one slot to the level with the largest share+whenever truncation would otherwise lose every slot, so `num_features=1` returns the same best feature that+`num_features=2` returns first. An apportionment that already gives out a slot is untouched, which with the+default configuration is every `num_features >= 2` (verified byte-identical with `torch.equal` over 16 size/count+combinations).++**The `mask` argument works, and means "where a detection may be".** `forward(img, mask)` and `detect(img, mask)`+accepted a `mask`, documented it as "a mask with weights where to apply the response function", and ignored it --+an all-zero mask returned bit-identical output. Anyone who was passing a mask and silently getting unmasked+detections now gets masked ones. The semantics are the same in both detectors and are chosen from the caller's+side. A boolean or integer mask is binary: any non-zero value keeps a position, so a 0/1 mask, an OpenCV 0/255+mask and `img > 0` all mean the same thing (a raw cast would have multiplied the responses by 255 and defeated an+absolute `score_threshold`). A floating-point mask is used as weights on the detection scores: a weight in+`(0, 1]` scales a score toward the worst -- a non-negative score is multiplied by it, a negative one divided -- so+a down-weighted candidate never outranks a full-weight one with an at-least-as-good score (a plain multiply pulled+a negative score toward zero, i.e. *up* the ranking of a signed response), and a zero or negative weight+suppresses. The weights are cast to the image dtype, so a weight a half-precision image cannot hold rounds to+zero and suppresses, and clamped to one, so a float 0/255 mask (an OpenCV mask through `.astype(np.float32)`)+means what the integer one means rather than scaling every score by 255. The weighting runs in float32 for+half-precision input and is bounded at the dtype's most negative finite value, so a negative score divided by a+small weight cannot overflow to `-inf`; an unfilled slot is ranked with `-inf` (not a finite sentinel such as+`finfo.min / 2`, which a genuine extreme response could sort below, and did: four float32 maxima at `-2e38`+were returned for a single image and dropped for a batch), so every finite detection precedes the padding. The+mask is checked at the integer maximum and again at the sub-pixel-refined centre, conservatively (every octave+pixel the centre touches), so the refinement cannot carry a detection into the zero region. A NaN weight+suppresses rather than winning the ranking. The mask must be `(1 or B, 1, H, W)` with the+image's spatial size. It is resampled onto every pyramid level or octave with a+min-pool rather than an interpolation, so a zero region suppresses every level pixel it touches and a two-pixel+zero stripe does not vanish at a factor-four level. And it is applied to the non-maxima-suppression output, not+to the response the suppression reads: multiplying the response first carves an edge into it, and the bilinear+ramp of that edge was a "maximum" on the suppressed side, so a blob wholly inside the zero region was still+detected (#4102). `ScaleSpaceDetector`, which did multiply its response per octave, takes the same path; its+detections inside the region kept by a binary mask are unchanged. A *floating-point* mask used to weight the+response before the non-maxima suppression and the sub-pixel refinement, so a graded mask moved maxima and+their refined positions; it now weights only the score of a maximum found in the unweighted response, so the+set of candidates and their positions are those of the unmasked image and the weight decides their rank.++`LocalFeatureMatcher` now carries those masks through the full extraction-and-matching path. It documented+`mask0`/`mask1` as `(B, H, W)` inputs but never passed either to its local feature module; that historical shape is+accepted by adding the singleton channel, and the detectors' `(B, 1, H, W)` form is also accepted directly.++**A mask no longer changes the response dtype.** It is resampled *and cast* onto the response map, where the+multiplication used to promote it, so a `float16` image with a `float32` mask returned `float32` responses beside+`float16` LAFs. This also applies to `ScaleSpaceDetector`, which shares the resampling helper: a `float32` image+with a `float64` mask used to return `float64` and now returns `float32`, i.e. the image dtype, in both detectors.+`ScaleSpaceDetector` gains the same shape check, and accepts a boolean or integer mask through the same helper+(it raised on one before). It resampled a mask of any size onto its octaves without complaint, so a stale mask+from before a resize, or a transposed one, was silently stretched onto the wrong geometry, and a multi-channel+mask was broadcast over the scale levels rather than the channels -- an error when the counts differed, the wrong+weighting when they matched. Both detectors now require `(1 or B, 1, H, W)`.++**`ScaleSpaceDetector` no longer leaks its own top-K sentinel for a batch.** For `B > 1` the per-octave top-K+ranks over the whole scale-space volume with non-candidates masked to `torch.finfo(dtype).min / 2`, and an image+with fewer maxima than requested got those sentinels back as detections: `ScaleSpaceDetector()` on+`torch.zeros(2, 1, 32, 32)` returned 70 slots per image with a response of `-1.7e38` and an arbitrary LAF, where+the same input at `B = 1` returned 500 zeros. Which slots a detection filled is now tracked through the top-K+rather than inferred from the response, and an unfilled one -- the sentinel, the padding that tops a short+result up to `num_features`, or a candidate whose frame reached outside the image -- carries a zero response and+a zero LAF, in `detect` and, after the affine-shape and orientation modules have run, in `forward`, and sorts+after every real detection, including a negative one. The mask is deliberately *not* `response == 0`: the+response function is pluggable and may be signed, so an exact zero can be a genuine maximum and keeps its frame.+The border-rejected candidate is the one visible change at `B = 1`: it used to keep its coordinates beside a+zero response, i.e. a keypoint that was never detected, and its scale was often the largest in the result. Both+detectors' `forward` read occupancy off the zero LAF, so a subclass overriding `detect` is honoured whole.++**Half-precision input yields half-precision LAFs.** `detect_features_on_single_level` hardcoded `.float()` on the+pixel coordinates, so a `float16`/`bfloat16` image came back with `float32` LAFs beside half-precision responses.+The index-to-coordinate arithmetic runs in float32 (float64 for a float64 image) and only the finished coordinate+is cast to the input dtype; `float32` and `float64` output is unchanged. A half-precision LAF centre carries the+dtype's integer resolution: exact up to 256 in `bfloat16` and up to 2048 in `float16`, then on a 2 px grid up to+twice that, 4 px up to four times, and so on -- where the old `float32` LAFs were exact.++**A detector model must return one spatial response map.** `detect_features_on_single_level` flattened the+whole response tensor and decoded the flat top-K index with the width alone, so a candidate from channel `c`+landed at `y + c * H`; `BlobHessian` on an RGB image put 56 of 100 LAFs outside a `64x64` frame, up to+`y = 179.9`. Merely decoding the channel would still spend the budget on duplicate LAFs -- a grayscale image+repeated into RGB returned three copies of almost every feature, whose grayscale descriptors are identical.+`MultiResolutionDetector` and `ScaleSpaceDetector` now require their detector model to emit one response channel+and fail with a named error otherwise. This does not restrict the model input: a learned detector may consume RGB+(or any other channel count) and collapse it to one response map itself, which is the intended color-image path.+Single-channel input and response output are unchanged.++**`score_threshold` must be non-negative**, and `MultiResolutionDetector.__init__` raises `ValueError` otherwise:+non-maxima suppression writes an exact zero at every suppressed position, so a negative threshold admitted all of+them as detections (with `score_threshold=-1.0` on a `64x64` image, 70 of 100 returned features were suppressed+border pixels) and would now also be indistinguishable from the zero response that marks an unfilled slot.++**`detect` enforces its documented `(1, C, H, W)`.** It is public, and a larger batch was flattened across the+batch axis and silently returned coordinates for the wrong image. `forward` already had that guard, so only+direct `detect` callers see a difference.++**A short result is sorted.** `MultiResolutionDetector.detect` only ran its final top-K when the levels had+produced *more* slots than `num_features`, so a short result came back in level order with each level's own+padding left in place: with `pyramid_levels=2, up_levels=0, num_features=6000` on a `48x48` image the three real+detections sat at flat indices 0, 1 and 2304. The ranking is now unconditional, as it is in+`ScaleSpaceDetector.detect`, and the zero-response padding sorts to the end.++**Padding is not a correspondence.** `LocalFeatureMatcher` used to describe and match every fixed-shape slot, so+`DescriptorMatcher("nn")` returned every padded origin frame and `mnn` returned one false origin match even when+neither image contained a detection. Zero LAFs are honest, but they are also identical, and identical descriptors+match each other at zero distance -- with plain nearest-neighbour matching the padded block became the largest+consistent set of "correspondences" and captured RANSAC (`SIFTFeature(400)` on two crops of one image: 0.09 px+mean reprojection error on `main`, 31 px with the zero LAFs matched, 0.09 px with them dropped). The matcher now+filters zero LAFs before matching, and skips a pair when either side has nothing left (`matcher` is an arbitrary+module with no obligation to accept a `(0, D)` input); the ratio tests `match_snn` and `match_smnn` reject the+block on their own (`match_mnn` and `match_nn` do not: identical zero descriptors are mutual nearest neighbours+at distance zero), and+`LocalFeature.forward` documents the one-line filter for a hand-rolled `match_nn` pipeline. The feature benchmark+does the same before affine/orientation/description, avoiding meaningless descriptor work and the quadratic+distance-matrix cost of padded rows; its CUDA timers also synchronize around the measured detector and full+matching regions.diff --git a/changelog.d/+migration-132.fixed.md b/changelog.d/+migration-132.fixed.mdnew file mode 100644index 000000000..5d4250ddb--- /dev/null+++ b/changelog.d/+migration-132.fixed.md@@ -0,0 +1,30 @@+`SIFTDescriptor`, `DenseSIFTDescriptor`, `HardNet` and `HardNet8` return NaN for a constant patch in `float16`,+and the SIFT descriptors' backward is NaN in `float16` wherever two neighbouring pixels are equal.++`F.normalize`'s default `eps` of 1e-12 is not representable in `float16` and rounds to zero, so the+`norm.clamp_min(eps)` that exists to stop a zero-norm input becoming `0 / 0` was itself zero in exactly that+dtype: an all-zero patch normalised to NaN, while `bfloat16`, `float32` and `float64` were fine. A detector that+pads a short result hands the descriptor a zero LAF, which samples one image point repeatedly and produces+exactly that patch -- `ScaleSpaceDetector(400)` on a random `64x64` `float16` image gave 365 NaN descriptor rows+-- and a NaN descriptor is worse than a meaningless one, because it propagates through `torch.cdist` and poisons+the whole matching. The nine `F.normalize` calls in those four modules now go through one helper that+normalises a `float16` input in float32 and casts back (an `eps` representable in `float16` is safe but not+neutral: a norm in the subnormal window came back as 0.5). `bfloat16`, `float32` and `float64` results are+unchanged: they keep the 1e-12 default.++The forward pass was only half of it. `SIFTDescriptor` and `DenseSIFTDescriptor` guard `sqrt(gx^2 + gy^2 + eps)`+and `atan2(gy, gx + eps)` with `eps = 1e-10`, which is zero in `float16` -- and a squared `float16` gradient+underflows long before that -- so at every pixel with a zero gradient both sat on their singular point and the+input gradient came back NaN (9 of 4096 on ordinary random `32x32` patches). The gradient magnitude and+orientation are now computed in float32 for `float16` input and cast back, and the RootSIFT `sqrt` is computed+in float32 for `float16` as well. An *exactly* flat patch -- what a zero-LAF padding slot samples -- was the+remaining case: the guard gave every zero-gradient pixel a magnitude of `sqrt(eps)`, so a flat patch's+descriptor was a unit vector built from `eps` (float32) or a subnormal one (float16) whose `1 / norm` gradient,+together with `atan2`'s `1 / eps`, overflowed through the float16 cast into an all-NaN input gradient (and was+a meaningless ~1e8 in float32). A zero-gradient pixel now contributes a zero magnitude, a zero vector normalises+to zero with a zero gradient (the `eps` clamp's `1 / eps` was never meaningful), and+`PatchDominantGradientOrientation` skips its parabolic refinement on an empty or uniform histogram instead of+dividing `0 / 0`; a flat patch has a zero SIFT descriptor and a zero input gradient in every dtype. `bfloat16`,+whose exponent range holds both the guard and the squares, and the wider dtypes are byte-identical at every+pixel whose gradient is not exactly zero; a patch with such pixels (a saturated region) loses their `sqrt(eps)`+contribution, a change of at most `1e-5` per pixel before normalisation.diff --git a/changelog.d/+migration-133.fixed.md b/changelog.d/+migration-133.fixed.mdnew file mode 100644index 000000000..b92fa867e--- /dev/null+++ b/changelog.d/+migration-133.fixed.md@@ -0,0 +1,5 @@+`RandomCutMixV2` and `CutmixGenerator` document `cut_size` as what it is: the `[min, max]` clamp on the+Beta-sampled mixing coefficient `lambda`, where the cut side is `floor(sqrt(1 - lambda) * side)`, so a larger+`cut_size` gives a smaller cut. It was described as the "minimum and maximum cut ratio". A minimum of `1.0` is+now rejected with a `ValueError`: it forced `lambda = 1`, built an inverted zero-size box and silently made the+augmentation an identity. (#4439, #4491)diff --git a/changelog.d/README.md b/changelog.d/README.mdnew file mode 100644index 000000000..aa2edee3e--- /dev/null+++ b/changelog.d/README.md@@ -0,0 +1,91 @@+# Changelog fragments++Each PR with a user-visible change adds its own Markdown file here. This avoids+merge conflicts caused by everyone editing the same section of `CHANGELOG.md`.+[Towncrier](https://towncrier.readthedocs.io/en/25.8.0/) combines the files at release time.++## Adding an entry++Name the file `<PR>.<type>.md`, for example `1234.fixed.md`. Use a PR number,+not an issue number: generated links point to `/pull/<PR>`.++```markdown+`CameraModel.project` now accepts empty batches instead of raising an error.+```++Write a short description without a heading or an outer bullet. Towncrier adds+the heading, bullet, and PR link. Use these types:++| Type | Changelog heading | Use for |+| --- | --- | --- |+| `added` | Added | New features and user-facing documentation |+| `fixed` | Bug fixes | Corrections to existing behavior |+| `breaking` | Breaking changes | Incompatible changes; describe both old and new behavior |++A PR can add files in more than one category. Put related changes in one file per+category. To credit several PRs for one change, put identical text in a file for+each PR in the same category (for example `1234.fixed.md` and `1235.fixed.md`).+Towncrier combines them into one bullet with both PR links.++If there is no PR number yet, use a unique name such as+`+fix-camera-shape.fixed.md`, then rename it to the PR number before merging.+Internal refactors, tests, and CI-only changes may omit a fragment; explain why+in the PR description and ask a maintainer to apply the `no-changelog` label.+CI requires a fragment and rejects edits to `CHANGELOG.md` on ordinary PRs.+The label permits internal and release PRs to omit a fragment and, when needed,+edit the assembled changelog. Filename and rendering checks still run. Rename temporary `+name` files before merging: CI rejects them.+The reserved `+migration-*` files are the one-time legacy exception.++Preview all pending notes from the repository root:++```bash+pixi run changelog-preview+```++This prints the notes without modifying the changelog or deleting fragments.+The pinned tool runs in an isolated uv tool environment; its first run needs+network access. It does not install Towncrier into Kornia's runtime environment.+Do not commit generated previews in ordinary PRs.++## Preparing a release++On the release branch, with a clean working tree:++1. Run `pixi run changelog-preview` and review the pending entries.+2. Run `pixi run changelog-build --version X.Y.Z` with the actual release version.+ The version argument is required by this workflow; do not run the build without it.+ The task uses `--yes`: Towncrier stages the dated section in `CHANGELOG.md` and+ removes and stages the consumed fragments without prompting, including in scripts.+3. Review `git diff --cached`, including the fragment deletions, and commit it in+ the release PR. Use the `no-changelog` label for this PR, since it consumes notes+ rather than adding one. Keep this README and the insertion marker in `CHANGELOG.md`.++Only release PRs update the assembled changelog. If a pending PR modifies a+fragment already consumed by a release, resolve that conflict by deciding whether+the correction belongs in the released notes or in a new fragment.++## Existing unreleased notes++The `+migration-*` files preserve the entries that were already under `Unreleased`+when this workflow was introduced, including their existing PR references. They+use Towncrier's orphan prefix (`+`) to avoid adding duplicate PR links. Keep those+names until the next release consumes the files; new PRs use the naming rule above.++## Updating an open PR during the switch++If your PR already edits `CHANGELOG.md`, move only its new entries into+`changelog.d/<PR>.<type>.md`, preserving their text. Then merge or rebase onto the+new `main` and resolve `CHANGELOG.md` to the version on `main`, removing your old+changelog hunk. Check the PR diff: the new fragments should contain your notes,+and `CHANGELOG.md` should have no changes. Run the preview before pushing.++Remove any local `CHANGELOG.md merge=union` rule from `.git/info/attributes` or+your global attributes file before doing this. Use `git check-attr merge -- CHANGELOG.md`+to check the effective rule. A union merge can silently restore the old unreleased+block alongside the fragments, causing every old entry to appear twice at release.+Resolve the transition explicitly instead of keeping both sides of that block.++Towncrier sorts entries within each category, so do not use βaboveβ or βbelowβ to+refer to another entry. Name its category or PR instead. The migrated notes retain+their original plain PR references; new fragments generate links. This mixed style+is limited to the first release after migration.diff --git a/docs/source/get-started/stability.rst b/docs/source/get-started/stability.rstindex 795528f4c..aa0ad6d3a 100644--- a/docs/source/get-started/stability.rst+++ b/docs/source/get-started/stability.rst@@ -106,7 +106,7 @@ Recording a completed deprecation---------------------------------Once the deprecation window has passed, remove the API and describe the removal-in ``CHANGELOG.md``. Update any existing entries in ``tests/api_surface.json``+in a ``changelog.d/<PR>.breaking.md`` fragment. Update any existing entries in ``tests/api_surface.json``in the same pull request; keep the module key, using an empty list if necessary.The import-surface check verifies that recorded names leave the export surfacein that change. An inventory edit acknowledges an ``__all__`` removal only fordiff --git a/pixi.toml b/pixi.tomlindex 29827664b..6c8ef3938 100644--- a/pixi.toml+++ b/pixi.toml@@ -60,6 +60,9 @@ toml-fmt-check = { cmd = "tombi format --check", description = "Check TOML formabuild-docs = { cmd = "uv run python -m sphinx -W -b html docs/source docs/build/html", depends-on = ["install-docs"] }+# Changelog tooling is isolated from Kornia's runtime and test dependencies.+changelog-preview = { cmd = "uv tool run --from towncrier==25.8.0 towncrier build --draft --version Unreleased", description = "Preview pending release notes without changing files" }+changelog-build = { cmd = "uv tool run --from towncrier==25.8.0 towncrier build --yes", description = "Assemble release notes (requires --version X.Y.Z); stages changelog and removes consumed fragments" }# Utilityclean = { cmd = "find . -type f -name '*.pyc' -delete && find . -type d -name '__pycache__' -delete && rm -rf .venv .venv-py312 .venv-py313 .venv-py314" }diff --git a/pyproject.toml b/pyproject.tomlindex 162ace620..72ca50714 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -340,6 +340,28 @@ max-statements = 64 # Recommended: 50"D", # Don't enforce documentation rules] # allow assert, random, ignore BLE, mutable class attr+# Changelog fragments are assembled only when preparing a release.+[tool.towncrier]+directory = "changelog.d"+filename = "CHANGELOG.md"+title_format = "## [{version}] - {project_date}"+issue_format = "[#{issue}](https://github.com/kornia/kornia/pull/{issue})"+# Setting ignore enables strict filename validation; tolerate Finder metadata only.+ignore = [".DS_Store"]+issue_pattern = "[0-9]+"++[[tool.towncrier.type]]+directory = "added"+name = "Added"++[[tool.towncrier.type]]+directory = "fixed"+name = "Bug fixes"++[[tool.towncrier.type]]+directory = "breaking"+name = "Breaking changes"+[tool.ty.src]include = ["kornia"]exclude = ["tests", "docs", "conftest.py"]diff --git a/tests/scripts/test_check_changelog.py b/tests/scripts/test_check_changelog.pynew file mode 100644index 000000000..76c088b92--- /dev/null+++ b/tests/scripts/test_check_changelog.py@@ -0,0 +1,159 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+import importlib.util+import subprocess+import sys+from pathlib import Path++import pytest++_SCRIPT = Path(__file__).parent.parent.parent / ".github" / "scripts" / "check_changelog.py"+_SPEC = importlib.util.spec_from_file_location("check_changelog", _SCRIPT)+assert _SPEC is not None and _SPEC.loader is not None+check_changelog = importlib.util.module_from_spec(_SPEC)+sys.modules[_SPEC.name] = check_changelog+_SPEC.loader.exec_module(check_changelog)+++def _git(*args: str, cwd: Path) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True) # noqa: S603, S607+++def _repo(tmp_path: Path) -> Path:+ repo = tmp_path / "repo"+ (repo / "changelog.d").mkdir(parents=True)+ (repo / "changelog.d" / "README.md").write_text("guide\n")+ (repo / "CHANGELOG.md").write_text("# Changelog\n")+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)+ return repo+++def _run_in(repo: Path, monkeypatch: pytest.MonkeyPatch, *args: str) -> int:+ monkeypatch.chdir(repo)+ return check_changelog.main(["--base-ref", "base", "--pr-number", "4513", *args])+++def test_accepts_current_numeric_fragment(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ (repo / "changelog.d" / "4513.fixed.md").write_text("Fix a public bug.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "fragment", cwd=repo)++ assert _run_in(repo, monkeypatch) == 0+++def test_requires_a_fragment_for_the_current_pr(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ (repo / "changelog.d" / "1234.fixed.md").write_text("Credit another pull request.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "other fragment", cwd=repo)++ assert _run_in(repo, monkeypatch) == 1+++def test_no_changelog_skip_does_not_skip_validation(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ (repo / "changelog.d" / "+unreviewed.fixed.md").write_text("An orphan.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "invalid fragment", cwd=repo)++ assert _run_in(repo, monkeypatch, "--skip-presence") == 1+++def test_no_changelog_skip_allows_an_internal_pr(tmp_path, monkeypatch):+ repo = _repo(tmp_path)++ assert _run_in(repo, monkeypatch, "--skip-presence") == 0+++def test_no_changelog_skip_allows_a_release_changelog_edit(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ (repo / "CHANGELOG.md").write_text("# Changelog\n\n## [1.0.0]\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "release notes", cwd=repo)++ assert _run_in(repo, monkeypatch, "--skip-presence") == 0+++def test_rejects_changelog_edit_in_an_ordinary_pr(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ (repo / "changelog.d" / "4513.fixed.md").write_text("Fix a public bug.\n")+ (repo / "CHANGELOG.md").write_text("# Changelog\n\nA premature note.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "fragment and changelog", cwd=repo)++ assert _run_in(repo, monkeypatch) == 1+++def test_migration_fragments_are_the_only_allowed_orphans(tmp_path):+ repo = _repo(tmp_path)+ migration = repo / "changelog.d" / "+migration-001.added.md"+ migration.write_text("Existing unreleased note.\n")+ (repo / "changelog.d" / ".DS_Store").write_bytes(b"finder metadata")++ assert check_changelog.validate_fragments(repo) == []+ migration.rename(repo / "changelog.d" / "+migration-note.added.md")+ assert check_changelog.validate_fragments(repo)+++ ("filename", "content"),+ [("4513.changed.md", "Unknown section.\n"), ("4513.fixed.md", " \n")],+)+def test_rejects_invalid_fragment_name_or_content(tmp_path, filename, content):+ repo = _repo(tmp_path)+ (repo / "changelog.d" / filename).write_text(content)++ assert check_changelog.validate_fragments(repo)+++def test_presence_uses_a_renamed_fragment_destination(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ old = repo / "changelog.d" / "temporary.fixed.md"+ old.write_text("Temporary name.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "temporary fragment", cwd=repo)+ _git("branch", "-f", "base", cwd=repo)+ old.rename(repo / "changelog.d" / "4513.fixed.md")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "rename fragment", cwd=repo)++ monkeypatch.chdir(repo)+ changed = check_changelog.changed_paths("base")+ assert changed == {Path("changelog.d/4513.fixed.md")}+ assert check_changelog.has_current_pr_fragment(changed, 4513)+++def test_deleting_a_fragment_does_not_satisfy_presence(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ fragment = repo / "changelog.d" / "4513.fixed.md"+ fragment.write_text("A former release note.\n")+ _git("add", ".", cwd=repo)+ _git("commit", "-q", "-m", "fragment", cwd=repo)+ _git("branch", "-f", "base", cwd=repo)+ fragment.unlink()+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "remove fragment", cwd=repo)++ monkeypatch.chdir(repo)+ assert check_changelog.changed_paths("base") == {Path("changelog.d/4513.fixed.md")}+ assert check_changelog.main(["--base-ref", "base", "--pr-number", "4513"]) == 1