`Hyperplane.through` returns a NaN gradient when `p1 - p0` and `p2 - p0` are orthogonal and of equal length
Hyperplane.through(p0, p1, p2) always evaluates the SVD fallback compute_normal_svd(v0, v1) and selects between
it and the cross-product normal with torch.where. torch.where sends a zero gradient into the branch it did not
select, but the backward pass still runs through the SVD. When the rows of m = stack(v0, v1) have equal singular
values, which happens whenever v0 = p2 - p0 and v1 = p1 - p0 are orthogonal and of equal length, the SVD backward
divides by s_i² - s_j² = 0. 0 · inf is NaN, so every input gradient is NaN, even when the forward result comes
from the cross-product branch and is correct.
import torch
from kornia.geometry.plane import Hyperplane
d = torch.float64
def grads(p0, p1, p2):
P = [torch.tensor(p, dtype=d, requires_grad=True) for p in (p0, p1, p2)]
h = Hyperplane.through(*P)
(h.normal.data.sum() + h.offset.data.sum()).backward()
return h.normal.data.tolist(), [p.grad.tolist() for p in P]
# v0 = (2, 1, -2), v1 = (1, 2, 2): orthogonal, both of length 3
print(grads([0.0, 0, 0], [1.0, 2, 2], [2.0, 1, -2]))
# the same plane with v0 twice as long: finite gradients
print(grads([0.0, 0, 0], [1.0, 2, 2], [4.0, 2, -4]))
# axis-aligned right isosceles triangles: the plane z = 1, and the test_projection fixture x = 0
print(grads([0.0, 0, 1], [1.0, 0, 1], [0.0, 1, 1]))
print(grads([0.0, 0, 0], [0.0, 1, 0], [0.0, 0, 1]))On main 38478f0dd (torch 2.14.0, CPU, float64), the first, third and fourth calls give nan for all nine gradient
entries. The second call gives finite gradients. The first plane is tilted, so it takes the cross-product branch,
and the NaN comes only from the unselected SVD branch. On main the axis-aligned planes take the SVD branch itself,
because their cross product has a zero component and so its p = -1 "norm" is 0. After #5055 (the #5012 fix) they
take the cross-product branch, and they still get NaN through the unselected branch. The unit right-isosceles
triangle is a common fixture shape.
Fix direction: substitute a matrix with distinct singular values for the rows that do not use the fallback before
the SVD, e.g. m = torch.where(normal_mask[..., None], m, safe) with a constant safe such as [[1, 0, 0], [0, 2, 0]], as AGENTS.md prescribes for guards whose unselected branch is singular. The pin is a finite gradient
(and gradcheck) on the orthogonal equal-length triangle above, for a tilted plane and an axis-aligned one.
Related: #5012 / #5055 (same method, normalisation), #5041 / #5054 (degenerate input now raises in eager).
Posted on behalf of @ducha-aiki by Claude (Opus 5.5).
Source: kornia/kornia