test_symeig3x3.py 9.1 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
2
3
4
5
6
7
8
9
10
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.


import unittest

import torch
11
from common_testing import get_random_cuda_device, TestCaseMixin
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
from pytorch3d.common.workaround import symeig3x3
from pytorch3d.transforms.rotation_conversions import random_rotations


class TestSymEig3x3(TestCaseMixin, unittest.TestCase):
    TEST_BATCH_SIZE = 1024

    @staticmethod
    def create_random_sym3x3(device, n):
        random_3x3 = torch.randn((n, 3, 3), device=device)
        random_3x3_T = torch.transpose(random_3x3, 1, 2)
        random_sym_3x3 = (random_3x3 * random_3x3_T).contiguous()

        return random_sym_3x3

    @staticmethod
    def create_diag_sym3x3(device, n, noise=0.0):
        # Create purly diagonal matrices
        random_diag_3x3 = torch.randn((n, 3), device=device).diag_embed()

        # Make them 'almost' diagonal
        random_diag_3x3 += noise * TestSymEig3x3.create_random_sym3x3(device, n)

        return random_diag_3x3

    def setUp(self) -> None:
        super().setUp()
        torch.manual_seed(42)

        self._gpu = get_random_cuda_device()
        self._cpu = torch.device("cpu")

    def test_is_eigen_gpu(self):
        test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE)

        self._test_is_eigen(test_input)

    def test_is_eigen_cpu(self):
        test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE)

        self._test_is_eigen(test_input)

    def _test_is_eigen(self, test_input, atol=1e-04, rtol=1e-02):
        """
        Verify that values and vectors produced are really eigenvalues and eigenvectors
        and can restore the original input matrix with good precision
        """
        eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)

        self.assertClose(
            test_input,
            eigenvectors @ eigenvalues.diag_embed() @ eigenvectors.transpose(-2, -1),
            atol=atol,
            rtol=rtol,
        )

    def test_eigenvectors_are_orthonormal_gpu(self):
        test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE)

        self._test_eigenvectors_are_orthonormal(test_input)

    def test_eigenvectors_are_orthonormal_cpu(self):
        test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE)

        self._test_eigenvectors_are_orthonormal(test_input)

    def _test_eigenvectors_are_orthonormal(self, test_input):
        """
        Verify that eigenvectors are an orthonormal set
        """
        eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)

        batched_eye = torch.zeros_like(test_input)
        batched_eye[..., :, :] = torch.eye(3, device=batched_eye.device)

        self.assertClose(
            batched_eye, eigenvectors @ eigenvectors.transpose(-2, -1), atol=1e-06
        )

    def test_is_not_nan_or_inf_gpu(self):
        test_input = self.create_random_sym3x3(self._gpu, n=self.TEST_BATCH_SIZE)

        self._test_is_not_nan_or_inf(test_input)

    def test_is_not_nan_or_inf_cpu(self):
        test_input = self.create_random_sym3x3(self._cpu, n=self.TEST_BATCH_SIZE)

        self._test_is_not_nan_or_inf(test_input)

    def _test_is_not_nan_or_inf(self, test_input):
        eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)

        self.assertTrue(torch.isfinite(eigenvalues).all())
        self.assertTrue(torch.isfinite(eigenvectors).all())

    def test_degenerate_inputs_gpu(self):
        self._test_degenerate_inputs(self._gpu)

    def test_degenerate_inputs_cpu(self):
        self._test_degenerate_inputs(self._cpu)

    def _test_degenerate_inputs(self, device):
        """
        Test degenerate case when input matrices are diagonal or near-diagonal
        """

        # Purely diagonal case
        test_input = self.create_diag_sym3x3(device, self.TEST_BATCH_SIZE)

        self._test_is_not_nan_or_inf(test_input)
        self._test_is_eigen(test_input)
        self._test_eigenvectors_are_orthonormal(test_input)

        # Almost-diagonal case
        test_input = self.create_diag_sym3x3(device, self.TEST_BATCH_SIZE, noise=1e-4)

        self._test_is_not_nan_or_inf(test_input)
        self._test_is_eigen(test_input)
        self._test_eigenvectors_are_orthonormal(test_input)

    def test_gradients_cpu(self):
        self._test_gradients(self._cpu)

    def test_gradients_gpu(self):
        self._test_gradients(self._gpu)

    def _test_gradients(self, device):
        """
        Tests if gradients pass though without any problems (infs, nans etc) and
        also performs gradcheck (compares numerical and analytical gradients)
        """
        test_random_input = self.create_random_sym3x3(device, n=16)
        test_diag_input = self.create_diag_sym3x3(device, n=16)
        test_almost_diag_input = self.create_diag_sym3x3(device, n=16, noise=1e-4)

        test_input = torch.cat(
            (test_random_input, test_diag_input, test_almost_diag_input)
        )
        test_input.requires_grad = True

        with torch.autograd.detect_anomaly():
            eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)

            loss = eigenvalues.mean() + eigenvectors.mean()
            loss.backward()

        test_random_input.requires_grad = True
        # Inputs are converted to double to increase the precision of gradcheck.
        torch.autograd.gradcheck(
            symeig3x3, test_random_input.double(), eps=1e-6, atol=1e-2, rtol=1e-2
        )

    def _test_eigenvalues_and_eigenvectors(
        self, test_eigenvectors, test_eigenvalues, atol=1e-04, rtol=1e-04
    ):
        test_input = (
            test_eigenvectors.transpose(-2, -1)
            @ test_eigenvalues.diag_embed()
            @ test_eigenvectors
        )

        test_eigenvalues_sorted, _ = torch.sort(test_eigenvalues, dim=-1)

        eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)

        self.assertClose(
            test_eigenvalues_sorted,
            eigenvalues,
            atol=atol,
            rtol=rtol,
        )

        self._test_is_not_nan_or_inf(test_input)
        self._test_is_eigen(test_input, atol=atol, rtol=rtol)
        self._test_eigenvectors_are_orthonormal(test_input)

    def test_degenerate_eigenvalues_gpu(self):
        self._test_degenerate_eigenvalues(self._gpu)

    def test_degenerate_eigenvalues_cpu(self):
        self._test_degenerate_eigenvalues(self._cpu)

    def _test_degenerate_eigenvalues(self, device):
        """
        Test degenerate eigenvalues like zero-valued and with 2-/3-multiplicity
        """
        # Error tolerances for degenerate values are increased as things might become
        #  numerically unstable
        deg_atol = 1e-3
        deg_rtol = 1.0

        # Construct random orthonormal sets
        test_eigenvecs = random_rotations(n=self.TEST_BATCH_SIZE, device=device)

        # Construct random eigenvalues
        test_eigenvals = torch.randn(
            (self.TEST_BATCH_SIZE, 3), device=test_eigenvecs.device
        )
        self._test_eigenvalues_and_eigenvectors(
            test_eigenvecs, test_eigenvals, atol=deg_atol, rtol=deg_rtol
        )

        # First eigenvalue is always 0.0 here: [0.0 X Y]
        test_eigenvals_with_zero = test_eigenvals.clone()
        test_eigenvals_with_zero[..., 0] = 0.0
        self._test_eigenvalues_and_eigenvectors(
            test_eigenvecs, test_eigenvals_with_zero, atol=deg_atol, rtol=deg_rtol
        )

        # First two eigenvalues are always the same here: [X X Y]
        test_eigenvals_with_multiplicity2 = test_eigenvals.clone()
        test_eigenvals_with_multiplicity2[..., 1] = test_eigenvals_with_multiplicity2[
            ..., 0
        ]
        self._test_eigenvalues_and_eigenvectors(
            test_eigenvecs,
            test_eigenvals_with_multiplicity2,
            atol=deg_atol,
            rtol=deg_rtol,
        )

        # All three eigenvalues are the same here: [X X X]
        test_eigenvals_with_multiplicity3 = test_eigenvals_with_multiplicity2.clone()
        test_eigenvals_with_multiplicity3[..., 2] = test_eigenvals_with_multiplicity2[
            ..., 0
        ]
        self._test_eigenvalues_and_eigenvectors(
            test_eigenvecs,
            test_eigenvals_with_multiplicity3,
            atol=deg_atol,
            rtol=deg_rtol,
        )

    def test_more_dimensions(self):
        """
        Tests if function supports arbitrary leading dimensions
        """
        repeat = 4

        test_input = self.create_random_sym3x3(self._cpu, n=16)
        test_input_4d = test_input[None, ...].expand((repeat,) + test_input.shape)

        eigenvalues, eigenvectors = symeig3x3(test_input, eigenvectors=True)
        eigenvalues_4d, eigenvectors_4d = symeig3x3(test_input_4d, eigenvectors=True)

        eigenvalues_4d_gt = eigenvalues[None, ...].expand((repeat,) + eigenvalues.shape)
        eigenvectors_4d_gt = eigenvectors[None, ...].expand(
            (repeat,) + eigenvectors.shape
        )

        self.assertClose(eigenvalues_4d_gt, eigenvalues_4d)
        self.assertClose(eigenvectors_4d_gt, eigenvectors_4d)