Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix quaternion averaging Dynamo graph capture (#5829)

Lakshay Aggarwal25e7f9277ab2
diff --git a/changelog.d/5829.fixed.md b/changelog.d/5829.fixed.md
new file mode 100644
index 000000000..b0e2a346c
--- /dev/null
+++ b/changelog.d/5829.fixed.md
@@ -0,0 +1 @@
+`average_quaternions` now compiles with `torch.compile(..., fullgraph=True)`. It used to fail Dynamo graph capture on the data-dependent column index that selects the eigenvector of the largest eigenvalue; it now gathers that column, with the same result in eager mode.
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index a6a8208b9..4d8f633d5 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -766,7 +766,8 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Q
# changing which eigenvector is selected when eigenvalues are close.
max_idx = torch.argmax(eigenvalues)
eigenvectors = eigenvectors.to(orig_dtype)
- q_avg = eigenvectors[:, max_idx]
+ indices = max_idx.reshape(1, 1).expand(eigenvectors.shape[0], 1)
+ q_avg = torch.gather(eigenvectors, 1, indices).squeeze(1)
q_avg = q_avg / q_avg.norm()
return Quaternion(q_avg.unsqueeze(0))
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index 0d8baa85b..a044f81bb 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -655,6 +655,16 @@ class TestQuaternionState(BaseTester):
class TestQuaternionAverage(BaseTester):
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_fullgraph(self, device, dtype, torch_optimizer):
+ def average(data):
+ return average_quaternions(Quaternion(data)).data
+
+ data = Quaternion.random(5, device=device, dtype=dtype).data
+ actual = torch_optimizer(average, fullgraph=True)(data)
+ expected = average(data)
+ self.assert_close(actual, expected, rtol=1e-5, atol=1e-5)
+
@pytest.mark.parametrize("M", [1, 2, 5, 10])
def test_average_identity(self, device, dtype, M):
"""All identity quaternions β†’ should return identity"""