test_chamfer.py 29.7 KB
Newer Older
1
# Copyright (c) Meta Platforms, Inc. and affiliates.
Patrick Labatut's avatar
Patrick Labatut committed
2
3
4
5
# 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.
facebook-github-bot's avatar
facebook-github-bot committed
6
7

import unittest
Nikhila Ravi's avatar
Nikhila Ravi committed
8
from collections import namedtuple
9

Nikhila Ravi's avatar
Nikhila Ravi committed
10
import numpy as np
facebook-github-bot's avatar
facebook-github-bot committed
11
12
import torch
import torch.nn.functional as F
13
from common_testing import get_random_cuda_device, TestCaseMixin
14
from pytorch3d.loss import chamfer_distance
Nikhila Ravi's avatar
Nikhila Ravi committed
15
16
17
18
19
20
21
from pytorch3d.structures.pointclouds import Pointclouds


# Output of init_pointclouds
points_normals = namedtuple(
    "points_normals", "p1_lengths p2_lengths cloud1 cloud2 p1 p2 n1 n2 weights"
)
facebook-github-bot's avatar
facebook-github-bot committed
22

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
23
24

class TestChamfer(TestCaseMixin, unittest.TestCase):
Nikhila Ravi's avatar
Nikhila Ravi committed
25
26
27
28
29
    def setUp(self) -> None:
        super().setUp()
        torch.manual_seed(1)

    @staticmethod
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
30
31
32
    def init_pointclouds(
        N, P1, P2, device, requires_grad: bool = True, allow_empty: bool = True
    ):
Nikhila Ravi's avatar
Nikhila Ravi committed
33
34
35
36
37
38
        """
        Create 2 pointclouds object and associated padded points/normals tensors by
        starting from lists. The clouds and tensors have the same data. The
        leaf nodes for the clouds are a list of tensors. The padded tensor can be
        used directly as a leaf node.
        """
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
39
40
41
        low = 0 if allow_empty else 1
        p1_lengths = torch.randint(low, P1, size=(N,), dtype=torch.int64, device=device)
        p2_lengths = torch.randint(low, P2, size=(N,), dtype=torch.int64, device=device)
Nikhila Ravi's avatar
Nikhila Ravi committed
42
43
        P1 = p1_lengths.max().item()
        P2 = p2_lengths.max().item()
Nikhila Ravi's avatar
Nikhila Ravi committed
44
45
46
        weights = torch.rand((N,), dtype=torch.float32, device=device)

        # list of points and normals tensors
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
47
48
49
50
51
52
53
        p1 = torch.rand((N, P1, 3), dtype=torch.float32, device=device)
        p2 = torch.rand((N, P2, 3), dtype=torch.float32, device=device)
        n1 = torch.rand((N, P1, 3), dtype=torch.float32, device=device)
        n2 = torch.rand((N, P2, 3), dtype=torch.float32, device=device)
        n1 /= n1.norm(dim=-1, p=2, keepdim=True)
        n2 /= n2.norm(dim=-1, p=2, keepdim=True)

Nikhila Ravi's avatar
Nikhila Ravi committed
54
55
56
57
58
59
60
        p1_list = []
        p2_list = []
        n1_list = []
        n2_list = []
        for i in range(N):
            l1 = p1_lengths[i]
            l2 = p2_lengths[i]
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
61
62
63
64
            p1_list.append(p1[i, :l1].clone())
            p2_list.append(p2[i, :l2].clone())
            n1_list.append(n1[i, :l1].clone())
            n2_list.append(n2[i, :l2].clone())
Nikhila Ravi's avatar
Nikhila Ravi committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

        # Set requires_grad for all tensors in the lists and
        # padded tensors.
        if requires_grad:
            for p in p2_list + p1_list + n1_list + n2_list + [p1, p2, n1, n2]:
                p.requires_grad = True

        # Create pointclouds objects
        cloud1 = Pointclouds(points=p1_list, normals=n1_list)
        cloud2 = Pointclouds(points=p2_list, normals=n2_list)

        # Return pointclouds objects and padded tensors
        return points_normals(
            p1_lengths=p1_lengths,
            p2_lengths=p2_lengths,
            cloud1=cloud1,
            cloud2=cloud2,
            p1=p1,
            p2=p2,
            n1=n1,
            n2=n2,
            weights=weights,
        )

facebook-github-bot's avatar
facebook-github-bot committed
89
    @staticmethod
90
    def chamfer_distance_naive_pointclouds(p1, p2, norm: int = 2, device="cpu"):
facebook-github-bot's avatar
facebook-github-bot committed
91
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
92
93
94
95
        Naive iterative implementation of nearest neighbor and chamfer distance.
        x and y are assumed to be pointclouds objects with points and optionally normals.
        This functions supports heterogeneous pointclouds in a batch.
        Returns lists of the unreduced loss and loss_normals.
facebook-github-bot's avatar
facebook-github-bot committed
96
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        x = p1.points_padded()
        y = p2.points_padded()
        N, P1, D = x.shape
        P2 = y.size(1)
        x_lengths = p1.num_points_per_cloud()
        y_lengths = p2.num_points_per_cloud()
        x_normals = p1.normals_padded()
        y_normals = p2.normals_padded()

        return_normals = x_normals is not None and y_normals is not None

        # Initialize all distances to + inf
        dist = torch.ones((N, P1, P2), dtype=torch.float32, device=device) * np.inf

        x_mask = (
            torch.arange(P1, device=x.device)[None] >= x_lengths[:, None]
        )  # shape [N, P1]
        y_mask = (
            torch.arange(P2, device=y.device)[None] >= y_lengths[:, None]
        )  # shape [N, P2]

Nikhila Ravi's avatar
Nikhila Ravi committed
118
119
        is_x_heterogeneous = (x_lengths != P1).any()
        is_y_heterogeneous = (y_lengths != P2).any()
Nikhila Ravi's avatar
Nikhila Ravi committed
120
121
122
123
        # Only calculate the distances for the points which are not masked
        for n in range(N):
            for i1 in range(x_lengths[n]):
                for i2 in range(y_lengths[n]):
124
125
126
127
128
129
130
131
                    if norm == 2:
                        dist[n, i1, i2] = torch.sum((x[n, i1, :] - y[n, i2, :]) ** 2)
                    elif norm == 1:
                        dist[n, i1, i2] = torch.sum(
                            torch.abs(x[n, i1, :] - y[n, i2, :])
                        )
                    else:
                        raise ValueError("No support for norm %d" % (norm))
Nikhila Ravi's avatar
Nikhila Ravi committed
132
133
134

        x_dist = torch.min(dist, dim=2)[0]  # (N, P1)
        y_dist = torch.min(dist, dim=1)[0]  # (N, P2)
facebook-github-bot's avatar
facebook-github-bot committed
135

Nikhila Ravi's avatar
Nikhila Ravi committed
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
        if is_x_heterogeneous:
            x_dist[x_mask] = 0.0
        if is_y_heterogeneous:
            y_dist[y_mask] = 0.0

        loss = [x_dist, y_dist]

        lnorm = [x.new_zeros(()), x.new_zeros(())]

        if return_normals:
            x_index = dist.argmin(2).view(N, P1, 1).expand(N, P1, 3)
            y_index = dist.argmin(1).view(N, P2, 1).expand(N, P2, 3)
            lnorm1 = 1 - torch.abs(
                F.cosine_similarity(
                    x_normals, y_normals.gather(1, x_index), dim=2, eps=1e-6
                )
            )
            lnorm2 = 1 - torch.abs(
                F.cosine_similarity(
                    y_normals, x_normals.gather(1, y_index), dim=2, eps=1e-6
                )
            )

            if is_x_heterogeneous:
                lnorm1[x_mask] = 0.0
            if is_y_heterogeneous:
                lnorm2[y_mask] = 0.0

            lnorm = [lnorm1, lnorm2]  # [(N, P1), (N, P2)]

        return loss, lnorm
facebook-github-bot's avatar
facebook-github-bot committed
167
168

    @staticmethod
169
    def chamfer_distance_naive(x, y, x_normals=None, y_normals=None, norm: int = 2):
facebook-github-bot's avatar
facebook-github-bot committed
170
171
        """
        Naive iterative implementation of nearest neighbor and chamfer distance.
Nikhila Ravi's avatar
Nikhila Ravi committed
172
173
        Returns lists of the unreduced loss and loss_normals. This naive
        version only supports homogeneous pointcouds in a batch.
facebook-github-bot's avatar
facebook-github-bot committed
174
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
175
176
        N, P1, D = x.shape
        P2 = y.size(1)
Nikhila Ravi's avatar
Nikhila Ravi committed
177
        device = x.device
Nikhila Ravi's avatar
Nikhila Ravi committed
178
        return_normals = x_normals is not None and y_normals is not None
facebook-github-bot's avatar
facebook-github-bot committed
179
180
181
182
183
        dist = torch.zeros((N, P1, P2), dtype=torch.float32, device=device)

        for n in range(N):
            for i1 in range(P1):
                for i2 in range(P2):
184
185
186
187
188
189
190
191
                    if norm == 2:
                        dist[n, i1, i2] = torch.sum((x[n, i1, :] - y[n, i2, :]) ** 2)
                    elif norm == 1:
                        dist[n, i1, i2] = torch.sum(
                            torch.abs(x[n, i1, :] - y[n, i2, :])
                        )
                    else:
                        raise ValueError("No support for norm %d" % (norm))
facebook-github-bot's avatar
facebook-github-bot committed
192
193
194
195
196

        loss = [
            torch.min(dist, dim=2)[0],  # (N, P1)
            torch.min(dist, dim=1)[0],  # (N, P2)
        ]
Nikhila Ravi's avatar
Nikhila Ravi committed
197
        lnorm = [x.new_zeros(()), x.new_zeros(())]
facebook-github-bot's avatar
facebook-github-bot committed
198
199

        if return_normals:
Nikhila Ravi's avatar
Nikhila Ravi committed
200
201
            x_index = dist.argmin(2).view(N, P1, 1).expand(N, P1, 3)
            y_index = dist.argmin(1).view(N, P2, 1).expand(N, P2, 3)
facebook-github-bot's avatar
facebook-github-bot committed
202
203
            lnorm1 = 1 - torch.abs(
                F.cosine_similarity(
Nikhila Ravi's avatar
Nikhila Ravi committed
204
                    x_normals, y_normals.gather(1, x_index), dim=2, eps=1e-6
facebook-github-bot's avatar
facebook-github-bot committed
205
206
207
208
                )
            )
            lnorm2 = 1 - torch.abs(
                F.cosine_similarity(
Nikhila Ravi's avatar
Nikhila Ravi committed
209
                    y_normals, x_normals.gather(1, y_index), dim=2, eps=1e-6
facebook-github-bot's avatar
facebook-github-bot committed
210
211
212
213
214
215
                )
            )
            lnorm = [lnorm1, lnorm2]  # [(N, P1), (N, P2)]

        return loss, lnorm

Nikhila Ravi's avatar
Nikhila Ravi committed
216
    def test_chamfer_point_batch_reduction_mean(self):
facebook-github-bot's avatar
facebook-github-bot committed
217
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
218
219
220
221
        Compare output of vectorized chamfer loss with naive implementation
        for the default settings (point_reduction = "mean" and batch_reduction = "mean")
        and no normals.
        This tests only uses homogeneous pointclouds.
facebook-github-bot's avatar
facebook-github-bot committed
222
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
223
        N, max_P1, max_P2 = 7, 10, 18
Nikhila Ravi's avatar
Nikhila Ravi committed
224
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
225

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        for norm in [1, 2]:
            points_normals = TestChamfer.init_pointclouds(N, max_P1, max_P2, device)
            p1 = points_normals.p1
            p2 = points_normals.p2
            weights = points_normals.weights
            p11 = p1.detach().clone()
            p22 = p2.detach().clone()
            p11.requires_grad = True
            p22.requires_grad = True
            P1 = p1.shape[1]
            P2 = p2.shape[1]

            pred_loss, pred_loss_norm = TestChamfer.chamfer_distance_naive(
                p1, p2, norm=norm
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
241

242
243
244
245
246
            # point_reduction = "mean".
            loss, loss_norm = chamfer_distance(p11, p22, weights=weights, norm=norm)
            pred_loss = pred_loss[0].sum(1) / P1 + pred_loss[1].sum(1) / P2
            pred_loss *= weights
            pred_loss = pred_loss.sum() / weights.sum()
Nikhila Ravi's avatar
Nikhila Ravi committed
247

248
249
            self.assertClose(loss, pred_loss)
            self.assertTrue(loss_norm is None)
facebook-github-bot's avatar
facebook-github-bot committed
250

251
252
            # Check gradients
            self._check_gradients(loss, None, pred_loss, None, p1, p11, p2, p22)
Nikhila Ravi's avatar
Nikhila Ravi committed
253
254

    def test_chamfer_vs_naive_pointcloud(self):
facebook-github-bot's avatar
facebook-github-bot committed
255
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
256
257
258
259
        Test the default settings for chamfer_distance
        (point reduction = "mean" and batch_reduction="mean") but with heterogeneous
        pointclouds as input. Compare with the naive implementation of chamfer
        which supports heterogeneous pointcloud objects.
facebook-github-bot's avatar
facebook-github-bot committed
260
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
261
        N, max_P1, max_P2 = 3, 70, 70
Nikhila Ravi's avatar
Nikhila Ravi committed
262
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
263

264
265
266
267
268
        for norm in [1, 2]:
            points_normals = TestChamfer.init_pointclouds(N, max_P1, max_P2, device)
            weights = points_normals.weights
            x_lengths = points_normals.p1_lengths
            y_lengths = points_normals.p2_lengths
Nikhila Ravi's avatar
Nikhila Ravi committed
269

270
271
272
273
274
275
276
277
278
279
280
            # Chamfer with tensors as input for heterogeneous pointclouds.
            cham_tensor, norm_tensor = chamfer_distance(
                points_normals.p1,
                points_normals.p2,
                x_normals=points_normals.n1,
                y_normals=points_normals.n2,
                x_lengths=points_normals.p1_lengths,
                y_lengths=points_normals.p2_lengths,
                weights=weights,
                norm=norm,
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
281

282
283
284
285
            # Chamfer with pointclouds as input.
            pred_loss, pred_norm_loss = TestChamfer.chamfer_distance_naive_pointclouds(
                points_normals.cloud1, points_normals.cloud2, norm=norm, device=device
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
            # Mean reduction point loss.
            pred_loss[0] *= weights.view(N, 1)
            pred_loss[1] *= weights.view(N, 1)
            pred_loss_mean = (
                pred_loss[0].sum(1) / x_lengths + pred_loss[1].sum(1) / y_lengths
            )
            pred_loss_mean = pred_loss_mean.sum()
            pred_loss_mean /= weights.sum()

            # Mean reduction norm loss.
            pred_norm_loss[0] *= weights.view(N, 1)
            pred_norm_loss[1] *= weights.view(N, 1)
            pred_norm_loss_mean = (
                pred_norm_loss[0].sum(1) / x_lengths
                + pred_norm_loss[1].sum(1) / y_lengths
            )
            pred_norm_loss_mean = pred_norm_loss_mean.sum() / weights.sum()
Nikhila Ravi's avatar
Nikhila Ravi committed
304

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
            self.assertClose(pred_loss_mean, cham_tensor)
            self.assertClose(pred_norm_loss_mean, norm_tensor)

            self._check_gradients(
                cham_tensor,
                norm_tensor,
                pred_loss_mean,
                pred_norm_loss_mean,
                points_normals.cloud1.points_list(),
                points_normals.p1,
                points_normals.cloud2.points_list(),
                points_normals.p2,
                points_normals.cloud1.normals_list(),
                points_normals.n1,
                points_normals.cloud2.normals_list(),
                points_normals.n2,
                x_lengths,
                y_lengths,
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
324
325
326
327

    def test_chamfer_pointcloud_object_withnormals(self):
        N = 5
        P1, P2 = 100, 100
Nikhila Ravi's avatar
Nikhila Ravi committed
328
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
329
330
331
332
333
334
335
336
337
338
339
340
341

        reductions = [
            ("sum", "sum"),
            ("mean", "sum"),
            ("sum", "mean"),
            ("mean", "mean"),
            ("sum", None),
            ("mean", None),
        ]
        for (point_reduction, batch_reduction) in reductions:

            # Reinitialize all the tensors so that the
            # backward pass can be computed.
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
342
343
344
            points_normals = TestChamfer.init_pointclouds(
                N, P1, P2, device, allow_empty=False
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

            # Chamfer with pointclouds as input.
            cham_cloud, norm_cloud = chamfer_distance(
                points_normals.cloud1,
                points_normals.cloud2,
                point_reduction=point_reduction,
                batch_reduction=batch_reduction,
            )

            # Chamfer with tensors as input.
            cham_tensor, norm_tensor = chamfer_distance(
                points_normals.p1,
                points_normals.p2,
                x_lengths=points_normals.p1_lengths,
                y_lengths=points_normals.p2_lengths,
                x_normals=points_normals.n1,
                y_normals=points_normals.n2,
                point_reduction=point_reduction,
                batch_reduction=batch_reduction,
            )

            self.assertClose(cham_cloud, cham_tensor)
            self.assertClose(norm_cloud, norm_tensor)
            self._check_gradients(
                cham_tensor,
                norm_tensor,
                cham_cloud,
                norm_cloud,
                points_normals.cloud1.points_list(),
                points_normals.p1,
                points_normals.cloud2.points_list(),
                points_normals.p2,
                points_normals.cloud1.normals_list(),
                points_normals.n1,
                points_normals.cloud2.normals_list(),
                points_normals.n2,
                points_normals.p1_lengths,
                points_normals.p2_lengths,
            )

    def test_chamfer_pointcloud_object_nonormals(self):
        N = 5
        P1, P2 = 100, 100
Nikhila Ravi's avatar
Nikhila Ravi committed
388
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
389
390
391
392
393
394
395
396
397
398
399
400
401

        reductions = [
            ("sum", "sum"),
            ("mean", "sum"),
            ("sum", "mean"),
            ("mean", "mean"),
            ("sum", None),
            ("mean", None),
        ]
        for (point_reduction, batch_reduction) in reductions:

            # Reinitialize all the tensors so that the
            # backward pass can be computed.
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
402
403
404
            points_normals = TestChamfer.init_pointclouds(
                N, P1, P2, device, allow_empty=False
            )
Nikhila Ravi's avatar
Nikhila Ravi committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443

            # Chamfer with pointclouds as input.
            cham_cloud, _ = chamfer_distance(
                points_normals.cloud1,
                points_normals.cloud2,
                point_reduction=point_reduction,
                batch_reduction=batch_reduction,
            )

            # Chamfer with tensors as input.
            cham_tensor, _ = chamfer_distance(
                points_normals.p1,
                points_normals.p2,
                x_lengths=points_normals.p1_lengths,
                y_lengths=points_normals.p2_lengths,
                point_reduction=point_reduction,
                batch_reduction=batch_reduction,
            )

            self.assertClose(cham_cloud, cham_tensor)
            self._check_gradients(
                cham_tensor,
                None,
                cham_cloud,
                None,
                points_normals.cloud1.points_list(),
                points_normals.p1,
                points_normals.cloud2.points_list(),
                points_normals.p2,
                lengths1=points_normals.p1_lengths,
                lengths2=points_normals.p2_lengths,
            )

    def test_chamfer_point_reduction_mean(self):
        """
        Compare output of vectorized chamfer loss with naive implementation
        for point_reduction = "mean" and batch_reduction = None.
        """
        N, max_P1, max_P2 = 7, 10, 18
Nikhila Ravi's avatar
Nikhila Ravi committed
444
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
445
446
447
448
449
450
451
452
453
454
455
456
457
        points_normals = TestChamfer.init_pointclouds(N, max_P1, max_P2, device)
        p1 = points_normals.p1
        p2 = points_normals.p2
        p1_normals = points_normals.n1
        p2_normals = points_normals.n2
        weights = points_normals.weights
        p11 = p1.detach().clone()
        p22 = p2.detach().clone()
        p11.requires_grad = True
        p22.requires_grad = True
        P1 = p1.shape[1]
        P2 = p2.shape[1]

facebook-github-bot's avatar
facebook-github-bot committed
458
        pred_loss, pred_loss_norm = TestChamfer.chamfer_distance_naive(
Nikhila Ravi's avatar
Nikhila Ravi committed
459
            p1, p2, x_normals=p1_normals, y_normals=p2_normals
facebook-github-bot's avatar
facebook-github-bot committed
460
461
462
463
        )

        # point_reduction = "mean".
        loss, loss_norm = chamfer_distance(
Nikhila Ravi's avatar
Nikhila Ravi committed
464
465
466
467
            p11,
            p22,
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
468
            weights=weights,
Nikhila Ravi's avatar
Nikhila Ravi committed
469
            batch_reduction=None,
facebook-github-bot's avatar
facebook-github-bot committed
470
471
472
473
            point_reduction="mean",
        )
        pred_loss_mean = pred_loss[0].sum(1) / P1 + pred_loss[1].sum(1) / P2
        pred_loss_mean *= weights
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
474
        self.assertClose(loss, pred_loss_mean)
facebook-github-bot's avatar
facebook-github-bot committed
475
476
477
478
479

        pred_loss_norm_mean = (
            pred_loss_norm[0].sum(1) / P1 + pred_loss_norm[1].sum(1) / P2
        )
        pred_loss_norm_mean *= weights
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
480
        self.assertClose(loss_norm, pred_loss_norm_mean)
facebook-github-bot's avatar
facebook-github-bot committed
481

Nikhila Ravi's avatar
Nikhila Ravi committed
482
483
484
485
486
487
488
489
490
491
492
        # Check gradients
        self._check_gradients(
            loss, loss_norm, pred_loss_mean, pred_loss_norm_mean, p1, p11, p2, p22
        )

    def test_chamfer_point_reduction_sum(self):
        """
        Compare output of vectorized chamfer loss with naive implementation
        for point_reduction = "sum" and batch_reduction = None.
        """
        N, P1, P2 = 7, 10, 18
Nikhila Ravi's avatar
Nikhila Ravi committed
493
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
        points_normals = TestChamfer.init_pointclouds(N, P1, P2, device)
        p1 = points_normals.p1
        p2 = points_normals.p2
        p1_normals = points_normals.n1
        p2_normals = points_normals.n2
        weights = points_normals.weights
        p11 = p1.detach().clone()
        p22 = p2.detach().clone()
        p11.requires_grad = True
        p22.requires_grad = True

        pred_loss, pred_loss_norm = TestChamfer.chamfer_distance_naive(
            p1, p2, x_normals=p1_normals, y_normals=p2_normals
        )

facebook-github-bot's avatar
facebook-github-bot committed
509
        loss, loss_norm = chamfer_distance(
Nikhila Ravi's avatar
Nikhila Ravi committed
510
511
512
513
            p11,
            p22,
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
514
            weights=weights,
Nikhila Ravi's avatar
Nikhila Ravi committed
515
            batch_reduction=None,
facebook-github-bot's avatar
facebook-github-bot committed
516
517
518
519
            point_reduction="sum",
        )
        pred_loss_sum = pred_loss[0].sum(1) + pred_loss[1].sum(1)
        pred_loss_sum *= weights
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
520
        self.assertClose(loss, pred_loss_sum)
facebook-github-bot's avatar
facebook-github-bot committed
521
522
523

        pred_loss_norm_sum = pred_loss_norm[0].sum(1) + pred_loss_norm[1].sum(1)
        pred_loss_norm_sum *= weights
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
524
        self.assertClose(loss_norm, pred_loss_norm_sum)
facebook-github-bot's avatar
facebook-github-bot committed
525

Nikhila Ravi's avatar
Nikhila Ravi committed
526
527
528
529
        # Check gradients
        self._check_gradients(
            loss, loss_norm, pred_loss_sum, pred_loss_norm_sum, p1, p11, p2, p22
        )
facebook-github-bot's avatar
facebook-github-bot committed
530

Nikhila Ravi's avatar
Nikhila Ravi committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    def _check_gradients(
        self,
        loss,
        loss_norm,
        pred_loss,
        pred_loss_norm,
        x1,
        x2,
        y1,
        y2,
        xn1=None,  # normals
        xn2=None,  # normals
        yn1=None,  # normals
        yn2=None,  # normals
        lengths1=None,
        lengths2=None,
    ):
facebook-github-bot's avatar
facebook-github-bot committed
548
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
549
550
551
        x1 and x2 can have different types based on the leaf node used in the calculation:
        e.g. x1 may be a list of tensors whereas x2 is a padded tensor.
        This also applies for the pairs: (y1, y2), (xn1, xn2), (yn1, yn2).
facebook-github-bot's avatar
facebook-github-bot committed
552
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
553
        grad_loss = torch.rand(loss.shape, device=loss.device, dtype=loss.dtype)
facebook-github-bot's avatar
facebook-github-bot committed
554

Nikhila Ravi's avatar
Nikhila Ravi committed
555
556
557
558
559
560
561
562
        # Loss for normals is optional. Iniitalize to 0.
        norm_loss_term = pred_norm_loss_term = 0.0
        if loss_norm is not None and pred_loss_norm is not None:
            grad_normals = torch.rand(
                loss_norm.shape, device=loss.device, dtype=loss.dtype
            )
            norm_loss_term = loss_norm * grad_normals
            pred_norm_loss_term = pred_loss_norm * grad_normals
facebook-github-bot's avatar
facebook-github-bot committed
563

Nikhila Ravi's avatar
Nikhila Ravi committed
564
565
566
567
        l1 = (loss * grad_loss) + norm_loss_term
        l1.sum().backward()
        l2 = (pred_loss * grad_loss) + pred_norm_loss_term
        l2.sum().backward()
facebook-github-bot's avatar
facebook-github-bot committed
568

Nikhila Ravi's avatar
Nikhila Ravi committed
569
570
        self._check_grad_by_type(x1, x2, lengths1)
        self._check_grad_by_type(y1, y2, lengths2)
facebook-github-bot's avatar
facebook-github-bot committed
571

Nikhila Ravi's avatar
Nikhila Ravi committed
572
573
574
575
        # If leaf nodes for normals are passed in, check their gradients.
        if all(n is not None for n in [xn1, xn2, yn1, yn2]):
            self._check_grad_by_type(xn1, xn2, lengths1)
            self._check_grad_by_type(yn1, yn2, lengths2)
facebook-github-bot's avatar
facebook-github-bot committed
576

Nikhila Ravi's avatar
Nikhila Ravi committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    def _check_grad_by_type(self, x1, x2, lengths=None):
        """
        x1 and x2 can be of different types e.g. list or tensor - compare appropriately
        based on the types.
        """
        error_msg = "All values for gradient checks must be tensors or lists of tensors"

        if all(isinstance(p, list) for p in [x1, x2]):
            # Lists of tensors
            for i in range(len(x1)):
                self.assertClose(x1[i].grad, x2[i].grad)
        elif isinstance(x1, list) and torch.is_tensor(x2):
            self.assertIsNotNone(lengths)  # lengths is required

            # List of tensors vs padded tensor
            for i in range(len(x1)):
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
593
                self.assertClose(x1[i].grad, x2.grad[i, : lengths[i]], atol=1e-7)
Nikhila Ravi's avatar
Nikhila Ravi committed
594
595
596
597
598
599
                self.assertTrue(x2.grad[i, lengths[i] :].sum().item() == 0.0)
        elif all(torch.is_tensor(p) for p in [x1, x2]):
            # Two tensors
            self.assertClose(x1.grad, x2.grad)
        else:
            raise ValueError(error_msg)
facebook-github-bot's avatar
facebook-github-bot committed
600
601
602
603

    def test_chamfer_joint_reduction(self):
        """
        Compare output of vectorized chamfer loss with naive implementation
Nikhila Ravi's avatar
Nikhila Ravi committed
604
        when batch_reduction in ["mean", "sum"] and
facebook-github-bot's avatar
facebook-github-bot committed
605
606
        point_reduction in ["mean", "sum"].
        """
Nikhila Ravi's avatar
Nikhila Ravi committed
607
        N, max_P1, max_P2 = 7, 10, 18
Nikhila Ravi's avatar
Nikhila Ravi committed
608
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
609
610
611
612
613
614
615
616
617
618

        points_normals = TestChamfer.init_pointclouds(N, max_P1, max_P2, device)
        p1 = points_normals.p1
        p2 = points_normals.p2
        p1_normals = points_normals.n1
        p2_normals = points_normals.n2
        weights = points_normals.weights

        P1 = p1.shape[1]
        P2 = p2.shape[1]
facebook-github-bot's avatar
facebook-github-bot committed
619
620

        pred_loss, pred_loss_norm = TestChamfer.chamfer_distance_naive(
Nikhila Ravi's avatar
Nikhila Ravi committed
621
            p1, p2, x_normals=p1_normals, y_normals=p2_normals
facebook-github-bot's avatar
facebook-github-bot committed
622
623
624
625
626
627
        )

        # batch_reduction = "sum", point_reduction = "sum".
        loss, loss_norm = chamfer_distance(
            p1,
            p2,
Nikhila Ravi's avatar
Nikhila Ravi committed
628
629
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
630
631
632
633
634
635
636
637
            weights=weights,
            batch_reduction="sum",
            point_reduction="sum",
        )
        pred_loss[0] *= weights.view(N, 1)
        pred_loss[1] *= weights.view(N, 1)
        pred_loss_sum = pred_loss[0].sum(1) + pred_loss[1].sum(1)  # point sum
        pred_loss_sum = pred_loss_sum.sum()  # batch sum
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
638
        self.assertClose(loss, pred_loss_sum)
facebook-github-bot's avatar
facebook-github-bot committed
639
640
641
642
643
644
645

        pred_loss_norm[0] *= weights.view(N, 1)
        pred_loss_norm[1] *= weights.view(N, 1)
        pred_loss_norm_sum = pred_loss_norm[0].sum(1) + pred_loss_norm[1].sum(
            1
        )  # point sum.
        pred_loss_norm_sum = pred_loss_norm_sum.sum()  # batch sum
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
646
        self.assertClose(loss_norm, pred_loss_norm_sum)
facebook-github-bot's avatar
facebook-github-bot committed
647
648
649
650
651

        # batch_reduction = "mean", point_reduction = "sum".
        loss, loss_norm = chamfer_distance(
            p1,
            p2,
Nikhila Ravi's avatar
Nikhila Ravi committed
652
653
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
654
655
656
657
658
            weights=weights,
            batch_reduction="mean",
            point_reduction="sum",
        )
        pred_loss_sum /= weights.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
659
        self.assertClose(loss, pred_loss_sum)
facebook-github-bot's avatar
facebook-github-bot committed
660
661

        pred_loss_norm_sum /= weights.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
662
        self.assertClose(loss_norm, pred_loss_norm_sum)
facebook-github-bot's avatar
facebook-github-bot committed
663
664
665
666
667

        # batch_reduction = "sum", point_reduction = "mean".
        loss, loss_norm = chamfer_distance(
            p1,
            p2,
Nikhila Ravi's avatar
Nikhila Ravi committed
668
669
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
670
671
672
673
674
675
            weights=weights,
            batch_reduction="sum",
            point_reduction="mean",
        )
        pred_loss_mean = pred_loss[0].sum(1) / P1 + pred_loss[1].sum(1) / P2
        pred_loss_mean = pred_loss_mean.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
676
        self.assertClose(loss, pred_loss_mean)
facebook-github-bot's avatar
facebook-github-bot committed
677
678
679
680
681

        pred_loss_norm_mean = (
            pred_loss_norm[0].sum(1) / P1 + pred_loss_norm[1].sum(1) / P2
        )
        pred_loss_norm_mean = pred_loss_norm_mean.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
682
        self.assertClose(loss_norm, pred_loss_norm_mean)
facebook-github-bot's avatar
facebook-github-bot committed
683
684
685
686
687

        # batch_reduction = "mean", point_reduction = "mean". This is the default.
        loss, loss_norm = chamfer_distance(
            p1,
            p2,
Nikhila Ravi's avatar
Nikhila Ravi committed
688
689
            x_normals=p1_normals,
            y_normals=p2_normals,
facebook-github-bot's avatar
facebook-github-bot committed
690
691
692
693
694
            weights=weights,
            batch_reduction="mean",
            point_reduction="mean",
        )
        pred_loss_mean /= weights.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
695
        self.assertClose(loss, pred_loss_mean)
facebook-github-bot's avatar
facebook-github-bot committed
696
697

        pred_loss_norm_mean /= weights.sum()
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
698
        self.assertClose(loss_norm, pred_loss_norm_mean)
facebook-github-bot's avatar
facebook-github-bot committed
699

Nikhila Ravi's avatar
Nikhila Ravi committed
700
701
702
703
704
705
706
707
        # Error when batch_reduction is not in ["mean", "sum"] or None.
        with self.assertRaisesRegex(ValueError, "batch_reduction must be one of"):
            chamfer_distance(p1, p2, weights=weights, batch_reduction="max")

        # Error when point_reduction is not in ["mean", "sum"].
        with self.assertRaisesRegex(ValueError, "point_reduction must be one of"):
            chamfer_distance(p1, p2, weights=weights, point_reduction=None)

facebook-github-bot's avatar
facebook-github-bot committed
708
709
    def test_incorrect_weights(self):
        N, P1, P2 = 16, 64, 128
Nikhila Ravi's avatar
Nikhila Ravi committed
710
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
711
712
713
714
715
716
717
718
719
720
721
        p1 = torch.rand(
            (N, P1, 3), dtype=torch.float32, device=device, requires_grad=True
        )
        p2 = torch.rand(
            (N, P2, 3), dtype=torch.float32, device=device, requires_grad=True
        )

        weights = torch.zeros((N,), dtype=torch.float32, device=device)
        loss, loss_norm = chamfer_distance(
            p1, p2, weights=weights, batch_reduction="mean"
        )
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
722
        self.assertClose(loss.cpu(), torch.zeros(()))
facebook-github-bot's avatar
facebook-github-bot committed
723
        self.assertTrue(loss.requires_grad)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
724
        self.assertClose(loss_norm.cpu(), torch.zeros(()))
facebook-github-bot's avatar
facebook-github-bot committed
725
726
727
        self.assertTrue(loss_norm.requires_grad)

        loss, loss_norm = chamfer_distance(
Nikhila Ravi's avatar
Nikhila Ravi committed
728
            p1, p2, weights=weights, batch_reduction=None
facebook-github-bot's avatar
facebook-github-bot committed
729
        )
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
730
        self.assertClose(loss.cpu(), torch.zeros((N, N)))
facebook-github-bot's avatar
facebook-github-bot committed
731
        self.assertTrue(loss.requires_grad)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
732
        self.assertClose(loss_norm.cpu(), torch.zeros((N, N)))
facebook-github-bot's avatar
facebook-github-bot committed
733
734
735
736
737
738
739
740
741
742
        self.assertTrue(loss_norm.requires_grad)

        weights = torch.ones((N,), dtype=torch.float32, device=device) * -1
        with self.assertRaises(ValueError):
            loss, loss_norm = chamfer_distance(p1, p2, weights=weights)

        weights = torch.zeros((N - 1,), dtype=torch.float32, device=device)
        with self.assertRaises(ValueError):
            loss, loss_norm = chamfer_distance(p1, p2, weights=weights)

Nikhila Ravi's avatar
Nikhila Ravi committed
743
744
    def test_incorrect_inputs(self):
        N, P1, P2 = 7, 10, 18
Nikhila Ravi's avatar
Nikhila Ravi committed
745
        device = get_random_cuda_device()
Nikhila Ravi's avatar
Nikhila Ravi committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
        points_normals = TestChamfer.init_pointclouds(N, P1, P2, device)
        p1 = points_normals.p1
        p2 = points_normals.p2
        p1_normals = points_normals.n1

        # Normals of wrong shape
        with self.assertRaisesRegex(ValueError, "Expected normals to be of shape"):
            chamfer_distance(p1, p2, x_normals=p1_normals[None])

        # Points of wrong shape
        with self.assertRaisesRegex(ValueError, "Expected points to be of shape"):
            chamfer_distance(p1[None], p2)

        # Lengths of wrong shape
        with self.assertRaisesRegex(ValueError, "Expected lengths to be of shape"):
            chamfer_distance(p1, p2, x_lengths=torch.tensor([1, 2, 3], device=device))

        # Points are not a tensor or Pointclouds
        with self.assertRaisesRegex(ValueError, "Pointclouds objects or torch.Tensor"):
            chamfer_distance(x=[1, 1, 1], y=[1, 1, 1])

767
768
769
770
771
772
773
774
775
776
777
778
779
    def test_invalid_norm(self):
        N, P1, P2 = 7, 10, 18
        device = get_random_cuda_device()
        points_normals = TestChamfer.init_pointclouds(N, P1, P2, device)
        p1 = points_normals.p1
        p2 = points_normals.p2

        with self.assertRaisesRegex(ValueError, "Support for 1 or 2 norm."):
            chamfer_distance(p1, p2, norm=0)

        with self.assertRaisesRegex(ValueError, "Support for 1 or 2 norm."):
            chamfer_distance(p1, p2, norm=3)

facebook-github-bot's avatar
facebook-github-bot committed
780
    @staticmethod
Nikhila Ravi's avatar
Nikhila Ravi committed
781
    def chamfer_with_init(
Nikhila Ravi's avatar
Nikhila Ravi committed
782
783
784
785
786
787
        batch_size: int,
        P1: int,
        P2: int,
        return_normals: bool,
        homogeneous: bool,
        device="cpu",
Nikhila Ravi's avatar
Nikhila Ravi committed
788
    ):
Nikhila Ravi's avatar
Nikhila Ravi committed
789
790
791
        points_normals = TestChamfer.init_pointclouds(batch_size, P1, P2, device=device)
        l1 = points_normals.p1_lengths
        l2 = points_normals.p2_lengths
Nikhila Ravi's avatar
Nikhila Ravi committed
792
793
794
795
796
        if homogeneous:
            # Set lengths to None so in Chamfer it assumes
            # there is no padding.
            l1 = l2 = None

facebook-github-bot's avatar
facebook-github-bot committed
797
798
799
800
        torch.cuda.synchronize()

        def loss():
            loss, loss_normals = chamfer_distance(
Nikhila Ravi's avatar
Nikhila Ravi committed
801
802
                points_normals.p1,
                points_normals.p2,
Nikhila Ravi's avatar
Nikhila Ravi committed
803
804
                x_lengths=l1,
                y_lengths=l2,
Nikhila Ravi's avatar
Nikhila Ravi committed
805
806
807
                x_normals=points_normals.n1,
                y_normals=points_normals.n2,
                weights=points_normals.weights,
facebook-github-bot's avatar
facebook-github-bot committed
808
809
810
811
812
813
814
            )
            torch.cuda.synchronize()

        return loss

    @staticmethod
    def chamfer_naive_with_init(
Nikhila Ravi's avatar
Nikhila Ravi committed
815
        batch_size: int, P1: int, P2: int, return_normals: bool, device="cpu"
facebook-github-bot's avatar
facebook-github-bot committed
816
    ):
Nikhila Ravi's avatar
Nikhila Ravi committed
817
        points_normals = TestChamfer.init_pointclouds(batch_size, P1, P2, device=device)
facebook-github-bot's avatar
facebook-github-bot committed
818
819
820
821
        torch.cuda.synchronize()

        def loss():
            loss, loss_normals = TestChamfer.chamfer_distance_naive(
Nikhila Ravi's avatar
Nikhila Ravi committed
822
823
824
825
                points_normals.p1,
                points_normals.p2,
                x_normals=points_normals.n1,
                y_normals=points_normals.n2,
facebook-github-bot's avatar
facebook-github-bot committed
826
827
828
829
            )
            torch.cuda.synchronize()

        return loss