Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(feature): drop the constant homogeneous row from laf_to_boundary_points (#4217)

Dmytro Mishkin64c4d902838e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a308a41b3..b0f8554ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -389,6 +389,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 38f8b80aa..a65890c3b 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -268,12 +268,11 @@ The honest reading:
start by bisecting stack against machine rather than reading the kernel. It is not the
N-chunking added in #4128: at B=1 N=2000 the sampling grid is ~16 MiB against a 64 MiB budget,
so that config takes the single-chunk fast path and still loses.
-- **`laf_to_boundary_points` is the weakest compiled op on CUDA** β€” 17.8M LAFs/s, below both
+- **`laf_to_boundary_points` was the weakest compiled op on CUDA** β€” 17.8M LAFs/s, below both
patch extractors, ~25Γ— below `ellipse_to_laf`, and the least moved by `torch.compile` there
- (1.26Γ—, against up to 9.1Γ— elsewhere). It builds its `linspace`/`ones`/`tensor` basis without a
- `device=` argument and `.to()`s the result on every call (`kornia/feature/laf.py`), so each
- call pays a host→device transfer. On CPU it is ~9× slower than the similar-sized
- `make_upright`. First optimization target in this file.
+ (1.26Γ—, against up to 9.1Γ— elsewhere). On CPU it was ~9Γ— slower than the similar-sized
+ `make_upright`. #4217 removed the cause; see the last bullet for what it actually was. The
+ tables above predate that change, as do their `laf_is_inside_image` rows, which share it.
- **Small N on CUDA is launch-latency bound, not work bound:** at B=1 N=2000 the three cheapest
ops all land within 8.2–14.2M LAFs/s regardless of what they compute, ~8.5–11Γ— below their own
B=1 N=20000 figures. Read the N=20000 rows for kernel cost and the N=2000 rows for per-call
@@ -293,12 +292,22 @@ The honest reading:
`torch.compile` (4.4Γ— and 3.8Γ—). MPS only wins where there is real work per LAF: patch
extraction, by 2.2–2.4Γ— eager and up to 3.4Γ— compiled. A pipeline that moves LAFs to the GPU
for the frame math alone pays for the transfer twice.
-- **`laf_to_boundary_points` is the worst op on every machine measured**, and its CPU numbers say
- why: on the M1 it is 30Γ— below `make_upright` and `torch.compile` recovers only 1.29Γ—, because
- the cost is not a kernel. It builds its 50-point basis with no `device=`, `.expand()`s it to
- `(B*N, n_pts, 3)` and only then calls `.to(device)`, so every call materializes β€” and on a GPU
- transfers β€” a tensor that scales with the LAF count: ~12 MiB per call at N=20000 for a basis
- with 50 distinct rows. Build it on the target device and broadcast in the matmul instead.
+- **`laf_to_boundary_points` was the worst op on every machine measured, and the obvious
+ diagnosis was the wrong one.** It built its 50-point basis with no `device=`, `.expand()`ed it
+ to `(B*N, n_pts, 3)` and only then called `.to(device)`, so every call materialized β€” and on a
+ GPU transferred β€” a tensor scaling with the LAF count: ~12 MiB per call at N=20000 for a basis
+ with 50 distinct rows. That is real, and it is a memory problem, not the speed problem: fixing
+ only it measures **1.00Γ— on CPU**. The cost was one gemm-shape cliff. The op appended a constant
+ `[0, 0, 1]` row to every LAF so that it could divide the result by a homogeneous coordinate that
+ is always exactly 1, and torch's CPU batched gemm falls off a fast path at that third row β€” at
+ B=1 N=20000, `bmm` on a `(B, 3, 3)` operand takes 14.9 ms where `(B, 2, 3)` takes 0.65 ms, 23Γ—
+ for 1.5Γ— the arithmetic, identically at 1, 4 and 8 threads (M=1 0.33 ms, M=2 0.65, M=3 14.87,
+ M=4 16.26). #4217 multiplies by the `(2, 3)` LAF directly. Quiet back-to-back A/B on the 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. **The lesson is the method:**
+ the transfer was visible by reading the source and the cliff was only visible by timing the
+ components, so the readable diagnosis got written up first and would have shipped a 1.00Γ— fix.
## Sample results β€” augmentation flagship (class API)
diff --git a/benchmarks/feature/laf_ops.py b/benchmarks/feature/laf_ops.py
index 4b35afe43..fc9f89c70 100644
--- a/benchmarks/feature/laf_ops.py
+++ b/benchmarks/feature/laf_ops.py
@@ -38,10 +38,10 @@ op why it is here
``laf_from_center_scale_ori`` LAF construction, runs once per detector forward
``make_upright`` orientation reset, per detector forward
``ellipse_to_laf`` Oxford-format import; :mod:`ellipse_to_laf` drills into it
-``laf_to_boundary_points`` visualization export; builds its basis on CPU every call
+``laf_to_boundary_points`` visualization export; also drives ``laf_is_inside_image``
``laf_is_inside_image`` border filtering, per detector forward
-``extract_patches_simple`` patch sampling; Python loop over the batch dimension
-``extract_patches_from_pyramid`` patch sampling; batch loop x full grid_sample per level
+``extract_patches_simple`` patch sampling; one folded ``grid_sample`` since #4128
+``extract_patches_from_pyramid`` patch sampling; one ``grid_sample`` over a packed atlas
=============================== =============================================================
Throughput counts **LAFs per second** (``B*N`` per call) -- the README's "items" for LAF ops.
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 8ba51f5ca..0bf4df562 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -22,7 +22,7 @@ import torch
import torch.nn.functional as F
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.conversions import angle_to_rotation_matrix
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
@@ -323,12 +323,17 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
dim=1,
)
# Add origin to draw also the orientation
- pts = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
- pts = pts.to(LAF.device).to(LAF.dtype)
- aux = torch.tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
- HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
- pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)
- return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
+ pts = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0)
+ # Move the 3-column basis before broadcasting it: expanding first and casting afterwards
+ # materialized -- and on an accelerator transferred -- one copy per LAF (~12 MiB at N = 20000)
+ # of a tensor with `n_pts` distinct rows.
+ pts = pts.to(device=LAF.device, dtype=LAF.dtype).t().unsqueeze(0).expand(B * N, 3, n_pts)
+ # The LAF's implied homogeneous row is the constant [0, 0, 1], so every output point has
+ # homogeneous coordinate exactly 1 and `convert_points_from_homogeneous` would divide by 1.0.
+ # Multiplying by the (2, 3) LAF directly skips both the appended row and that division, and it
+ # keeps `bmm`'s M dimension at 2: measured on torch 2.14 / Apple M1, a `(B, 3, 3)` operand
+ # costs 23x a `(B, 2, 3)` one for 1.5x the arithmetic. See benchmarks/README.md.
+ return torch.bmm(LAF.view(-1, 2, 3), pts).permute(0, 2, 1).reshape(B, N, n_pts, 2)
def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]:
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 692b714a7..792265ca1 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -42,7 +42,7 @@ from .responses import BlobHessian
# angles = linspace(0, 2Ο€, n_pts - 1) = linspace(0, 2Ο€, 11) β†’ k * 2Ο€/10 for k=0..10
# max|sin| at k=2 and k=3: sin(2Ο€/5) β‰ˆ 0.9511; max|cos| at k=0: cos(0) = 1.0
# Used to inline the boundary check in _process_octave for isotropic LAFs (rotmat=eye(2)),
-# avoiding CPU→GPU allocation + bmm every octave.
+# avoiding the basis allocations and the bmm every octave.
_MAX_ABS_SIN_12: float = math.sin(2 * 2 * math.pi / 10) # β‰ˆ 0.9511
@@ -464,7 +464,9 @@ class ScaleSpaceDetector(nn.Module):
# Inline equivalent of laf_is_inside_image(scale_laf(current_lafs, 0.5), octave[:, 0], 5)
# for isotropic LAFs (rotmat = eye(2)). Avoids: scale_laf (torch.cat), and
- # laf_to_boundary_points (linspace/sin/cos allocations + CPU→GPU transfer + bmm).
+ # laf_to_boundary_points (linspace/sin/cos allocations and their launches, plus a small
+ # host->device copy of the basis). Since #4217 that op no longer transfers a tensor that
+ # scales with the LAF count, so what is saved here is per-call overhead, not bandwidth.
# For the axis-aligned isotropic case the 12-pt boundary check reduces to:
# max x-extent = max|sin| * half_s; max y-extent = max|cos| * half_s = half_s
half_s = current_lafs[:, :, 0, 0] * 0.5
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 56f32b632..d3345409f 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -465,6 +465,52 @@ class TestLAF2pts(BaseTester):
laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.feature.laf_to_boundary_points, (laf))
+ def test_matches_explicit_affine_reference(self, device, dtype):
+ """The boundary points are the LAF affine map applied to the origin + unit-circle basis.
+
+ `test_conversion` uses a symmetric 2x2 block, so it passes even if the LAF and the basis are
+ multiplied in the wrong order. This uses random anisotropic LAFs, where they disagree, and
+ pins the equality that lets the implementation multiply by the (2, 3) LAF directly instead
+ of appending a constant `[0, 0, 1]` row and dividing the result by its homogeneous
+ coordinate, which is then always exactly 1.
+ """
+ if dtype in (torch.float16, torch.bfloat16):
+ # `einsum` and `bmm` accumulate the length-3 dot in a different order, which in half
+ # precision costs more than the equality being pinned here (4.4e-3 in float16 against a
+ # float64 reference, i.e. this dtype's own resolution). `test_dtype_device_preserved`
+ # carries the half coverage.
+ pytest.skip("reference accumulates differently from bmm in half precision")
+ torch.manual_seed(0)
+ laf = torch.randn(2, 5, 2, 3, device=device, dtype=dtype)
+ n_pts = 9
+ # The implementation builds its angles in float32 and casts, so the reference does too.
+ angles = torch.linspace(0, 2 * math.pi, n_pts - 1, device=device).to(dtype)
+ origin = torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ basis = torch.cat([origin, torch.stack([angles.sin(), angles.cos(), torch.ones_like(angles)], dim=-1)])
+ expected = torch.einsum("bnij,pj->bnpi", laf, basis)
+ self.assert_close(kornia.feature.laf_to_boundary_points(laf, n_pts), expected)
+
+ def test_dtype_device_preserved(self, device, dtype):
+ """Boundary points keep the LAF's dtype and device, in every dtype.
+
+ Nothing else covered this op in half precision. Note this cannot see *where* the basis is
+ cast -- casting it before or after the broadcast gives the same dtype, device and values,
+ so that ordering is a memory property, not an observable one.
+ """
+ laf = torch.tensor([[[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0]]]], device=device, dtype=dtype)
+ n_pts = 6
+ expected = torch.tensor([[[[1, 1], [1, 2], [2, 1], [1, 0], [0, 1], [1, 2]]]], device=device, dtype=dtype)
+ pts = kornia.feature.laf_to_boundary_points(laf, n_pts)
+ assert pts.dtype == dtype
+ assert pts.device == laf.device
+ self.assert_close(pts, expected)
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ laf = torch.rand(2, 4, 2, 3, device=device, dtype=dtype)
+ expected = kornia.feature.laf_to_boundary_points(laf)
+ op = torch_optimizer(kornia.feature.laf_to_boundary_points)
+ self.assert_close(op(laf), expected)
+
def test_jit(self, device, dtype):
batch_size, channels, height, width = 3, 2, 2, 3
laf = torch.rand(batch_size, channels, height, width, device=device)