Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): batch patch extraction and sample the pyramid from a packed atlas (#4128)

Dmytro Mishkinc61dad2bbfe4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 35087a4c4..0d7a98852 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Breaking changes
+* `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).
+
* 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 β€”
@@ -92,6 +129,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* 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,
diff --git a/benchmarks/feature/scale_space_detector.py b/benchmarks/feature/scale_space_detector.py
index f4d34c718..4dd857316 100644
--- a/benchmarks/feature/scale_space_detector.py
+++ b/benchmarks/feature/scale_space_detector.py
@@ -281,9 +281,10 @@ class KeyNetExtractor(nn.Module):
# model and nms run at 6 different image sizes β†’ dynamic=True avoids recompilation
det.model = torch.compile(det.model, dynamic=True)
det.nms = torch.compile(det.nms, dynamic=True)
- # aff/ori/descriptor NOT compiled: extract_patches_from_pyramid (laf.py) contains
- # an .item() call inside a while-loop that creates graph breaks, causing extra
- # sub-graphs that need additional warmup and show as a spike on the first eval pair.
+ # aff/ori/descriptor NOT compiled: extract_patches_from_pyramid traces as one graph
+ # now, but each (num-LAF, patch-size) pair it is called with would still specialize
+ # into its own graph, needing additional warmup that shows as a spike on the first
+ # eval pair.
@torch.no_grad()
def forward(self, img: torch.Tensor):
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 701224a9e..f899aa85d 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -21,7 +21,7 @@ from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
-from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
@@ -369,6 +369,9 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
[a11*MIN_SIZE a12*MIN_SIZE x*(W-1)]
[a21*MIN_SIZE a22*MIN_SIZE y*(H-1)]
+ A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so
+ the conversion stays finite and round-trips with :func:`normalize_laf`.
+
Args:
LAF: :math:`(B, N, 2, 3)`
images: :math:`(B, CH, H, W)`
@@ -379,8 +382,12 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
- wf = float(w - 1)
- hf = float(h - 1)
+ # A singleton image axis has a single valid coordinate and therefore no spatial extent.
+ # Treating it as one pixel wide keeps the conversion finite and round-trippable with
+ # `normalize_laf`, instead of collapsing every LAF to zero here and raising a
+ # `ZeroDivisionError` there.
+ wf = float(max(w - 1, 1))
+ hf = float(max(h - 1, 1))
min_size = min(hf, wf)
coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) * min_size
coef[0, 0, 0, 2] = wf
@@ -400,6 +407,9 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
[a11/MIN_SIZE a12/MIN_SIZE x/(W-1)]
[a21/MIN_SIZE a22/MIN_SIZE y/(H-1)]
+ A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so
+ the conversion stays finite instead of dividing by zero.
+
Args:
LAF: :math:`(B, N, 2, 3)`
images: :math:`(B, CH, H, W)`
@@ -410,8 +420,10 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
- wf = float(w - 1)
- hf = float(h - 1)
+ # See `denormalize_laf`: a singleton axis counts as one pixel of extent, so a 1-pixel-wide or
+ # 1-pixel-tall image normalizes finitely instead of dividing by zero.
+ wf = float(max(w - 1, 1))
+ hf = float(max(h - 1, 1))
min_size = min(hf, wf)
coef = torch.ones(1, 1, 2, 3, dtype=LAF.dtype, device=LAF.device) / min_size
coef[0, 0, 0, 2] = 1.0 / wf
@@ -440,8 +452,10 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
LAF_renorm = denormalize_laf(LAF, img)
grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False)
- grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w - 1) - 1.0
- grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h - 1) - 1.0
+ # A singleton axis has no spatial extent; one pixel of denominator keeps the grid finite and
+ # lets the border padding return that single pixel (see `denormalize_laf`).
+ grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(max(w - 1, 1)) - 1.0
+ grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(max(h - 1, 1)) - 1.0
return grid
@@ -457,13 +471,14 @@ def _clamp_grid_to_pixel_centers(grid: torch.Tensor, h: int, w: int) -> torch.Te
exactly.
Args:
- grid: sampling grid :math:`(B, PS, PS, 2)`, last dimension ordered ``(x, y)``. Only the 2-D form is
- handled; a 3-D grid would need a third bound from the depth of the sampled volume.
+ grid: sampling grid :math:`(..., 2)` with any leading batch dimensions, last dimension ordered
+ ``(x, y)``. Only 2-D sampling is handled; a 3-D grid would need a third bound from the
+ depth of the sampled volume.
h: height of the sampled image.
w: width of the sampled image.
Returns:
- the clamped grid :math:`(B, PS, PS, 2)`.
+ the clamped grid, same shape as ``grid``.
"""
x = grid[..., 0].clamp(-1.0 + 1.0 / float(w), 1.0 - 1.0 / float(w))
@@ -471,6 +486,148 @@ def _clamp_grid_to_pixel_centers(grid: torch.Tensor, h: int, w: int) -> torch.Te
return torch.stack([x, y], dim=-1)
+def _grid_sample_patches(img: torch.Tensor, grid: torch.Tensor, h: int, w: int) -> torch.Tensor:
+ r"""Run ``grid_sample`` with border padding, robust across devices.
+
+ MPS does not implement ``padding_mode="border"``; it is emulated with a clamped grid plus
+ zero padding (see :func:`_clamp_grid_to_pixel_centers`). ``img`` and ``grid`` share a dtype:
+ the extractors upcast reduced-precision inputs to float32 once, before their chunk loops.
+ That upcast is deliberate on every torch version, not only the torch <= 2.9 builds whose
+ float16/bfloat16 CPU kernel reads out of bounds at the border β€” half-precision sampling
+ coordinates also quantize to whole pixels on large images. It is a real trade on CUDA, where
+ the native half kernels are fine: float16 ``extract_patches_simple`` pays roughly a 2x
+ slowdown at high N for the accuracy.
+ """
+ if img.device.type == "mps":
+ return F.grid_sample(img, _clamp_grid_to_pixel_centers(grid, h, w), padding_mode="zeros", align_corners=False)
+ return F.grid_sample(img, grid, padding_mode="border", align_corners=False)
+
+
+def _grid_dtype(dtype: torch.dtype) -> torch.dtype:
+ """Return the sampling-grid dtype for an image or LAF dtype."""
+ return torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+
+
+def _promoted_grid_dtype(image_dtype: torch.dtype, laf_dtype: torch.dtype) -> torch.dtype:
+ """Return a grid dtype that never discards image or LAF coordinate precision."""
+ return _grid_dtype(torch.promote_types(image_dtype, laf_dtype))
+
+
+def _grid_elem_bytes(dtype: torch.dtype) -> int:
+ """Bytes per element after applying the sampling-grid dtype policy."""
+ return 8 if _grid_dtype(dtype) == torch.float64 else 4
+
+
+def _grid_chunk_lafs(B: int, N: int, ch: int, PS: int, elem_size: int, budget: int = 64 * 1024 * 1024) -> int:
+ r"""Largest LAF count whose folded grid and sampled chunk each fit the byte budget.
+
+ The sampling grid and its pointwise intermediates scale with :math:`B \cdot N \cdot PS^2`,
+ so extraction is chunked along N to bound peak memory, in the spirit of
+ :func:`kornia.core.utils.batched_forward`. Both the two-coordinate folded grid and the
+ channel-scaled ``grid_sample`` result are individually kept within the budget; pointwise remap
+ temporaries can still make the real peak a multiple of it. At least one LAF per chunk; when
+ everything fits the budget the loop degenerates to the single-call fast path. The default
+ budget is a defaulted argument rather than a module constant because TorchScript cannot close
+ over module-level ints; tests monkeypatch this function to force multi-chunk sampling on small
+ inputs.
+ """
+ per_laf = B * PS * PS * max(2, ch) * elem_size
+ return min(N, max(1, budget // per_laf))
+
+
+def _pyramid_atlas_fits(atlas_bytes: int, budget: int = 128 * 1024 * 1024) -> bool:
+ """Return whether a packed pyramid atlas fits its default memory budget.
+
+ The budget is a defaulted argument because TorchScript cannot close over module-level integer
+ constants. Keeping the policy in a helper also gives tests a narrow seam for forcing either
+ extraction path.
+ """
+ return atlas_bytes <= budget
+
+
+def _sample_patches(img: torch.Tensor, grid: torch.Tensor, h: int, w: int) -> torch.Tensor:
+ r"""Sample one patch per LAF with a single ``grid_sample`` call.
+
+ The per-LAF grids :math:`(B, N, PS, PS, 2)` are folded to :math:`(B, N \cdot PS, PS, 2)` so
+ one call covers the whole batch, without a Python loop over B or a ``(B*N, CH, H, W)`` input
+ copy. ``grid`` must already live on ``img``'s device: the extractors move a cross-device LAF
+ to the image's device up front, so the grid is built there.
+
+ Returns:
+ patches :math:`(B, N, CH, PS, PS)` as a permuted view; assigning it or calling
+ ``.contiguous()`` makes the copy.
+ """
+ B, N, PS = grid.size(0), grid.size(1), grid.size(2)
+ ch = img.size(1)
+ folded = grid.view(B, N * PS, PS, 2)
+ return _grid_sample_patches(img, folded, h, w).view(B, ch, N, PS, PS).permute(0, 2, 1, 3, 4)
+
+
+def _extract_patches_from_pyramid_levelwise(
+ img: torch.Tensor,
+ nlaf: torch.Tensor,
+ pyr_idx: torch.Tensor,
+ heights: List[int],
+ widths: List[int],
+ PS: int,
+) -> torch.Tensor:
+ """Sample each pyramid level separately when a single atlas would be too large.
+
+ Patches accumulate on the image's device and dtype, like the atlas path: the callers move a
+ cross-device LAF to the image's device before the level index is derived, and
+ reduced-precision levels are upcast once, before the loops, so no full level is re-cast per
+ chunk. Out-of-range level indices (the -1 marking a non-finite LAF) match no level and keep
+ their zero patch.
+ """
+ B, N = nlaf.shape[:2]
+ ch = img.shape[1]
+ grid_dtype = _promoted_grid_dtype(img.dtype, nlaf.dtype)
+ grid_laf = nlaf.to(grid_dtype) if nlaf.dtype != grid_dtype else nlaf
+ out = torch.zeros(B, N, ch, PS, PS, dtype=img.dtype, device=img.device)
+ chunk = _grid_chunk_lafs(B, N, ch, PS, _grid_elem_bytes(grid_dtype))
+ cur_img = img.to(grid_laf.dtype) if img.dtype != grid_laf.dtype else img
+ laf_a = grid_laf[..., :2]
+ t = 2.0 * grid_laf[..., :, 2] - 1.0
+
+ # Most calls fit in one bounded chunk, so their level-independent affine grid can be reused
+ # across the streaming pyramid. A multi-chunk call rebuilds each chunk's grid per level rather
+ # than retaining every grid or pyramid level: the fallback exists specifically to keep peak
+ # memory bounded, and either cache would make it scale with all N or another third of the image.
+ base_grid_all = torch.empty(0, dtype=grid_dtype, device=nlaf.device)
+ if chunk == N:
+ theta = torch.cat([laf_a, torch.zeros(B, N, 2, 1, dtype=grid_dtype, device=nlaf.device)], dim=-1)
+ base_grid_all = F.affine_grid(theta.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False).view(
+ B, N, PS, PS, 2
+ )
+
+ for level_idx, (h_l, w_l) in enumerate(zip(heights, widths)):
+ if level_idx > 0:
+ cur_img = pyrdown(cur_img)
+ for st in range(0, N, chunk):
+ en = min(st + chunk, N)
+ nc = en - st
+ if chunk == N:
+ base_grid = base_grid_all
+ else:
+ theta = torch.cat(
+ [laf_a[:, st:en], torch.zeros(B, nc, 2, 1, dtype=grid_dtype, device=nlaf.device)], dim=-1
+ )
+ base_grid = F.affine_grid(theta.view(B * nc, 2, 3), [B * nc, ch, PS, PS], align_corners=False).view(
+ B, nc, PS, PS, 2
+ )
+ translation = t[:, st:en].view(B, nc, 1, 1, 2)
+ # Match `normalize_laf` / `denormalize_laf`: a singleton axis counts as one pixel of
+ # extent. Border padding still repeats that axis's only pixel, while the other axis
+ # keeps its spatial variation instead of being collapsed by a shared zero `min_l`.
+ min_l = float(min(max(h_l - 1, 1), max(w_l - 1, 1)))
+ k = base_grid.new_tensor([2.0 * min_l / float(max(w_l - 1, 1)), 2.0 * min_l / float(max(h_l - 1, 1))])
+ grid = base_grid * k + translation
+ patches = _sample_patches(cur_img, grid, h_l, w_l).to(img.dtype)
+ mask = (pyr_idx[:, st:en] == level_idx).view(B, en - st, 1, 1, 1)
+ out[:, st:en] = torch.where(mask, patches, out[:, st:en])
+ return out
+
+
def extract_patches_simple(
img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
) -> torch.Tensor:
@@ -489,32 +646,40 @@ def extract_patches_simple(
"""
KORNIA_CHECK_LAF(laf)
+ KORNIA_CHECK(img.size(0) == laf.size(0), "img and laf must have the same batch size")
+ # The image owns the output device and dtype, but the LAF keeps its coordinate precision.
+ # Moving the tiny LAF up front also preserves mixed-precision autocast pipelines whose
+ # detector emits a reduced-precision LAF for a float32 image.
+ laf = laf.to(device=img.device)
+ grid_dtype = _promoted_grid_dtype(img.dtype, laf.dtype)
+ laf = laf.to(grid_dtype) if laf.dtype != grid_dtype else laf
if normalize_lafs_before_extraction:
nlaf = normalize_laf(laf, img)
else:
nlaf = laf
_, ch, h, w = img.size()
B, N, _, _ = laf.size()
- out = []
- # for loop temporarily, to be refactored
- for i in range(B):
- grid = generate_patch_grid_from_normalized_LAF(img[i : i + 1], nlaf[i : i + 1], PS).to(img.device)
- if img.device.type == "mps":
- out.append(
- F.grid_sample(
- img[i : i + 1].expand(grid.size(0), ch, h, w),
- _clamp_grid_to_pixel_centers(grid, h, w),
- padding_mode="zeros",
- align_corners=False,
- )
- )
- else:
- out.append(
- F.grid_sample(
- img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
- )
- )
- return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
+ if B == 0 or N == 0:
+ return torch.zeros(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)
+ # See `extract_patches_from_pyramid`: a non-finite value anywhere in a training-time LAF
+ # frame, including only its center, would reach `grid_sample` as an invalid grid, and the CPU
+ # border-padding backward kernel can segfault on it. Mark the whole frame invalid and
+ # sanitize it before any grid arithmetic; the frame then contributes neither output nor
+ # gradient, and its finite neighbours are untouched.
+ invalid_lafs = ~torch.isfinite(nlaf).all(dim=-1).all(dim=-1)
+ nlaf = nlaf.masked_fill(invalid_lafs.view(B, N, 1, 1), 0.0)
+ # The image is upcast to the grid's dtype once, before the chunk loop: `_grid_sample_patches`
+ # samples in one dtype, and re-casting the full image per chunk would defeat the chunk budget.
+ sample_img = img.to(grid_dtype) if img.dtype != grid_dtype else img
+ out = torch.empty(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)
+ chunk = _grid_chunk_lafs(B, N, ch, PS, _grid_elem_bytes(grid_dtype))
+ for st in range(0, N, chunk):
+ en = min(st + chunk, N)
+ grid = generate_patch_grid_from_normalized_LAF(img, nlaf[:, st:en], PS).view(B, en - st, PS, PS, 2)
+ out[:, st:en] = _sample_patches(sample_img, grid, h, w)
+ # Zeroing after the loop keeps the masking unconditional, so the fullgraph `torch.compile`
+ # path never takes a data-dependent Python branch.
+ return out.masked_fill_(invalid_lafs.view(B, N, 1, 1, 1), 0.0)
def extract_patches_from_pyramid(
@@ -522,7 +687,8 @@ def extract_patches_from_pyramid(
) -> torch.Tensor:
"""Extract patches defined by LAFs from image torch.Tensor.
- Patches are extracted from appropriate pyramid level.
+ Patches are extracted from the appropriate pyramid level. A LAF whose scale selects a level
+ smaller than ``PS`` is sampled from the coarsest level that can still provide a full patch.
Args:
img: images, LAFs are detected in :math:`(B, CH, H, W)`.
@@ -535,44 +701,142 @@ def extract_patches_from_pyramid(
"""
KORNIA_CHECK_LAF(laf)
+ KORNIA_CHECK(img.size(0) == laf.size(0), "img and laf must have the same batch size")
+ # See `extract_patches_simple`: the image owns the public output contract, while the much
+ # smaller LAF moves to its device without discarding coordinate precision.
+ laf = laf.to(device=img.device)
+ grid_dtype = _promoted_grid_dtype(img.dtype, laf.dtype)
+ laf = laf.to(grid_dtype) if laf.dtype != grid_dtype else laf
if normalize_lafs_before_extraction:
nlaf = normalize_laf(laf, img)
else:
nlaf = laf
B, N, _, _ = laf.size()
_, ch, h, w = img.size()
- scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)
+ if B == 0 or N == 0:
+ return torch.zeros(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)
# max_level is a compile-time constant for static image shapes.
max_level = min(h, w) // PS
- pyr_idx = scale.log2().clamp(min=0.0, max=max(0, max_level - 1)).long() # (B, N, 1, 1)
- out = torch.zeros(B, N, ch, PS, PS, dtype=nlaf.dtype, device=nlaf.device)
- cur_img = img
- # Always run at least level 0; max_level is a compile-time constant for static shapes.
- num_levels = max(1, max_level)
- for cur_pyr_level in range(num_levels):
- _, ch_l, h_l, w_l = cur_img.size()
- for i in range(B):
- # torch.where avoids nonzero/data-dependent shapes β†’ fully compilable.
- level_mask = (pyr_idx[i] == cur_pyr_level).view(N, 1, 1, 1)
- grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1], PS)
- if cur_img.device.type == "mps":
- patches = F.grid_sample(
- cur_img[i : i + 1].expand(N, ch_l, h_l, w_l),
- _clamp_grid_to_pixel_centers(grid, h_l, w_l),
- padding_mode="zeros",
- align_corners=False,
- )
- else:
- patches = F.grid_sample(
- cur_img[i : i + 1].expand(N, ch_l, h_l, w_l), grid, padding_mode="border", align_corners=False
- )
- out[i] = torch.where(level_mask, patches.to(nlaf.dtype), out[i])
- if cur_pyr_level < num_levels - 1:
+ # Build exactly the pyramid that can provide a PS-sized patch. ``pyrdown`` defines its output
+ # size as floor(side / 2), including for odd inputs, so the atlas can be allocated before the
+ # levels are materialized and each level can be released after it is copied.
+ heights = [h]
+ widths = [w]
+ for _ in range(1, max(1, max_level)):
+ # `pyrdown` applies a 5x5 Gaussian with two pixels of reflect padding, which requires
+ # both source axes to be larger than two. Keep such a source as the actual coarsest
+ # usable level instead of recording a target level that cannot be materialized.
+ if min(heights[-1], widths[-1]) <= 2:
+ break
+ h_l = heights[-1] // 2
+ w_l = widths[-1] // 2
+ if min(h_l, w_l) < PS:
+ break
+ heights.append(h_l)
+ widths.append(w_l)
+
+ # A non-finite value anywhere in a training-time LAF, including only its center, can reach an
+ # invalid sampling grid. The CPU border-padding backward kernel can segfault on a NaN grid.
+ # Mark the whole frame invalid and sanitize it before any grid arithmetic; both paths then
+ # return a zero patch and a zero gradient for that frame without disturbing finite neighbours.
+ invalid_lafs = ~torch.isfinite(nlaf).all(dim=-1).all(dim=-1)
+ nlaf = nlaf.masked_fill(invalid_lafs.view(B, N, 1, 1), 0.0)
+ scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)
+ pyr_idx = scale.log2().clamp(min=0.0, max=float(len(heights) - 1)).long().squeeze(-1).squeeze(-1)
+ pyr_idx = pyr_idx.masked_fill(invalid_lafs, -1)
+
+ # Small images and ROIs commonly have only level 0. Sampling that image directly avoids
+ # allocating and remapping a one-level atlas that cannot provide any pyramid benefit.
+ if len(heights) == 1:
+ return _extract_patches_from_pyramid_levelwise(img, nlaf, pyr_idx, heights, widths, PS)
+
+ # Place every level side-by-side with a one-pixel replicated guard. The guard absorbs
+ # floating-point remapping error at an outer pixel center and preserves both the border value
+ # and its zero outward gradient instead of leaking into the neighbouring level.
+ atlas_h = h + 2
+ packed_widths = [w_l + 2 for w_l in widths]
+ atlas_w = sum(packed_widths)
+ # A full-height atlas is counterproductive for very large or heavily batched images. Keep
+ # its storage bounded; the static shape guard disappears under torch.compile, and the
+ # levelwise path preserves the same clamping and reduced-precision grid semantics. The atlas
+ # is built in the grid's dtype -- reduced-precision inputs are upcast once, so the replicate
+ # pad, `pyrdown` and every chunk's `grid_sample` run on kernels every torch build has, and no
+ # full-atlas recast is paid per chunk. A 1-pixel axis in any *built level* -- a 1-pixel input
+ # image, or a coarse level that `PS == 1` lets the pyramid descend to -- would make the level
+ # constants' Python `size - 1` division below raise; the levelwise sampler treats that axis
+ # as having zero spatial extent instead.
+ atlas_elements = B * ch * atlas_h * atlas_w
+ atlas_bytes = atlas_elements * _grid_elem_bytes(grid_dtype)
+ if img.dtype != grid_dtype:
+ atlas_bytes += B * ch * h * w * _grid_elem_bytes(grid_dtype) # the one-time upcast copy
+ if min(heights[-1], widths[-1]) < 2 or not _pyramid_atlas_fits(atlas_bytes):
+ return _extract_patches_from_pyramid_levelwise(img, nlaf, pyr_idx, heights, widths, PS)
+ sample_img = img.to(grid_dtype) if img.dtype != grid_dtype else img
+ atlas = sample_img.new_zeros(B, ch, atlas_h, atlas_w)
+ cur_img = sample_img
+ xoff = 0
+ for level_idx, (h_l, w_l) in enumerate(zip(heights, widths)):
+ if level_idx > 0:
cur_img = pyrdown(cur_img)
- # Stop early if the pyramided image is too small for further levels.
- if min(cur_img.size(2), cur_img.size(3)) < PS:
- break
- return out
+ atlas[:, :, : h_l + 2, xoff : xoff + w_l + 2] = F.pad(cur_img, (1, 1, 1, 1), mode="replicate")
+ xoff += w_l + 2
+
+ # A patch grid's linear part is level-independent: it is generated from normalized LAF A with
+ # zero translation; reduced-precision inputs need float32 grid arithmetic because the atlas is
+ # wider than the original image.
+ laf_a = nlaf[..., :2].to(grid_dtype)
+ t = 2.0 * nlaf[..., :, 2].to(grid_dtype) - 1.0
+
+ # Gather all level-dependent conversion constants per patch, packed as (x, y) pairs so the
+ # remap below runs on the whole grid tensor step by step, never holding split-axis copies. A
+ # giant LAF that nominally selects an unbuilt level is sampled from the actual coarsest
+ # pyramid image.
+ xoff = 0
+ constants = []
+ for h_l, w_l in zip(heights, widths):
+ min_l = float(min(h_l - 1, w_l - 1))
+ constants.append(
+ (
+ 2.0 * min_l / float(w_l - 1), # k: LAF frame -> level-normalized units
+ 2.0 * min_l / float(h_l - 1),
+ -1.0 + 1.0 / float(w_l), # lo/hi: the level's outermost pixel centers
+ -1.0 + 1.0 / float(h_l),
+ 1.0 - 1.0 / float(w_l),
+ 1.0 - 1.0 / float(h_l),
+ float(w_l) / float(atlas_w), # scale/offset: level frame -> atlas frame
+ float(h_l) / float(atlas_h),
+ (float(w_l) + 2.0 * float(xoff + 1)) / float(atlas_w) - 1.0,
+ (float(h_l) + 2.0) / float(atlas_h) - 1.0,
+ )
+ )
+ xoff += w_l + 2
+ level_constants = torch.tensor(constants, dtype=grid_dtype, device=nlaf.device).view(-1, 5, 2)
+
+ # The folded grid and its remap intermediates scale with B*N*PS^2, so sampling is chunked
+ # along N to bound peak memory; each chunk repeats exactly the single-call arithmetic, and
+ # for small workloads the loop is a single iteration.
+ out = torch.empty(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)
+ chunk = _grid_chunk_lafs(B, N, ch, PS, _grid_elem_bytes(grid_dtype))
+ # Invalid (non-finite) LAFs carry level -1: they index the level-0 constants here and their
+ # patches are zeroed after the loop, unconditionally -- a data-dependent Python branch would
+ # break the fullgraph `torch.compile` path.
+ safe_pyr_idx = pyr_idx.clamp(min=0)
+ for st in range(0, N, chunk):
+ en = min(st + chunk, N)
+ nc = en - st
+ theta = torch.cat([laf_a[:, st:en], torch.zeros(B, nc, 2, 1, dtype=grid_dtype, device=nlaf.device)], dim=-1)
+ grid = F.affine_grid(theta.view(B * nc, 2, 3), [B * nc, ch, PS, PS], align_corners=False).view(B, nc, PS, PS, 2)
+ k, lo, hi, level_scale, level_offset = (
+ level_constants[safe_pyr_idx[:, st:en]].view(B, nc, 1, 1, 5, 2).unbind(-2)
+ )
+ grid = grid * k
+ grid = grid + t[:, st:en].view(B, nc, 1, 1, 2)
+ grid = grid.maximum(lo)
+ grid = grid.minimum(hi)
+ grid = grid * level_scale
+ grid = grid + level_offset
+ out[:, st:en] = _sample_patches(atlas, grid, atlas_h, atlas_w)
+ return out.masked_fill_((pyr_idx < 0).view(B, N, 1, 1, 1), 0.0)
def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:
diff --git a/testing/base.py b/testing/base.py
index ace21b614..228c6c83b 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -194,26 +194,6 @@ def supports_replicate_padding(device: torch.device, dtype: torch.dtype) -> bool
return _supports_kernel_probe(_replicate_padding_op, device.type, dtype)
-def _grid_sample_op(device_type: str, dtype: torch.dtype) -> None:
- F.grid_sample(
- _probe_zeros(device_type, dtype, 1, 1, 2, 2),
- _probe_zeros(device_type, dtype, 1, 2, 2, 2),
- align_corners=False,
- )
-
-
-def supports_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:
- """Whether this device has a 2D ``grid_sample`` kernel for ``dtype``.
-
- Patch extraction (:func:`kornia.feature.extract_patches_from_pyramid`, and so every LAF
- orienter, affine-shape estimator and descriptor pipeline built on it) samples that way.
- torch 2.5.1 has no float16 or bfloat16 CPU ``grid_sampler_2d``, so a test that hardcodes a
- half dtype rather than reading the injected one fails there on every job. Probed at runtime
- and cached per (device type, dtype), like :func:`supports_replicate_padding`.
- """
- return _supports_kernel_probe(_grid_sample_op, device.type, dtype)
-
-
def _conv2d_op(device_type: str, dtype: torch.dtype) -> None:
F.conv2d(_probe_zeros(device_type, dtype, 1, 1, 3, 3), _probe_zeros(device_type, dtype, 1, 1, 2, 2))
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index c8d97d0db..3d44fc419 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -24,7 +24,7 @@ from kornia.feature.affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeE
from kornia.feature.laf import make_upright
from kornia.filters import get_gaussian_kernel2d
-from testing.base import BaseTester, supports_grid_sample
+from testing.base import BaseTester
class DegenerateShape(torch.nn.Module):
@@ -201,9 +201,6 @@ class TestLAFAffineShapeEstimator(BaseTester):
# Keep the end-to-end assertion to pin the public finite-value and finite-gradient boundary.
if device.type == "mps":
pytest.skip("MPS autocast changes the effective dtype")
- if not supports_grid_sample(device, dtype):
- # Patch extraction still runs in the input dtype; the moment estimator promotes to float32.
- pytest.skip(f"no float16 grid_sample kernel on {device.type}")
y = torch.linspace(0, 1, 32, device=device, dtype=dtype).view(32, 1).expand(32, 32)
x = torch.linspace(0, 1e-4, 32, device=device, dtype=dtype).view(1, 32).expand(32, 32)
img = (y + x).view(1, 1, 32, 32).clone().requires_grad_()
@@ -223,8 +220,6 @@ class TestLAFAffineShapeEstimator(BaseTester):
pytest.skip("half-precision regression test")
if device.type == "mps":
pytest.skip("MPS autocast changes the effective dtype")
- if not supports_grid_sample(device, dtype):
- pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
laf = torch.tensor([[[[0.0, 0.0, 16.0], [0.0, 0.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
aff = LAFAffineShapeEstimator(32, DegenerateShape(), preserve_orientation=preserve_orientation).to(
@@ -289,8 +284,6 @@ class TestLAFAffineShapeEstimator(BaseTester):
class TestLAFAffNetShapeEstimator(BaseTester):
def test_singular_prediction_falls_back_upright(self, device, dtype):
- if dtype in (torch.float16, torch.bfloat16) and not supports_grid_sample(device, dtype):
- pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
laf = torch.tensor([[[[0.0, 8.0, 16.0], [-8.0, 0.0, 16.0]]]], device=device, dtype=dtype)
aff = LAFAffNetShapeEstimator(preserve_orientation=False).to(device, dtype)
@@ -304,8 +297,6 @@ class TestLAFAffNetShapeEstimator(BaseTester):
pytest.skip("half-precision regression test")
if device.type == "mps":
pytest.skip("MPS autocast changes the effective dtype")
- if not supports_grid_sample(device, dtype):
- pytest.skip(f"no {dtype} grid_sample kernel on {device.type}")
img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)
laf = torch.tensor([[[[0.0, 0.0, 16.0], [0.0, 0.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)
aff = LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation).to(device, dtype)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index afe2e00fc..03be335c3 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -16,6 +16,9 @@
#
import math
+import subprocess
+import sys
+import textwrap
import pytest
import torch
@@ -590,6 +593,31 @@ class TestClampGridToPixelCenters(BaseTester):
self.assert_close(actual.cpu(), expected)
+# The two half-precision border tests below are CPU-only, for two reasons. The broken kernel and
+# the float32 workaround that routes around it are CPU-specific, so no other device exercises
+# anything the rest of the suite misses; and the half dtype comes from a `half_dtype` parameter,
+# which the CUDA half-precision isolation in `conftest.py` does not see -- both
+# `_is_subprocess_isolated_test` and `skip_half_precision_on_cuda` key on the global `dtype`
+# fixture (`dtype_name`). A `--device=cuda --dtype=float32` job would therefore run half kernels
+# in the shared CUDA context with no subprocess isolation, where a device-side assert poisons
+# every later test in the process. MPS autocast changes the effective dtype as well.
+_HALF_BORDER_SKIP = "the reduced-precision `grid_sample` gap and its float32 workaround are CPU-only"
+
+
+def _corner_border_laf(device, dtype, scale: float = 8.0, angle_deg: float = 15.0, center: float = 255.0):
+ """Build a rotated LAF centered on the last pixel of a 256x256 image.
+
+ Its patch straddles the image corner, so half of the sampling grid falls outside the frame and
+ is served by the border padding. ``scale`` is below the patch size used by the tests (16), so
+ ``extract_patches_from_pyramid`` routes it through pyramid level 0: at a downsampled level the
+ repeated blur turns the patch into a near-constant that hides a bad read.
+ """
+ t = math.radians(angle_deg)
+ cos, sin = scale * math.cos(t), scale * math.sin(t)
+ laf = torch.tensor([[cos, -sin, center], [sin, cos, center]], device=device, dtype=dtype)
+ return laf.view(1, 1, 2, 3).expand(1, 3, 2, 3)
+
+
class TestExtractPatchesSimple(BaseTester):
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)
@@ -608,6 +636,72 @@ class TestExtractPatchesSimple(BaseTester):
assert patches.mean().item() > 0.01
assert patches.shape == (1, 1, 1, PS, PS)
+ def test_exception(self, device, dtype):
+ # Batch disagreement is rejected at the boundary with a clear message instead of an
+ # internal `grid_sample` error or a silently truncated result.
+ img = torch.rand(3, 1, 32, 32, device=device, dtype=dtype)
+ with pytest.raises(Exception, match="same batch size"):
+ kornia.feature.extract_patches_simple(img, torch.rand(1, 2, 2, 3, device=device, dtype=dtype), 8)
+
+ def test_mixed_dtype_laf_under_autocast(self, device):
+ # Reduced-precision detectors commonly emit a half/bfloat16 LAF while their source image
+ # remains float32. The extractor owns this small conversion instead of rejecting a valid
+ # autocast pipeline or relying on backend-specific grid_sample promotion.
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("autocast coverage is provided by CPU and CUDA")
+ laf_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ img = torch.rand(1, 1, 32, 32, device=device)
+ laf = torch.tensor([[4.0, 0.0, 16.0], [0.0, 4.0, 16.0]], device=device, dtype=laf_dtype).view(1, 1, 2, 3)
+ with torch.autocast(device_type=device.type, dtype=laf_dtype):
+ actual = kornia.feature.extract_patches_simple(img, laf, 8)
+ expected = kornia.feature.extract_patches_simple(img, laf.float(), 8)
+ assert actual.dtype == img.dtype
+ self.assert_close(actual, expected)
+
+ def test_mixed_dtype_preserves_laf_precision(self, device):
+ # A float32 LAF paired with a half image must not be rounded to half and then upcast: its
+ # subpixel coordinates are the reason grid arithmetic uses a promoted dtype.
+ if device.type != "cpu":
+ pytest.skip("CPU provides deterministic reduced-precision reference coverage")
+ img = torch.rand(1, 1, 32, 32).to(torch.float16)
+ laf = torch.tensor([[4.1234, 0.2712, 15.789], [-0.1923, 3.9876, 16.321]]).view(1, 1, 2, 3)
+ actual = kornia.feature.extract_patches_simple(img, laf, 8)
+ expected = kornia.feature.extract_patches_simple(img.float(), laf, 8).to(img.dtype)
+ assert actual.dtype == img.dtype
+ assert torch.equal(actual, expected)
+
+ def test_nonfinite_laf_returns_zero_patch_with_safe_backward(self, device, dtype):
+ # Same contract as `TestExtractPatchesPyr`: a training-time detector can emit a non-finite
+ # LAF frame, including one whose only invalid entry is its center. The whole frame is
+ # sanitized before any grid arithmetic, so it returns a zero patch and a zero gradient
+ # rather than handing `grid_sample` an invalid grid -- whose CPU border-padding backward
+ # kernel can segfault the process. Infinity is invalid for the same API-level reason.
+ PS = 8
+ img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ nan = float("nan")
+ inf = float("inf")
+ laf = torch.tensor(
+ [
+ [[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]],
+ [[nan, nan, nan], [nan, nan, nan]],
+ [[8.0, 0.0, nan], [0.0, 8.0, nan]],
+ [[8.0, 0.0, inf], [0.0, 8.0, inf]],
+ ],
+ device=device,
+ dtype=dtype,
+ ).view(1, 4, 2, 3)
+
+ expected_finite = kornia.feature.extract_patches_simple(img, laf[:, :1], PS)
+ grad_img = img.detach().clone().requires_grad_()
+ grad_laf = laf.detach().clone().requires_grad_()
+ patches = kornia.feature.extract_patches_simple(grad_img, grad_laf, PS)
+ self.assert_close(patches[:, :1], expected_finite)
+ assert patches[:, 1:].abs().sum().item() == 0
+ patches.sum().backward()
+ assert grad_img.grad is not None and bool(grad_img.grad.isfinite().all())
+ assert grad_laf.grad is not None and bool(grad_laf.grad.isfinite().all())
+ assert grad_laf.grad[:, 1:].abs().sum().item() == 0
+
def test_same_odd(self, device, dtype):
img = torch.arange(5)[None].repeat(5, 1)[None, None].to(device, dtype)
laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
@@ -629,6 +723,110 @@ class TestExtractPatchesSimple(BaseTester):
PS = 11
self.gradcheck(kornia.feature.extract_patches_simple, (img, nlaf, PS, False), fast_mode=False)
+ def test_batch_independence(self, device, dtype):
+ # Each patch must come only from its own batch element.
+ B, N, PS = 3, 4, 8
+ img = torch.arange(B, device=device, dtype=dtype).view(B, 1, 1, 1).expand(B, 1, 32, 32).contiguous()
+ laf = torch.tensor([[4.0, 0.0, 16.0], [0.0, 4.0, 16.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ patches = kornia.feature.extract_patches_simple(img, laf.expand(B, N, 2, 3), PS)
+ assert patches.shape == (B, N, 1, PS, PS)
+ expected = torch.arange(B, device=device, dtype=dtype).view(B, 1, 1, 1, 1).expand(B, N, 1, PS, PS)
+ self.assert_close(patches, expected)
+
+ def test_empty(self, device, dtype):
+ # Degenerate shapes follow the empty-in -> empty-out convention instead of raising from
+ # inside `affine_grid`.
+ PS = 8
+ patches = kornia.feature.extract_patches_simple(
+ torch.rand(0, 2, 32, 32, device=device, dtype=dtype), torch.rand(0, 3, 2, 3, device=device, dtype=dtype), PS
+ )
+ assert patches.shape == (0, 3, 2, PS, PS)
+ assert patches.dtype == dtype
+ patches = kornia.feature.extract_patches_simple(
+ torch.rand(2, 1, 32, 32, device=device, dtype=dtype), torch.rand(2, 0, 2, 3, device=device, dtype=dtype), PS
+ )
+ assert patches.shape == (2, 0, 1, PS, PS)
+
+ def test_chunked_matches_single_call(self, device, dtype, monkeypatch):
+ # Forcing one LAF per chunk must reproduce the single-call result exactly, since
+ # chunking only splits the grid along N.
+ import kornia.feature.laf as laf_module
+
+ torch.manual_seed(0)
+ img = torch.rand(2, 3, 48, 64, device=device, dtype=dtype)
+ laf = torch.rand(2, 5, 2, 3, device=device, dtype=dtype)
+ expected = kornia.feature.extract_patches_simple(img, laf, 8)
+ monkeypatch.setattr(laf_module, "_grid_chunk_lafs", lambda *args: 1)
+ chunked = kornia.feature.extract_patches_simple(img, laf, 8)
+ self.assert_close(chunked, expected)
+ if device.type == "cpu":
+ assert torch.equal(chunked, expected)
+
+ def test_chunk_budget_accounts_for_channels(self):
+ # A high-channel feature map can make the sampled chunk much larger than its 2-coordinate
+ # grid. Both transient tensors must respect the workspace budget.
+ import kornia.feature.laf as laf_module
+
+ assert laf_module._grid_chunk_lafs(1, 1000, 1, 32, 4) == 1000
+ assert laf_module._grid_chunk_lafs(1, 1000, 256, 32, 4) == 64
+
+ def test_channel_laf_correspondence(self, device, dtype):
+ # The patch at [b, n] must equal the one extracted for that LAF alone. At ch=1 or N=1 a
+ # scrambled unfold is bit-identical to the right one (it permutes a size-1 dim), so this
+ # pins ch>1 together with N>1 and distinct LAFs.
+ B, N, ch, PS = 2, 4, 3, 8
+ torch.manual_seed(0)
+ img = torch.rand(B, ch, 48, 48, device=device, dtype=dtype)
+ laf = torch.rand(B, N, 2, 3, device=device, dtype=dtype)
+ patches = kornia.feature.extract_patches_simple(img, laf, PS)
+ for b in range(B):
+ for n in range(N):
+ single = kornia.feature.extract_patches_simple(img[b : b + 1], laf[b : b + 1, n : n + 1], PS)
+ self.assert_close(patches[b, n], single[0, 0])
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_border_patches_stay_in_range(self, device, half_dtype):
+ # A patch straddling the frame reads border pixels, so every sampled value is a convex
+ # combination of image values and cannot leave the image's range. The float16/bfloat16 CPU
+ # `grid_sample` kernels in torch <= 2.9 read out of bounds for such coordinates and return
+ # zeros, values of order 1e4 or NaN depending on what the heap happens to hold, so the
+ # extractor samples reduced-precision CPU images in float32. Parametrized on the dtype
+ # rather than taking the global `dtype` fixture: CI runs the suite in float32/float64 only,
+ # where the kernel is sound and this test cannot fail.
+ if device.type != "cpu":
+ pytest.skip(_HALF_BORDER_SKIP)
+ torch.manual_seed(0)
+ img = torch.rand(1, 1, 256, 256, device=device).to(half_dtype)
+ laf = _corner_border_laf(device, half_dtype)
+ patches = kornia.feature.extract_patches_simple(img, laf, 16)
+ assert patches.dtype == half_dtype
+ assert bool(patches.isfinite().all())
+ assert patches.min() >= img.min()
+ assert patches.max() <= img.max()
+
+ def test_laf_on_another_device(self, device, dtype):
+ # The sampling grid follows the LAF, so it has to be moved to the image: this function has
+ # always accepted a LAF on a different device than the image and returned a patch on the
+ # image's device.
+ if device.type == "cpu":
+ pytest.skip("needs a second device besides the CPU")
+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)
+ laf = torch.tensor([[4.0, 0.0, 16.0], [0.0, 4.0, 16.0]], dtype=dtype).view(1, 1, 2, 3)
+ patches = kornia.feature.extract_patches_simple(img, laf, 8)
+ assert patches.device == img.device
+ self.assert_close(patches, kornia.feature.extract_patches_simple(img, laf.to(device), 8))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ laf = torch.rand(2, 4, 2, 3, device=device, dtype=dtype)
+ img = torch.rand(2, 1, 40, 30, device=device, dtype=dtype)
+ expected = kornia.feature.extract_patches_simple(img, laf, 10)
+ op = torch_optimizer(kornia.feature.extract_patches_simple)
+ self.assert_close(op(img, laf, 10), expected)
+ # The fixture compiles without `fullgraph`, so it would pass on a graph break too, and the
+ # extractor is meant to trace as one graph -- assert that directly.
+ torch._dynamo.reset()
+ self.assert_close(torch.compile(kornia.feature.extract_patches_simple, fullgraph=True)(img, laf, 10), expected)
+
class TestExtractPatchesPyr(BaseTester):
def test_shape(self, device):
@@ -664,13 +862,217 @@ class TestExtractPatchesPyr(BaseTester):
def test_small_image_single_level(self, device, dtype):
# When min(H, W) < 2 * PS, the pyramid cannot descend beyond level 0.
- # All patches must still have the correct shape and non-zero content.
+ # Sampling that image directly must retain the plain extractor's border behavior without
+ # allocating a one-level atlas.
PS = 16
img = torch.rand(1, 1, 24, 24, device=device, dtype=dtype) # 24 < 2*16=32 β†’ only level 0
- laf = torch.tensor([[6.0, 0.0, 12.0], [0.0, 6.0, 12.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ laf = torch.tensor([[6.0, 0.0, 2.0], [0.0, 6.0, 2.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
assert patches.shape == (1, 1, 1, PS, PS)
assert patches.abs().sum().item() > 0
+ self.assert_close(patches, kornia.feature.extract_patches_simple(img, laf, PS))
+
+ def test_exception(self, device, dtype):
+ # Batch disagreement is rejected at the boundary with a clear message instead of an
+ # internal broadcasting error or a silently truncated result.
+ img = torch.rand(3, 1, 32, 32, device=device, dtype=dtype)
+ with pytest.raises(Exception, match="same batch size"):
+ kornia.feature.extract_patches_from_pyramid(img, torch.rand(1, 2, 2, 3, device=device, dtype=dtype), 8)
+
+ def test_mixed_dtype_laf_under_autocast(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("autocast coverage is provided by CPU and CUDA")
+ laf_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ img = torch.rand(1, 1, 64, 64, device=device)
+ laf = torch.tensor([[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]], device=device, dtype=laf_dtype).view(1, 1, 2, 3)
+ with torch.autocast(device_type=device.type, dtype=laf_dtype):
+ actual = kornia.feature.extract_patches_from_pyramid(img, laf, 8)
+ expected = kornia.feature.extract_patches_from_pyramid(img, laf.float(), 8)
+ assert actual.dtype == img.dtype
+ self.assert_close(actual, expected)
+
+ def test_mixed_dtype_preserves_laf_precision(self, device):
+ if device.type != "cpu":
+ pytest.skip("CPU provides deterministic reduced-precision reference coverage")
+ img = torch.rand(1, 1, 64, 64).to(torch.float16)
+ laf = torch.tensor([[8.1234, 0.2712, 31.789], [-0.1923, 7.9876, 32.321]]).view(1, 1, 2, 3)
+ actual = kornia.feature.extract_patches_from_pyramid(img, laf, 8)
+ expected = kornia.feature.extract_patches_from_pyramid(img.float(), laf, 8).to(img.dtype)
+ assert actual.dtype == img.dtype
+ assert torch.equal(actual, expected)
+
+ def test_one_pixel_axis_does_not_raise(self, device, dtype):
+ # A 1-pixel image axis has no spatial extent. `normalize_laf`/`denormalize_laf` count it as
+ # one pixel instead of dividing by zero, and the levelwise sampler uses a zero grid scale
+ # for that axis, so the only real pixel is repeated instead of leaking a NaN. Both the
+ # default pixel-LAF entry point and the pre-normalized one stay finite, on both extractors.
+ for shape in ((1, 1, 5, 1), (1, 1, 1, 5)):
+ img = torch.rand(shape, device=device, dtype=dtype)
+ laf = torch.rand(1, 1, 2, 3, device=device, dtype=dtype)
+ for normalize_lafs in (False, True):
+ for extract in (
+ kornia.feature.extract_patches_from_pyramid,
+ kornia.feature.extract_patches_simple,
+ ):
+ patches = extract(img, laf, 4, normalize_lafs)
+ assert patches.shape == (1, 1, 1, 4, 4)
+ assert bool(patches.isfinite().all())
+
+ def test_one_pixel_axis_preserves_non_singleton_extent(self, device, dtype):
+ # A singleton axis must collapse only itself. The other axis still has spatial extent, so
+ # a full-image LAF over a 1x5 or 5x1 ramp must retain that ramp instead of degenerating to
+ # the center pixel in both directions.
+ for h, w in ((1, 5), (5, 1)):
+ img = torch.arange(5, device=device, dtype=dtype).reshape(1, 1, h, w)
+ pixel_laf = torch.tensor(
+ [
+ [float(max(w - 1, 1)) / 2.0, 0.0, float(w - 1) / 2.0],
+ [0.0, float(max(h - 1, 1)) / 2.0, float(h - 1) / 2.0],
+ ],
+ device=device,
+ dtype=dtype,
+ ).view(1, 1, 2, 3)
+ normalized_laf = kornia.feature.normalize_laf(pixel_laf, img)
+ expected = img.expand(1, 1, 5, 5).unsqueeze(1)
+
+ for laf, normalize_lafs in ((pixel_laf, True), (normalized_laf, False)):
+ simple = kornia.feature.extract_patches_simple(img, laf, 5, normalize_lafs)
+ pyramid = kornia.feature.extract_patches_from_pyramid(img, laf, 5, normalize_lafs)
+ self.assert_close(simple, expected)
+ self.assert_close(pyramid, expected)
+
+ @pytest.mark.parametrize("height,width", [(12, 12), (8, 8), (2, 8), (8, 2)])
+ def test_one_pixel_level_does_not_raise(self, device, dtype, height, width):
+ # PS=1 can make a pyramid descend to a 1-pixel level. A 12-pixel axis reaches it safely
+ # through 12 -> 6 -> 3 -> 1, while a power-of-two or rectangular axis reaches 2 first;
+ # `pyrdown` cannot reflect-pad that 2-pixel source, so it must remain the coarsest usable
+ # level instead of attempting the final downsample.
+ img = torch.rand(1, 1, height, width, device=device, dtype=dtype)
+ laf = torch.tensor([[3.0, 0.0, width / 2.0], [0.0, 3.0, height / 2.0]], device=device, dtype=dtype).view(
+ 1, 1, 2, 3
+ )
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, 1)
+ assert patches.shape == (1, 1, 1, 1, 1)
+ assert bool(patches.isfinite().all())
+
+ def test_nonfinite_laf_returns_zero_patch_with_safe_backward(self, device, dtype, monkeypatch):
+ # A training-time detector can emit a non-finite LAF frame. Passing a NaN grid to the CPU
+ # border-padding backward kernel can segfault the process, even when forward output is
+ # zeroed afterwards. Both paths must sanitize the whole frame before sampling, including
+ # when only its center is invalid, and return zero output/gradient without changing finite
+ # frames. Infinity is invalid for the same API-level reason, independent of backend quirks.
+ import kornia.feature.laf as laf_module
+
+ PS = 8
+ img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ nan = float("nan")
+ inf = float("inf")
+ laf = torch.tensor(
+ [
+ [[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]],
+ [[nan, nan, nan], [nan, nan, nan]],
+ [[8.0, 0.0, nan], [0.0, 8.0, nan]],
+ [[8.0, 0.0, inf], [0.0, 8.0, inf]],
+ ],
+ device=device,
+ dtype=dtype,
+ ).view(1, 4, 2, 3)
+
+ expected_finite = kornia.feature.extract_patches_from_pyramid(img, laf[:, :1], PS)
+ for atlas_fits in (True, False):
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args, fits=atlas_fits: fits)
+ grad_img = img.detach().clone().requires_grad_()
+ grad_laf = laf.detach().clone().requires_grad_()
+ patches = kornia.feature.extract_patches_from_pyramid(grad_img, grad_laf, PS)
+ self.assert_close(patches[:, :1], expected_finite)
+ assert patches[:, 1:].abs().sum().item() == 0
+ patches.sum().backward()
+ assert grad_img.grad is not None and bool(grad_img.grad.isfinite().all())
+ assert grad_laf.grad is not None and bool(grad_laf.grad.isfinite().all())
+ assert grad_laf.grad[:, 1:].abs().sum().item() == 0
+
+ def test_giant_laf_uses_actual_coarsest_level(self, device, dtype):
+ # The nominal level for this LAF is beyond the levels that can provide a PS-sized
+ # patch. It must sample the actual coarsest level rather than becoming zero padding.
+ PS = 16
+ img = torch.arange(128 * 128, device=device, dtype=dtype).reshape(1, 1, 128, 128)
+ # The LAF is deliberately float32: 1e5 overflows float16 to infinity, which the non-finite
+ # contract turns into a zero patch, so a half LAF would test the opposite behavior. Paired
+ # with the injected image dtype it keeps the giant *finite* case under test on every dtype
+ # and exercises the mixed-dtype promotion path at the same time.
+ laf = torch.tensor([[1.0e5, 0.0, 64.0], [0.0, 1.0e5, 64.0]], device=device, dtype=torch.float32).view(
+ 1, 1, 2, 3
+ )
+
+ actual = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ nlaf = kornia.feature.normalize_laf(laf, img)
+ # Build the reference pyramid the way the extractor does for half dtypes -- in float32 --
+ # so the reference itself does not hit the missing half reflect-pad kernel on old torch.
+ coarsest = img.float() if dtype in (torch.float16, torch.bfloat16) else img
+ for _ in range(3):
+ coarsest = kornia.geometry.transform.pyrdown(coarsest)
+ expected = kornia.feature.extract_patches_simple(coarsest.to(dtype), nlaf, PS, False)
+
+ self.assert_close(actual, expected)
+ assert actual.abs().sum().item() > 0
+
+ def test_oversized_atlas_uses_equivalent_levelwise_fallback(self, device, dtype, monkeypatch):
+ import kornia.feature.laf as laf_module
+
+ PS = 16
+ img = torch.rand(1, 1, 65, 97, device=device, dtype=dtype)
+ laf = torch.tensor(
+ [[[4.0, 0.0, 48.0], [0.0, 4.0, 32.0]], [[24.0, 0.0, 48.0], [0.0, 24.0, 32.0]]],
+ device=device,
+ dtype=dtype,
+ ).view(1, 2, 2, 3)
+
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: False)
+ fallback = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: True)
+ atlas = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+
+ self.assert_close(fallback, atlas)
+
+ def test_atlas_guards_preserve_level_border_value_and_gradient(self, device, dtype, monkeypatch):
+ import kornia.feature.laf as laf_module
+
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the coordinate-rounding leak this test pins is below half-precision resolution")
+
+ def sample(limit, size, patch_size):
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: limit > 0)
+ img = torch.zeros(1, 1, size, size, device=device, dtype=dtype)
+ img[:, :, :, -1] = 1.0
+ # A quarter pixel OUTSIDE the outermost pixel center, so the clamp engages strictly on
+ # every backend: probing exactly at the center can round onto the clamp bound, where
+ # the subgradient convention differs between CPU and MPS.
+ center_x = 1.0 - 1.0 / (4.0 * size)
+ nlaf = torch.tensor(
+ [[[[0.0, 0.0, center_x], [0.0, 0.0, 0.5]]]], device=device, dtype=dtype, requires_grad=True
+ )
+ patch = kornia.feature.extract_patches_from_pyramid(img, nlaf, patch_size, False)
+ value = patch[0, 0, 0, patch_size // 2, patch_size // 2]
+ grad = torch.autograd.grad(value, nlaf)[0][0, 0, 0, 2]
+ return patch, grad
+
+ # 2495 exposes a forward-coordinate rounding leak without guards; 32 exposes the
+ # non-zero outward center gradient even when the rounded forward value happens to match.
+ # The discriminating pin is the patch CENTER: its sampling coordinate is clamped to the
+ # border-pixel center, so with the guard both bilinear partners are exactly the border
+ # value and the sample stays within a couple of float32 ulp of 1.0, while a missing guard
+ # blends in the neighbouring level at the coordinate-rounding scale (~5e-5 in float32 at
+ # size 2495, measured). Interior pixels legitimately differ between the atlas and
+ # levelwise paths at that same rounding scale -- and across platforms -- so the
+ # whole-patch comparison uses the standard tolerances instead of `torch.equal`.
+ for size, patch_size in ((2495, 8), (32, 5)):
+ fallback, fallback_grad = sample(0, size, patch_size)
+ atlas, atlas_grad = sample(1 << 60, size, patch_size)
+ self.assert_close(atlas, fallback)
+ center = patch_size // 2
+ assert abs(atlas[0, 0, 0, center, center].item() - 1.0) < 1e-5
+ assert abs(fallback[0, 0, 0, center, center].item() - 1.0) < 1e-5
+ assert atlas_grad == fallback_grad == 0.0
def test_multi_level_uses_correct_pyramid_level(self, device, dtype):
# Two LAFs with very different scales should be extracted from different pyramid levels.
@@ -695,6 +1097,236 @@ class TestExtractPatchesPyr(BaseTester):
nondet_tol=1e-8,
)
+ def test_gradcheck_chunked(self, device, monkeypatch):
+ # Gradients must survive the chunked sampling loop and its slice writes, on both the
+ # atlas path and the levelwise fallback.
+ import kornia.feature.laf as laf_module
+
+ monkeypatch.setattr(laf_module, "_grid_chunk_lafs", lambda *args: 1)
+ nlaf = torch.tensor(
+ [[[0.1, 0.001, 0.4], [0.0, 0.1, 0.5]], [[0.05, 0.0, 0.6], [0.0, 0.05, 0.4]]],
+ device=device,
+ dtype=torch.float64,
+ ).view(1, 2, 2, 3)
+ img = torch.rand(1, 2, 20, 30, device=device, dtype=torch.float64)
+ self.gradcheck(kornia.feature.extract_patches_from_pyramid, (img, nlaf, 7, False), nondet_tol=1e-8)
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: False)
+ self.gradcheck(kornia.feature.extract_patches_from_pyramid, (img, nlaf, 7, False), nondet_tol=1e-8)
+
+ def test_batch_independence(self, device, dtype):
+ # Each patch must come only from its own batch element, across pyramid levels: the two
+ # scales route the patches through level 0 and a downsampled level respectively.
+ B, PS = 3, 8
+ img = torch.arange(B, device=device, dtype=dtype).view(B, 1, 1, 1).expand(B, 1, 64, 64).contiguous()
+ laf_small = torch.tensor([[4.0, 0.0, 32.0], [0.0, 4.0, 32.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ laf_large = torch.tensor([[16.0, 0.0, 32.0], [0.0, 16.0, 32.0]], device=device, dtype=dtype).view(1, 1, 2, 3)
+ laf = torch.cat([laf_small, laf_large], dim=1).expand(B, 2, 2, 3)
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ assert patches.shape == (B, 2, 1, PS, PS)
+ expected = torch.arange(B, device=device, dtype=dtype).view(B, 1, 1, 1, 1).expand(B, 2, 1, PS, PS)
+ self.assert_close(patches, expected)
+
+ def test_empty(self, device, dtype):
+ # Degenerate shapes follow the empty-in -> empty-out convention: the batched rewrite must
+ # not call `affine_grid` on an empty batch (main returned an empty result for B=0).
+ PS = 8
+ patches = kornia.feature.extract_patches_from_pyramid(
+ torch.rand(0, 2, 32, 32, device=device, dtype=dtype), torch.rand(0, 3, 2, 3, device=device, dtype=dtype), PS
+ )
+ assert patches.shape == (0, 3, 2, PS, PS)
+ assert patches.dtype == dtype
+ patches = kornia.feature.extract_patches_from_pyramid(
+ torch.rand(2, 1, 32, 32, device=device, dtype=dtype), torch.rand(2, 0, 2, 3, device=device, dtype=dtype), PS
+ )
+ assert patches.shape == (2, 0, 1, PS, PS)
+
+ def test_chunked_matches_single_call(self, device, dtype, monkeypatch):
+ # Forcing one LAF per chunk must reproduce the single-call result on both the atlas path
+ # and the levelwise fallback, since chunking only splits the grid along N.
+ import kornia.feature.laf as laf_module
+
+ torch.manual_seed(0)
+ PS = 8
+ img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
+ laf = torch.zeros(2, 5, 2, 3, device=device, dtype=dtype)
+ laf[..., 0, 0] = laf[..., 1, 1] = torch.tensor([2.0, 4.0, 9.0, 17.0, 33.0], device=device, dtype=dtype)
+ laf[..., :, 2] = torch.rand(2, 5, 2, device=device, dtype=dtype) * 40 + 12
+ default_chunk = laf_module._grid_chunk_lafs
+ expected = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ monkeypatch.setattr(laf_module, "_grid_chunk_lafs", lambda *args: 1)
+ chunked = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ self.assert_close(chunked, expected)
+ if device.type == "cpu":
+ assert torch.equal(chunked, expected)
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: False)
+ fallback_chunked = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ monkeypatch.setattr(laf_module, "_grid_chunk_lafs", default_chunk)
+ fallback_expected = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ self.assert_close(fallback_chunked, fallback_expected)
+ if device.type == "cpu":
+ assert torch.equal(fallback_chunked, fallback_expected)
+
+ def test_channel_laf_correspondence(self, device, dtype):
+ # The patch at [b, n] must equal the one extracted for that LAF alone. At ch=1 or N=1 a
+ # scrambled unfold is bit-identical to the right one (it permutes a size-1 dim), so this
+ # pins ch>1 together with N>1, across pyramid levels.
+ B, N, ch, PS = 2, 4, 3, 8
+ torch.manual_seed(0)
+ img = torch.rand(B, ch, 64, 64, device=device, dtype=dtype)
+ laf = torch.zeros(B, N, 2, 3, device=device, dtype=dtype)
+ laf[..., 0, 0] = laf[..., 1, 1] = torch.tensor([3.0, 6.0, 17.0, 33.0], device=device, dtype=dtype)
+ laf[..., :, 2] = torch.rand(B, N, 2, device=device, dtype=dtype) * 40 + 12
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, PS)
+ for b in range(B):
+ for n in range(N):
+ single = kornia.feature.extract_patches_from_pyramid(img[b : b + 1], laf[b : b + 1, n : n + 1], PS)
+ self.assert_close(patches[b, n], single[0, 0])
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_border_patches_stay_in_range(self, device, half_dtype):
+ # Same border read as in `TestExtractPatchesSimple`, at pyramid level 0: `_corner_border_laf`
+ # has a scale below the patch size, so the patch comes from the undownsampled image and the
+ # level-0 result must equal the plain extractor's byte for byte. A larger LAF would be served
+ # by a blurred level whose near-constant patch stays in range even when the read is wrong.
+ # The whole pyramid (pad, `pyrdown`, sampling) runs in float32 for half inputs, so no
+ # reduced-precision pad or `grid_sample` kernel gate is needed on any torch version.
+ if device.type != "cpu":
+ pytest.skip(_HALF_BORDER_SKIP)
+ torch.manual_seed(0)
+ img = torch.rand(1, 1, 256, 256, device=device).to(half_dtype)
+ laf = _corner_border_laf(device, half_dtype)
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, 16)
+ assert patches.dtype == half_dtype
+ assert bool(patches.isfinite().all())
+ assert patches.min() >= img.min()
+ assert patches.max() <= img.max()
+ self.assert_close(patches, kornia.feature.extract_patches_simple(img, laf, 16))
+
+ def test_reduced_precision_level_zero_matches_float_reference(self, device, dtype):
+ # Unlike the explicit half_dtype regression above, this uses the global dtype fixture so
+ # CUDA half tests run in the suite's per-test subprocess isolation. The float32 grid policy
+ # is universal even though the out-of-bounds kernel bug that motivated it is CPU-specific.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("reduced-precision sampling policy")
+ img = torch.rand(1, 1, 256, 256, device=device).to(dtype)
+ laf = _corner_border_laf(device, dtype)
+ simple = kornia.feature.extract_patches_simple(img, laf, 16)
+ pyramid = kornia.feature.extract_patches_from_pyramid(img, laf, 16)
+ reference = kornia.feature.extract_patches_simple(img.float(), laf.float(), 16).to(dtype)
+ assert simple.dtype == pyramid.dtype == dtype
+ assert bool(simple.isfinite().all()) and bool(pyramid.isfinite().all())
+ self.assert_close(simple, reference)
+ self.assert_close(pyramid, reference)
+
+ def test_laf_on_another_device(self, device, dtype, monkeypatch):
+ # The small LAF is moved to the image before grid construction, so the pyramid extractor
+ # accepts a cross-device pair like `extract_patches_simple` -- on the atlas path AND on the
+ # levelwise fallback, which a 64x64 image never reaches on its own (the contract must not
+ # flip with the image size).
+ import kornia.feature.laf as laf_module
+
+ if device.type == "cpu":
+ pytest.skip("needs a second device besides the CPU")
+ img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ laf = torch.tensor([[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]], dtype=dtype).view(1, 1, 2, 3)
+ patches = kornia.feature.extract_patches_from_pyramid(img, laf, 8)
+ assert patches.device == img.device
+ self.assert_close(patches, kornia.feature.extract_patches_from_pyramid(img, laf.to(device), 8))
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: False)
+ fallback = kornia.feature.extract_patches_from_pyramid(img, laf, 8)
+ assert fallback.device == img.device
+ self.assert_close(fallback, kornia.feature.extract_patches_from_pyramid(img, laf.to(device), 8))
+
+ def test_dynamo(self, device, dtype, torch_optimizer, optimizer_backend):
+ if optimizer_backend == "jit":
+ # `pyrdown` -> `filter2d` closes over a `set` of valid border modes, which TorchScript
+ # cannot compile; unrelated to this extractor and to the compile path CI exercises.
+ pytest.skip("`extract_patches_from_pyramid` reaches a non-scriptable `filter2d`")
+ laf = torch.rand(2, 4, 2, 3, device=device, dtype=dtype)
+ img = torch.rand(2, 1, 40, 30, device=device, dtype=dtype)
+ expected = kornia.feature.extract_patches_from_pyramid(img, laf, 10)
+ op = torch_optimizer(kornia.feature.extract_patches_from_pyramid)
+ self.assert_close(op(img, laf, 10), expected)
+ # The fixture compiles without `fullgraph`, so it would pass on a graph break too, and the
+ # extractor is meant to trace as one graph -- assert that directly.
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.extract_patches_from_pyramid, fullgraph=True)
+ self.assert_close(compiled(img, laf, 10), expected)
+
+ def test_dynamo_levelwise_fallback(self, device, dtype, torch_optimizer, optimizer_backend, monkeypatch):
+ import kornia.feature.laf as laf_module
+
+ if optimizer_backend == "jit":
+ # Same TorchScript incompatibility `test_dynamo` skips.
+ pytest.skip("`extract_patches_from_pyramid` reaches a non-scriptable `filter2d`")
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: False)
+ laf = torch.rand(2, 4, 2, 3, device=device, dtype=dtype)
+ img = torch.rand(2, 1, 65, 97, device=device, dtype=dtype)
+ expected = kornia.feature.extract_patches_from_pyramid(img, laf, 16)
+ op = torch_optimizer(kornia.feature.extract_patches_from_pyramid)
+ self.assert_close(op(img, laf, 16), expected)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.extract_patches_from_pyramid, fullgraph=True)
+ self.assert_close(compiled(img, laf, 16), expected)
+
+ def test_dynamo_chunked(self, device, dtype, torch_optimizer, optimizer_backend, monkeypatch):
+ # The chunk loop unrolls at trace time for static shapes; forcing one LAF per chunk
+ # exercises it.
+ import kornia.feature.laf as laf_module
+
+ if optimizer_backend == "jit":
+ # Same TorchScript incompatibility `test_dynamo` skips.
+ pytest.skip("`extract_patches_from_pyramid` reaches a non-scriptable `filter2d`")
+ monkeypatch.setattr(laf_module, "_grid_chunk_lafs", lambda *args: 1)
+ laf = torch.rand(2, 4, 2, 3, device=device, dtype=dtype)
+ img = torch.rand(2, 1, 65, 97, device=device, dtype=dtype)
+ expected = kornia.feature.extract_patches_from_pyramid(img, laf, 16)
+ op = torch_optimizer(kornia.feature.extract_patches_from_pyramid)
+ self.assert_close(op(img, laf, 16), expected)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.extract_patches_from_pyramid, fullgraph=True)
+ self.assert_close(compiled(img, laf, 16), expected)
+
+
+def test_nonfinite_laf_backward_does_not_crash_the_interpreter():
+ """Backward through a non-finite LAF must not take the interpreter down.
+
+ Both extractors advertise zero patches and zero gradients for a non-finite LAF frame. The
+ failure mode of a regression is not a wrong number but a native segfault inside
+ ``grid_sampler_2d_backward`` -- torch's CPU ``padding_mode="border"`` kernel on a NaN grid --
+ which would kill the pytest process itself rather than fail a test. A fresh interpreter turns
+ that into an ordinary assertion on the exit code. CPU-only on purpose: the crashing kernel is
+ the CPU one, and the guard needs no device fixture to be meaningful.
+ """
+ script = textwrap.dedent(
+ """
+ import torch
+
+ import kornia
+
+ img = torch.rand(1, 1, 64, 64, requires_grad=True)
+ # Only the center is invalid: the whole frame must still be treated as invalid.
+ laf = torch.tensor([[[[8.0, 0.0, float("nan")], [0.0, 8.0, 32.0]]]])
+ extractors = (kornia.feature.extract_patches_simple, kornia.feature.extract_patches_from_pyramid)
+ for extract in extractors:
+ patches = extract(img, laf, 8)
+ assert patches.abs().sum().item() == 0.0, extract.__name__
+ patches.sum().backward()
+ assert img.grad is not None and bool(img.grad.isfinite().all())
+ """
+ )
+ # Trusted, fixed command (the current interpreter running a literal script); no external input.
+ result = subprocess.run( # noqa: S603
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=300,
+ )
+ assert result.returncode == 0, (
+ f"non-finite LAF backward exited with {result.returncode}:\n{result.stdout}\n{result.stderr}"
+ )
+
class TestLAFIsTouchingBoundary(BaseTester):
def test_shape(self, device):
diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.py
index bce891d40..574786212 100644
--- a/tests/feature/test_local_features_orientation.py
+++ b/tests/feature/test_local_features_orientation.py
@@ -21,7 +21,7 @@ import torch
from kornia.feature.orientation import LAFOrienter, OriNet, PassLAF, PatchDominantGradientOrientation
from kornia.geometry.conversions import rad2deg
-from testing.base import BaseTester, supports_grid_sample, supports_replicate_padding
+from testing.base import BaseTester, supports_replicate_padding
class TestPassLAF(BaseTester):
@@ -135,10 +135,11 @@ class TestOrientationHalfPrecisionIsFinite(BaseTester):
def test_flat_image_laf(self, device, half_dtype):
if device.type == "mps":
pytest.skip("MPS autocast changes the effective dtype")
- if not (supports_replicate_padding(device, half_dtype) and supports_grid_sample(device, half_dtype)):
- # The orienter extracts patches with `grid_sample` and differentiates them with a
- # replicate pad; torch 2.5.1 has neither CPU kernel for float16, nor `grid_sample` for bfloat16.
- pytest.skip(f"no half-precision patch-extraction kernels for {half_dtype} on {device.type}")
+ if not supports_replicate_padding(device, half_dtype):
+ # The orienter differentiates the extracted patches with a replicate pad, which torch
+ # 2.5.1 has no float16 CPU kernel for. Patch extraction itself samples half inputs in
+ # float32 and needs no `grid_sample` gate on any torch version.
+ pytest.skip(f"no replicate-pad kernel for {half_dtype} on {device.type}")
img = torch.full((1, 1, 32, 32), 0.5, device=device, dtype=half_dtype)
laf = torch.tensor([[[[5.0, 0.0, 16.0], [0.0, 5.0, 16.0]]]], device=device, dtype=half_dtype)
out = LAFOrienter(19).to(device, half_dtype)(laf, img)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 6c2876b54..905dc60b9 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -29,7 +29,7 @@ from kornia.feature.scale_space_detector import (
)
from kornia.geometry.subpix import ConvQuadInterp3d
-from testing.base import BaseTester, supports_conv2d, supports_grid_sample, supports_replicate_padding, supports_topk
+from testing.base import BaseTester, supports_conv2d, supports_replicate_padding, supports_topk
def _require_affine_orientation_kernels(device: torch.device, dtype: torch.dtype) -> None:
@@ -40,7 +40,6 @@ def _require_affine_orientation_kernels(device: torch.device, dtype: torch.dtype
probes = (
("replicate-padding", supports_replicate_padding),
("conv2d", supports_conv2d),
- ("grid-sample", supports_grid_sample),
("topk", supports_topk),
)
for name, probe in probes: