Kornia 相机标定 tilt 检查兼容 torch.compile(fullgraph=True) 的修复详解
Kornia 相机标定 tilt 检查兼容 torch.compile(fullgraph=True) 的修复详解
导读
本文围绕 Kornia 合入的修复(对应 changelog 片段,PR #4391)展开:distort_points 与 undistort_points 原本在 host 端读取张量形式的 tilt 畸变系数(τx、τy)来决定是否走 tilt 投影分支,这种"由张量值驱动控制流"的写法在 torch.compile(fullgraph=True) 图捕获阶段无法读取系数数值,会破坏编译。修复后,编译/导出路径无条件应用 tilt 分支(零角度时退化为单位矩阵),同时完整保留 eager 与 TorchScript 行为。读完本文,你将理解该 bug 的根因、Kornia 采用的兼容策略、底层 tilt_projection 的数学实现,以及对应的编译回归测试如何验证正确性。
修复背景:为什么 tilt 检查会破坏 fullgraph 编译
Kornia 的镜头畸变模型在径向(k1..k6)、切向(p1,p2)、薄棱镜(s1..s4)之外还支持 tilt 畸变,对应 dist 系数向量的第 13、14 个元素(τx, τy)。distort_points 与 undistort_points 接受 4/5/8/12/14 长度的系数向量,并在内部零填充到 14 个元素(见 distort.py 与 undistort.py)。
修复前的代码用如下条件判断是否应用 tilt 变换:
if torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14])
...
问题在于:torch.any(dist<a href="https://link.gitcode.com/i/ef77269abd1af63fc1d1d3ca1fad8493" target="_blank">..., 12] != 0) 是对张量值的运行时判断。在 torch.compile(fullgraph=True) 图捕获阶段,Dynamo 无法读取(也不允许读取)GPU/CPU 张量的具体数值来决定控制流,这种 tensor-dependent 的分支要么导致图捕获失败,要么迫使 Dynamo 将系数值特化(specialize)进编译结果——一旦运行时传入不同的 tilt 系数,编译产物就会给出错误结果。这正是 [test_compile.py 注释中所记录的 #4286 问题:"tensor-dependent tilt checks must not break capture or specialize on coefficient values"。
修复方案:捕获期检测 + 无条件应用 tilt 分支
修复思路非常直接:图捕获阶段无法"看"系数值,那就干脆不看——在编译或导出时无条件执行 tilt 投影分支;由于 τx = τy = 0 时 tilt 投影矩阵恒等于单位矩阵 eye(3),无条件分支不会改变数学结果,零 tilt 的投影就是恒等变换。
改动集中在两个文件的同一段逻辑(两处实现刻意保持一致):
- distort.py(前向畸变):
# Graph capture cannot read the coefficient values on the host. Apply the tilt unconditionally
# while compiling or exporting; zero angles give the identity. Keep eager and scripted behavior.
capture = is_exporting()
if not torch.jit.is_scripting():
capture = capture or is_compiling()
if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14])
points_untilt = torch.stack([xd, yd, torch.ones_like(xd)], -1) @ tilt.transpose(-2, -1)
xd = points_untilt[..., 0] / points_untilt[..., 2]
yd = points_untilt[..., 1] / points_untilt[..., 2]
- undistort.py(逆畸变):
capture = is_exporting()
if not torch.jit.is_scripting():
capture = capture or is_compiling()
if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
inv_tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14], True)
if inv_tilt.dim() == 2:
inv_tilt = inv_tilt.unsqueeze(0)
x, y = transform_points(inv_tilt, torch.stack([x, y], dim=-1)).unbind(-1)
要点拆解:
- 分支条件变为
capture or 数值判断:只要处于图捕获环境就进入 tilt 分支,不再依赖张量值;eager 模式下仍保留原来的数值判断,零 tilt 时跳过多余计算。 is_exporting()与is_compiling()的语义:二者定义在 kornia/core/utils.py。is_compiling()判断是否处于torch.compile或torch.export捕获中(内部解析torch.compiler.is_compiling,缺失时回退到torch._dynamo.is_compiling);is_exporting()判断是否处于torch.export或 dynamo ONNX 导出器捕获中,并且@torch.jit.unused装饰保证 TorchScript 下恒为False,因此该 guard 可安全用于脚本化函数。torch.jit.is_scripting()保护:显式排除 TorchScript 路径,保持"eager 和 scripted 行为"与修复前完全一致——这正是 changelog 中所说的 preserving eager behavior。
底层支撑:tilt_projection 的数学实现
tilt 分支调用的 tilt_projection(distort.py)构造 OpenCV 风格的 tilt 投影矩阵,约定 R = Ry(tauy) @ Rx(taux),并支持正逆两个分支:
return_inverse=False返回Pz @ R,与 OpenCV 的 tilt projection 一致,用于distort_points的"加 tilt"方向;return_inverse=True返回Pz @ R的逆矩阵(R.T @ invPz),即undistort_points使用的"去 tilt"方向,可在仓库自带的参考值上复现 OpenCV 的undistortPoints。
两个分支在 τx = τy = 0 时都精确返回 eye(3)(旋转矩阵为单位阵、R<a href="https://link.gitcode.com/i/04a87ef3c3ee88194551bf3302dbfd85" target="_blank">..., 2, 2] = 1),这是"无条件应用 tilt 分支也不会改变结果"的数学保证。相关约定在测试中有专门覆盖,见 [test_distort.py:零角度恒等性、正逆分支互为逆矩阵、前向分支等于 Pz @ R 等断言(对应问题 #4276)。
回归测试:fullgraph 编译下的逐值一致性验证
本次修复配套了专门的编译回归测试 test_compile.py:
@pytest.mark.parametrize("op", [distort_points, undistort_points])
@pytest.mark.parametrize("num_coefficients", [4, 14])
def test_dynamo_fullgraph(self, device, dtype, torch_optimizer, op, num_coefficients):
counter = CompileCounter()
counted = torch.compile(op, backend=counter, fullgraph=True)
compiled = torch_optimizer(op, fullgraph=True)
for tilt in [0.0, 0.1]:
if num_coefficients == 14:
dist[:, 12] = tilt
dist[:, 13] = -2 * tilt
expected = op(points, camera, dist)
self.assert_close(counted(points, camera, dist), expected)
self.assert_close(compiled(points, camera, dist), expected)
assert counter.frame_count == 1
测试覆盖了两个关键维度:
op × 系数长度:distort_points与undistort_points各自在 4 系数(无 tilt 槽位)和 14 系数(含 tilt 槽位)下编译;tilt 取值:分别以0.0(零 tilt,编译分支"无条件走 tilt"但数学上应为恒等)和0.1(真实 tilt,τy = -2τx)验证。
断言要求 fullgraph=True 编译后的输出与 eager 参考值 assert_close 一致,同时 CompileCounter 记录 frame_count == 1——即整个函数被成功捕获进单个编译图,没有因 host 端取值而触发图重建或回退。修复前这类测试会因无法在捕获期读取 dist 值而失败。
此外,既有功能测试也验证了修复不改变 eager 语义,例如 test_undistort.py 的 test_convention_distort_undistort_round_trip_with_tilt_4276:在非零径向/切向系数叠加非对称 tilt([0.1, 0.2])时,undistort_points(distort_points(...)) 往返仍能闭合到参考点。
实战指引:如何在你的代码中编译这两个算子
修复生效后,可以放心地对标定流程做端到端图编译:
import torch
from kornia.geometry.calibration import distort_points, undistort_points
points = torch.tensor([[[1.0, 2.0], [6.0, 5.0]]])
K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]])
dist = torch.zeros(1, 14)
dist[:, :4] = torch.tensor([0.1, 0.01, 0.001, 0.0001])
dist[:, 12] = 0.1 # taux
dist[:, 13] = -0.2 # tauy
compiled_distort = torch.compile(distort_points, fullgraph=True)
compiled_undistort = torch.compile(undistort_points, fullgraph=True)
d = compiled_distort(points, K, dist)
u = compiled_undistort(d, K, dist)
注意事项:
dist系数向量长度必须为 4、5、8、12 或 14 之一,其他长度会抛出ValueError;短向量内部自动零填充到 14,因此 4 系数与 14 系数零填充版本结果一致(见 distort.py)。undistort_points的逆变换是num_iters=5的固定点迭代而非闭式解,往返精度受迭代次数与 dtype 限制;float16在默认迭代次数下可能已触及舍入下限,float32/float64增大num_iters可继续改善(见 undistort.py)。- 若同时使用 ONNX 导出,
is_exporting()会走与编译相同的"无条件 tilt"路径,零 tilt 时投影为恒等,导出图行为一致。 - 该修复依赖 Kornia 的捕获检测工具,位于 kornia/core/utils.py,其同时被其他 export-safe 路径(如闭式逆、
sort类中位数等)复用。
小结
本次修复的实质,是把"依赖张量值的数据依赖分支"改写为"环境感知的条件分支":图捕获期间无条件走数学上等价(零角度恒等)的 tilt 分支,eager 与 TorchScript 则维持原有数值判断。它同时保证了三点——fullgraph=True 可成功捕获单图、编译/导出产物与 eager 输出逐值一致、以及零 tilt 时的恒等语义。若要深入源码,可从 distort.py 与 undistort.py 的 tilt 分支入手,配合 test_compile.py 与 test_distort.py 中的约定测试对照阅读。