Kornia 相机去畸变数值稳定性修复解析:`undistort_points_kannala_brandt` 的 float16 精度与梯度修复
Kornia 相机去畸变数值稳定性修复解析:undistort_points_kannala_brandt 的 float16 精度与梯度修复
本篇技术指南围绕 Kornia 仓库中 changelog.d/+migration-038.fixed.md 记录的修复展开,深入剖析 Kannala-Brandt 鱼眼相机模型中点去畸变(undistort)函数在 float16 半精度场景下的数值缺陷、修复策略及其在源码与测试中的落地。读完本文,你将理解 Kornia 中 undistort_points_kannala_brandt 的完整实现细节(包括 Gauss-Newton 迭代反演、零半径分支处理、半精度中间量提升),掌握其参数约定、精度边界与回归测试的验证方法,可直接用于自己的相机标定、鱼眼去畸变与可微分相机建模工作。
一、修复背景:鱼眼去畸变为何会出现半精度坍缩
Kannala-Brandt 是鱼眼镜头常用的等距投影(equidistant projection)近似模型,用入射角 θ 的奇次多项式描述径向畸变。Kornia 在 kornia/geometry/camera/distortion_kannala_brandt.py 中提供了一组与之配套的函数:
distort_points_kannala_brandt:将归一化 z=1 平面上的点投影到像素坐标(前向畸变);undistort_points_kannala_brandt:将像素坐标反解回归一化 z=1 平面(去畸变,本修复的主角);dx_distort_points_kannala_brandt:前向畸变相对输入点的解析 Jacobian。
三个函数共享同一 8 元素参数向量约定:[fx, fy, cx, cy, k0, k1, k2, k3],前四项是仿射内参(与 distort_points_affine 完全一致),后四项分别乘上 θ²、θ⁴、θ⁶、θ⁸ 构成鱼眼多项式。
去畸变在数学上是前向畸变的逆映射,Kornia 没有采用闭式解,而是用固定步数的 Gauss-Newton 迭代逼近(源码 iters = 10,不可由调用方调整)。这一实现方式带来了两个在半精度下被放大的数值风险点:
- 主点附近点的平方下溢:计算归一化半径 r = √(x² + y²) 时,
float16的最小正规数约为 6.1e-5,靠近主点 (cx, cy) 的像素归一化后坐标极小,x² + y²会下溢为 0,导致半径被误判为零; - 零半径分支的非有限梯度:当半径恰为 0 时,若用
epsilon(如+1e-8)保护除法分母,径向重缩放因子r_distorted / r会退化为一个不连续、且对自动微分(autograd)不友好的路径,主点处的梯度变为 NaN 或无穷。
修复前的具体故障表现,正是本次 changelog 所描述的:主点附近可表示的 float16 点被错误地坍缩到了原点,且精确主点路径上 autograd 梯度不有限。相关议题编号为 #4308 与 #4370。
二、修复的核心策略:结构化处理而非依赖 epsilon
本次修复在 undistort_points_kannala_brandt 的实现 中体现为四条环环相扣的措施,下面逐一对照源码剖析。
2.1 零半径判定改用未平方的归一化坐标
修复前的实现(可以推断)基于归一化坐标平方和 x² + y² 与阈值比较来判定"是否在主点附近"。修复后的源码改为:
un = (x - cx) / fx
vn = (y - cy) / fy
nonzero_radius = (un != 0) | (vn != 0)
即:只要归一化坐标 un、vn 本身不全为零,就认为半径非零。这里不再对坐标做平方,也就不会在半精度下因平方下溢而把本非零的点误判为零。只有 un == 0 且 vn == 0 的"精确主点"才走零半径分支——这正是 changelog 中 "the zero-radius decision is made from the unsquared normalized coordinates" 的源码对应。
2.2 float16 半径使用 float32 中间量,避免平方下溢
判定之后,需要对非零半径安全地计算 r 值。源码先构造安全坐标,再按 dtype 决定计算精度:
safe_un = torch.where(nonzero_radius, un, torch.ones_like(un))
safe_vn = torch.where(nonzero_radius, vn, torch.zeros_like(vn))
radius_dtype = safe_un.dtype
if radius_dtype == torch.float16:
safe_un = safe_un.float()
safe_vn = safe_vn.float()
rth = (safe_un * safe_un + safe_vn * safe_vn).sqrt().to(radius_dtype)
rth = torch.where(nonzero_radius, rth, torch.zeros_like(rth))
关键点在于:当工作 dtype 是 float16 时,先原地提升到 float32 再做平方与开方,得到半径后再转回 float16。这样一来,x² + y² 不会在半精度下下溢为 0,主点附近那些"在 float16 中仍可表示"的点的半径可以正确求出,点不再被错误坍缩到原点。这与 dx_distort_points_kannala_brandt 中 "half-precision arithmetic is evaluated in float32 and rounded once at the end" 的设计哲学一致(见 该函数源码)。
2.3 精确主点路径的结构化处理保证有限梯度
对精确主点(un == vn == 0),源码用 torch.where 在数据流层面单独处理,而不是靠一个全局 epsilon 兜底:
safe_rth = torch.where(nonzero_radius, rth, torch.ones_like(rth))
th = safe_rth.sqrt()
th = torch.where(nonzero_radius, th, torch.zeros_like(th))
...
radius_undistorted = th.tan()
denom = torch.where(nonzero_radius, rth, torch.ones_like(rth))
mag = radius_undistorted.abs() / denom
mag = torch.where(nonzero_radius, mag, torch.ones_like(mag))
undistorted = torch.stack([mag * un, mag * vn], dim=-1)
对主点,denom 被替换为 1、mag 被替换为 1,于是输出恰好是 [un, vn] = [0, 0],结果精确等于原点。因为该分支全程不涉及 0/0 或 0/ε,autograd 可以沿 mag = 1、un = (x-cx)/fx 这条干净的路径回传梯度:主点处对输入点的 Jacobian 恰好是 diag(1/fx, 1/fy),对参数的 Jacobian 是除 -1/fx、-1/fy 两项外全零——全部有限。这就是 changelog 中 "the exact principal-point path now has finite autograd gradients" 的落点。
2.4 非零径向重缩放保持无 epsilon
对非零半径,最终径向缩放 mag = |tan(θ)| / r 直接除以真实的 r,不再使用 r + 1e-8 这类加性 epsilon。修复前,1e-8 的分母保护会给 float64 往返(round trip)引入约 1e-8 量级的系统性偏差;修复后,float64 往返残差可以降到 Gauss-Newton 舍入下限以下。这对应 changelog 中 "nonzero radial rescaling remains epsilon-free" 的表述。
三、回归测试:修复如何被验证
本修复的验证集中在 tests/geometry/camera/test_distortion.py 中 TestDistortionKannalaBrandt 类下,四个以 #4308 为后缀的约定测试(convention pin)逐一钉死了上文四条策略:
| 测试方法 | 验证内容 | 断言方式 |
|---|---|---|
test_convention_nearest_float16_point_is_not_collapsed_4308 |
主点旁边最近的 float16 点 [4.00390625, 3.0] 去畸变后 x 分量不为 0,且与解析期望 (px - cx)/fx 吻合 |
CPU + float16 专用,atol=6e-8 |
test_convention_principal_point_has_finite_gradients_4308 |
精确主点处对点 Jacobian 为 diag(1/fx, 1/fy),对参数 Jacobian 仅 -1/fx、-1/fy 两项非零,全部有限 |
与 torch.autograd.functional.jacobian 对比 |
test_convention_principal_point_undistorts_to_the_origin |
精确主点去畸变后逐位等于零向量(torch.equal,而非 assert_close) |
零半径分支是精确路径而非近似 |
test_convention_float64_round_trip_precision_4308 |
代表点 [0.5, 0.25]、[3.0, 0.0]、[0.01, 0.0] 的往返残差 < 1e-12 |
float64 专用,验证无 epsilon 重缩放 |
其中第一个测试是半精度坍缩回归的直接守卫:point = torch.tensor([4.00390625, 3.0]) 是 float16 在 4.0 附近可表示的下一个值,修复前会被平方下溢误判为零半径而输出 [0, 0];修复后它正确输出了 [3.90625e-05, 0] 附近的有限值。注意该测试限定了 device.type == "cpu" 且 dtype == torch.float16,说明此回归在 CPU 半精度路径上表现最典型。
此外,test_convention_principal_point_undistorts_to_the_origin 还额外验证了混合精度情形:float16 点配 float32 参数时,函数按参数 dtype 计算再转回点的 dtype,主点仍逐位输出零——函数内部 "computes in params.dtype and casts back to the points dtype" 的约定因此也被固化下来。
四、在代码库中的位置与配套修复链
本修复并非孤立改动,它与 Kornia 相机畸变模块的近期演进构成一条连续的数值稳健性链条:
- changelog.d/+migration-027.fixed.md 记录了前序修复:
dx_distort_points_kannala_brandt此前返回的并非前向畸变的真实 Jacobian,修复后其在原点也返回有限的仿射 Jacobiandiag(fx, fy)(议题 #4277、#4368); - 本次 migration-038 修复(议题 #4308、#4370)则继续覆盖
undistort_points_kannala_brandt的半精度与梯度问题。
两者在测试中相互印证:test_convention_dx_distort_points_kannala_brandt_affine_branch 断言 radius_sq <= 1e-8 时 Jacobian 恰为 diag(fx, fy)(包括原点),test_convention_dx_distort_points_kannala_brandt_matches_autograd_4277 则用不对称焦距(fx=100, fy=50)防止行/列或 fx/fy 互换被掩盖,确保解析 Jacobian 与 autograd 完全一致。
在 API 层面,undistort_points_kannala_brandt 通过 kornia/geometry/camera/init.py 导出,并作为传感器层 KannalaBrandtK3Transform 的底层实现被复用(见 kornia/sensors/camera/distortion_model.py),因此本修复同时惠及 kornia.sensors 面向 Vector2 的高级接口。想查看该 API 的导出形态可参考 docs/source/geometry.camera.rst。
五、使用与注意事项
函数的标准用法(取自 函数 docstring)如下:
import torch
from kornia.geometry.camera import undistort_points_kannala_brandt
points = torch.tensor([319.5, 239.5]) # 640x480 图像中心(像素)
params = torch.tensor([1000.0, 1000.0, 320.0, 280.0, 0.1, 0.01, 0.001, 0.0001])
undistort_points_kannala_brandt(points, params).shape # torch.Size([2])
输入 distorted_points_in_camera 形状为 (..., 2)(像素坐标),params 形状为 (..., 8),输出为 (..., 2) 的归一化 z=1 平面坐标。理解本修复时需记住以下边界条件:
- 去畸变是迭代近似:10 步 Gauss-Newton 且无收敛判据,往返
distort → undistort只闭合到迭代精度,不是逐位精确;与undistort_points_affine的闭式反解形成对照(对比见 distortion_affine.py); - 半精度提升只发生在 float16:
bfloat16与float32/float64直接按原生 dtype 计算;float16点配float32参数时按参数 dtype 计算后转回点的 dtype; - 主点处精确:精确主点输出逐位等于原点,但该结论依赖
torch.where的分支结构,是"结构化精确"而非浮点巧合; - 远轴点依然稳健:测试还固定了离轴 3 倍焦距处的往返闭合(见
test_convention_undistort_points_kannala_brandt_closes_far_off_axis),只是bfloat16下该场景残差超出容差被显式跳过,说明半精度下离轴大畸变仍需谨慎。
若要在自己的标定管线中复现本修复的行为,最直接的方式是运行上述回归测试:
pytest tests/geometry/camera/test_distortion.py -k "4308" -v
六、小结
undistort_points_kannala_brandt 的 migration-038 修复,本质是把"用 epsilon 掩盖数值病态"改为"用结构化的分支与 dtype 提升根治数值病态":未平方坐标判定半径、float32 中间量防下溢、torch.where 构造精确主点路径、去掉径向重缩放中的加性 epsilon。四管齐下后,float16 主点邻域不再坍缩,主点 autograd 梯度有限,float64 往返精度到达舍入下限。这套"修复 + 约定测试 + dtype 专用回归"的组合,也为 Kornia 中其他涉及半精度与可微分的几何算子提供了可复制的数值稳健性范式。