test_compositing.py 13.8 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.
Olivia's avatar
Olivia committed
6
7
8

import unittest

9
import torch
Olivia's avatar
Olivia committed
10
11
12
13
14
15
from pytorch3d.renderer.compositing import (
    alpha_composite,
    norm_weighted_sum,
    weighted_sum,
)

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
16
17
from .common_testing import get_random_cuda_device, TestCaseMixin

Olivia's avatar
Olivia committed
18

Nikhila Ravi's avatar
Nikhila Ravi committed
19
class TestAccumulatePoints(TestCaseMixin, unittest.TestCase):
Olivia's avatar
Olivia committed
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

    # NAIVE PYTHON IMPLEMENTATIONS (USED FOR TESTING)
    @staticmethod
    def accumulate_alphacomposite_python(points_idx, alphas, features):
        """
        Naive pure PyTorch implementation of alpha_composite.
        Inputs / Outputs: Same as function
        """

        B, K, H, W = points_idx.size()
        C = features.size(0)

        output = torch.zeros(B, C, H, W, dtype=alphas.dtype)

        for b in range(0, B):
            for c in range(0, C):
                for i in range(0, W):
                    for j in range(0, H):
                        t_alpha = 1
                        for k in range(0, K):
                            n_idx = points_idx[b, k, j, i]

                            if n_idx < 0:
                                continue

                            alpha = alphas[b, k, j, i]
46
                            output[b, c, j, i] += features[c, n_idx] * alpha * t_alpha
Olivia's avatar
Olivia committed
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
                            t_alpha = (1 - alpha) * t_alpha

        return output

    @staticmethod
    def accumulate_weightedsum_python(points_idx, alphas, features):
        """
        Naive pure PyTorch implementation of weighted_sum rasterization.
        Inputs / Outputs: Same as function
        """
        B, K, H, W = points_idx.size()
        C = features.size(0)

        output = torch.zeros(B, C, H, W, dtype=alphas.dtype)

        for b in range(0, B):
            for c in range(0, C):
                for i in range(0, W):
                    for j in range(0, H):

                        for k in range(0, K):
                            n_idx = points_idx[b, k, j, i]

                            if n_idx < 0:
                                continue

                            alpha = alphas[b, k, j, i]
                            output[b, c, j, i] += features[c, n_idx] * alpha

        return output

    @staticmethod
    def accumulate_weightedsumnorm_python(points_idx, alphas, features):
        """
        Naive pure PyTorch implementation of norm_weighted_sum.
        Inputs / Outputs: Same as function
        """

        B, K, H, W = points_idx.size()
        C = features.size(0)

        output = torch.zeros(B, C, H, W, dtype=alphas.dtype)

        for b in range(0, B):
            for c in range(0, C):
                for i in range(0, W):
                    for j in range(0, H):
                        t_alpha = 0
                        for k in range(0, K):
                            n_idx = points_idx[b, k, j, i]

                            if n_idx < 0:
                                continue

                            t_alpha += alphas[b, k, j, i]

                        t_alpha = max(t_alpha, 1e-4)

                        for k in range(0, K):
                            n_idx = points_idx[b, k, j, i]

                            if n_idx < 0:
                                continue

                            alpha = alphas[b, k, j, i]
112
                            output[b, c, j, i] += features[c, n_idx] * alpha / t_alpha
Olivia's avatar
Olivia committed
113
114
115
116
117

        return output

    def test_python(self):
        device = torch.device("cpu")
118
        self._simple_alphacomposite(self.accumulate_alphacomposite_python, device)
Olivia's avatar
Olivia committed
119
120
121
122
123
124
125
126
127
128
        self._simple_wsum(self.accumulate_weightedsum_python, device)
        self._simple_wsumnorm(self.accumulate_weightedsumnorm_python, device)

    def test_cpu(self):
        device = torch.device("cpu")
        self._simple_alphacomposite(alpha_composite, device)
        self._simple_wsum(weighted_sum, device)
        self._simple_wsumnorm(norm_weighted_sum, device)

    def test_cuda(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
129
        device = get_random_cuda_device()
Olivia's avatar
Olivia committed
130
131
132
133
134
135
136
137
138
139
140
        self._simple_alphacomposite(alpha_composite, device)
        self._simple_wsum(weighted_sum, device)
        self._simple_wsumnorm(norm_weighted_sum, device)

    def test_python_vs_cpu_vs_cuda(self):
        self._python_vs_cpu_vs_cuda(
            self.accumulate_alphacomposite_python, alpha_composite
        )
        self._python_vs_cpu_vs_cuda(
            self.accumulate_weightedsumnorm_python, norm_weighted_sum
        )
141
        self._python_vs_cpu_vs_cuda(self.accumulate_weightedsum_python, weighted_sum)
Olivia's avatar
Olivia committed
142
143
144
145
146
147
148
149
150

    def _python_vs_cpu_vs_cuda(self, accumulate_func_python, accumulate_func):
        torch.manual_seed(231)
        device = torch.device("cpu")

        W = 8
        C = 3
        P = 32

Nikhila Ravi's avatar
Nikhila Ravi committed
151
        for d in ["cpu", get_random_cuda_device()]:
Olivia's avatar
Olivia committed
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
            # TODO(gkioxari) add torch.float64 to types after double precision
            # support is added to atomicAdd
            for t in [torch.float32]:
                device = torch.device(d)

                # Create values
                alphas = torch.rand(2, 4, W, W, dtype=t).to(device)
                alphas.requires_grad = True
                alphas_cpu = alphas.detach().cpu()
                alphas_cpu.requires_grad = True

                features = torch.randn(C, P, dtype=t).to(device)
                features.requires_grad = True
                features_cpu = features.detach().cpu()
                features_cpu.requires_grad = True

                inds = torch.randint(P + 1, size=(2, 4, W, W)).to(device) - 1
                inds_cpu = inds.detach().cpu()

                args_cuda = (inds, alphas, features)
                args_cpu = (inds_cpu, alphas_cpu, features_cpu)

                self._compare_impls(
                    accumulate_func_python,
                    accumulate_func,
                    args_cpu,
                    args_cuda,
                    (alphas_cpu, features_cpu),
                    (alphas, features),
                    compare_grads=True,
                )

    def _compare_impls(
        self, fn1, fn2, args1, args2, grads1, grads2, compare_grads=False
    ):
        res1 = fn1(*args1)
        res2 = fn2(*args2)
Georgia Gkioxari's avatar
Georgia Gkioxari committed
189

Nikhila Ravi's avatar
Nikhila Ravi committed
190
        self.assertClose(res1.cpu(), res2.cpu(), atol=1e-6)
Olivia's avatar
Olivia committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

        if not compare_grads:
            return

        # Compare gradients
        torch.manual_seed(231)
        grad_res = torch.randn_like(res1)
        loss1 = (res1 * grad_res).sum()
        loss1.backward()

        grads1 = [gradsi.grad.data.clone().cpu() for gradsi in grads1]
        grad_res = grad_res.to(res2)

        loss2 = (res2 * grad_res).sum()
        loss2.backward()
        grads2 = [gradsi.grad.data.clone().cpu() for gradsi in grads2]

        for i in range(0, len(grads1)):
Nikhila Ravi's avatar
Nikhila Ravi committed
209
            self.assertClose(grads1[i].cpu(), grads2[i].cpu(), atol=1e-6)
Olivia's avatar
Olivia committed
210
211
212

    def _simple_wsum(self, accum_func, device):
        # Initialise variables
213
        features = torch.Tensor([[0.1, 0.4, 0.6, 0.9], [0.1, 0.4, 0.6, 0.9]]).to(device)
Olivia's avatar
Olivia committed
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

        alphas = torch.Tensor(
            [
                [
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                ]
            ]
        ).to(device)

        points_idx = (
            torch.Tensor(
                [
                    [
                        # fmt: off
                        [
                            [0,  0,  0,  0],  # noqa: E241, E201
                            [0, -1, -1, -1],  # noqa: E241, E201
                            [0,  1,  1,  0],  # noqa: E241, E201
                            [0,  0,  0,  0],  # noqa: E241, E201
                        ],
                        [
                            [2,  2,  2,  2],  # noqa: E241, E201
                            [2,  3,  3,  2],  # noqa: E241, E201
                            [2,  3,  3,  2],  # noqa: E241, E201
                            [2,  2, -1,  2],  # noqa: E241, E201
                        ],
                        # fmt: on
                    ]
                ]
            )
            .long()
            .to(device)
        )

        result = accum_func(points_idx, alphas, features)

        self.assertTrue(result.shape == (1, 2, 4, 4))

        true_result = torch.Tensor(
            [
                [
                    [
                        [0.35, 0.35, 0.35, 0.35],
                        [0.35, 0.90, 0.90, 0.30],
                        [0.35, 1.30, 1.30, 0.35],
                        [0.35, 0.35, 0.05, 0.35],
                    ],
                    [
                        [0.35, 0.35, 0.35, 0.35],
                        [0.35, 0.90, 0.90, 0.30],
                        [0.35, 1.30, 1.30, 0.35],
                        [0.35, 0.35, 0.05, 0.35],
                    ],
                ]
            ]
        ).to(device)

Nikhila Ravi's avatar
Nikhila Ravi committed
282
        self.assertClose(result.cpu(), true_result.cpu(), rtol=1e-3)
Olivia's avatar
Olivia committed
283
284
285

    def _simple_wsumnorm(self, accum_func, device):
        # Initialise variables
286
        features = torch.Tensor([[0.1, 0.4, 0.6, 0.9], [0.1, 0.4, 0.6, 0.9]]).to(device)
Olivia's avatar
Olivia committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

        alphas = torch.Tensor(
            [
                [
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                ]
            ]
        ).to(device)

        # fmt: off
        points_idx = (
            torch.Tensor(
                [
                    [
                        [
                            [0,  0,  0,  0],  # noqa: E241, E201
                            [0, -1, -1, -1],  # noqa: E241, E201
                            [0,  1,  1,  0],  # noqa: E241, E201
                            [0,  0,  0,  0],  # noqa: E241, E201
                        ],
                        [
                            [2, 2,  2, 2],  # noqa: E241, E201
                            [2, 3,  3, 2],  # noqa: E241, E201
                            [2, 3,  3, 2],  # noqa: E241, E201
                            [2, 2, -1, 2],  # noqa: E241, E201
                        ],
                    ]
                ]
            )
            .long()
            .to(device)
        )
        # fmt: on

        result = accum_func(points_idx, alphas, features)

        self.assertTrue(result.shape == (1, 2, 4, 4))

        true_result = torch.Tensor(
            [
                [
                    [
                        [0.35, 0.35, 0.35, 0.35],
                        [0.35, 0.90, 0.90, 0.60],
                        [0.35, 0.65, 0.65, 0.35],
                        [0.35, 0.35, 0.10, 0.35],
                    ],
                    [
                        [0.35, 0.35, 0.35, 0.35],
                        [0.35, 0.90, 0.90, 0.60],
                        [0.35, 0.65, 0.65, 0.35],
                        [0.35, 0.35, 0.10, 0.35],
                    ],
                ]
            ]
        ).to(device)

Nikhila Ravi's avatar
Nikhila Ravi committed
355
        self.assertClose(result.cpu(), true_result.cpu(), rtol=1e-3)
Olivia's avatar
Olivia committed
356
357
358

    def _simple_alphacomposite(self, accum_func, device):
        # Initialise variables
359
        features = torch.Tensor([[0.1, 0.4, 0.6, 0.9], [0.1, 0.4, 0.6, 0.9]]).to(device)
Olivia's avatar
Olivia committed
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

        alphas = torch.Tensor(
            [
                [
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                    [
                        [0.5, 0.5, 0.5, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 1.0, 1.0, 0.5],
                        [0.5, 0.5, 0.5, 0.5],
                    ],
                ]
            ]
        ).to(device)

        # fmt: off
        points_idx = (
            torch.Tensor(
                [
                    [
                        [
                            [0,  0,  0,  0],  # noqa: E241, E201
                            [0, -1, -1, -1],  # noqa: E241, E201
                            [0,  1,  1,  0],  # noqa: E241, E201
                            [0,  0,  0,  0],  # noqa: E241, E201
                        ],
                        [
                            [2, 2,  2, 2],  # noqa: E241, E201
                            [2, 3,  3, 2],  # noqa: E241, E201
                            [2, 3,  3, 2],  # noqa: E241, E201
                            [2, 2, -1, 2],  # noqa: E241, E201
                        ],
                    ]
                ]
            )
            .long()
            .to(device)
        )
        # fmt: on

        result = accum_func(points_idx, alphas, features)

        self.assertTrue(result.shape == (1, 2, 4, 4))

        true_result = torch.Tensor(
            [
                [
                    [
                        [0.20, 0.20, 0.20, 0.20],
                        [0.20, 0.90, 0.90, 0.30],
                        [0.20, 0.40, 0.40, 0.20],
                        [0.20, 0.20, 0.05, 0.20],
                    ],
                    [
                        [0.20, 0.20, 0.20, 0.20],
                        [0.20, 0.90, 0.90, 0.30],
                        [0.20, 0.40, 0.40, 0.20],
                        [0.20, 0.20, 0.05, 0.20],
                    ],
                ]
            ]
        ).to(device)

        self.assertTrue((result == true_result).all().item())