test_rasterize_meshes.py 55.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.
facebook-github-bot's avatar
facebook-github-bot committed
6
7
8
9

import functools
import unittest

10
import torch
facebook-github-bot's avatar
facebook-github-bot committed
11
from pytorch3d import _C
12
13
from pytorch3d.renderer import FoVPerspectiveCameras, look_at_view_transform
from pytorch3d.renderer.mesh import MeshRasterizer, RasterizationSettings
facebook-github-bot's avatar
facebook-github-bot committed
14
15
16
17
from pytorch3d.renderer.mesh.rasterize_meshes import (
    rasterize_meshes,
    rasterize_meshes_python,
)
18
19
20
21
from pytorch3d.renderer.mesh.utils import (
    _clip_barycentric_coordinates,
    _interpolate_zbuf,
)
facebook-github-bot's avatar
facebook-github-bot committed
22
23
24
from pytorch3d.structures import Meshes
from pytorch3d.utils import ico_sphere

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
25
26
from .common_testing import get_random_cuda_device, TestCaseMixin

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
27
28

class TestRasterizeMeshes(TestCaseMixin, unittest.TestCase):
facebook-github-bot's avatar
facebook-github-bot committed
29
30
    def test_simple_python(self):
        device = torch.device("cpu")
31
        self._simple_triangle_raster(rasterize_meshes_python, device, bin_size=-1)
facebook-github-bot's avatar
facebook-github-bot committed
32
33
        self._simple_blurry_raster(rasterize_meshes_python, device, bin_size=-1)
        self._test_behind_camera(rasterize_meshes_python, device, bin_size=-1)
34
        self._test_perspective_correct(rasterize_meshes_python, device, bin_size=-1)
35
        self._test_barycentric_clipping(rasterize_meshes_python, device, bin_size=-1)
36
        self._test_back_face_culling(rasterize_meshes_python, device, bin_size=-1)
facebook-github-bot's avatar
facebook-github-bot committed
37

38
    def _test_simple_cpu_naive_instance(self):
facebook-github-bot's avatar
facebook-github-bot committed
39
        device = torch.device("cpu")
40
41
42
43
        self._simple_triangle_raster(rasterize_meshes, device, bin_size=0)
        self._simple_blurry_raster(rasterize_meshes, device, bin_size=0)
        self._test_behind_camera(rasterize_meshes, device, bin_size=0)
        self._test_perspective_correct(rasterize_meshes, device, bin_size=0)
44
        self._test_back_face_culling(rasterize_meshes, device, bin_size=0)
facebook-github-bot's avatar
facebook-github-bot committed
45

46
47
48
49
50
51
52
53
54
55
    def test_simple_cpu_naive(self):
        n_threads = torch.get_num_threads()
        torch.set_num_threads(1)  # single threaded
        self._test_simple_cpu_naive_instance()
        torch.set_num_threads(4)  # even (divisible) number of threads
        self._test_simple_cpu_naive_instance()
        torch.set_num_threads(5)  # odd (nondivisible) number of threads
        self._test_simple_cpu_naive_instance()
        torch.set_num_threads(n_threads)

facebook-github-bot's avatar
facebook-github-bot committed
56
    def test_simple_cuda_naive(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
57
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
58
59
60
61
        self._simple_triangle_raster(rasterize_meshes, device, bin_size=0)
        self._simple_blurry_raster(rasterize_meshes, device, bin_size=0)
        self._test_behind_camera(rasterize_meshes, device, bin_size=0)
        self._test_perspective_correct(rasterize_meshes, device, bin_size=0)
62
        self._test_back_face_culling(rasterize_meshes, device, bin_size=0)
facebook-github-bot's avatar
facebook-github-bot committed
63
64

    def test_simple_cuda_binned(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
65
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
66
67
68
69
        self._simple_triangle_raster(rasterize_meshes, device, bin_size=5)
        self._simple_blurry_raster(rasterize_meshes, device, bin_size=5)
        self._test_behind_camera(rasterize_meshes, device, bin_size=5)
        self._test_perspective_correct(rasterize_meshes, device, bin_size=5)
70
        self._test_back_face_culling(rasterize_meshes, device, bin_size=5)
facebook-github-bot's avatar
facebook-github-bot committed
71
72
73
74
75

    def test_python_vs_cpu_vs_cuda(self):
        torch.manual_seed(231)
        device = torch.device("cpu")
        image_size = 32
76
        blur_radius = 0.1**2
facebook-github-bot's avatar
facebook-github-bot committed
77
78
        faces_per_pixel = 3

Nikhila Ravi's avatar
Nikhila Ravi committed
79
        for d in ["cpu", get_random_cuda_device()]:
facebook-github-bot's avatar
facebook-github-bot committed
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
            device = torch.device(d)
            compare_grads = True
            # Mesh with a single face.
            verts1 = torch.tensor(
                [[0.0, 0.6, 0.1], [-0.7, -0.4, 0.5], [0.7, -0.4, 0.7]],
                dtype=torch.float32,
                requires_grad=True,
                device=device,
            )
            faces1 = torch.tensor([[0, 1, 2]], dtype=torch.int64, device=device)
            meshes1 = Meshes(verts=[verts1], faces=[faces1])
            args1 = (meshes1, image_size, blur_radius, faces_per_pixel)
            verts2 = verts1.detach().clone()
            verts2.requires_grad = True
            meshes2 = Meshes(verts=[verts2], faces=[faces1])
            args2 = (meshes2, image_size, blur_radius, faces_per_pixel)
            self._compare_impls(
                rasterize_meshes_python,
                rasterize_meshes,
                args1,
                args2,
                verts1,
                verts2,
                compare_grads=compare_grads,
            )

            # Mesh with multiple faces.
            # fmt: off
            verts1 = torch.tensor(
                [
                    [ -0.5, 0.0,  0.1],  # noqa: E241, E201
                    [  0.0, 0.6,  0.5],  # noqa: E241, E201
                    [  0.5, 0.0,  0.7],  # noqa: E241, E201
                    [-0.25, 0.0,  0.9],  # noqa: E241, E201
                    [ 0.26, 0.5,  0.8],  # noqa: E241, E201
                    [ 0.76, 0.0,  0.8],  # noqa: E241, E201
                    [-0.41, 0.0,  0.5],  # noqa: E241, E201
                    [ 0.61, 0.6,  0.6],  # noqa: E241, E201
                    [ 0.41, 0.0,  0.5],  # noqa: E241, E201
                    [ -0.2, 0.0, -0.5],  # noqa: E241, E201
                    [  0.3, 0.6, -0.5],  # noqa: E241, E201
                    [  0.4, 0.0, -0.5],  # noqa: E241, E201
                ],
                dtype=torch.float32,
                device=device,
                requires_grad=True
            )
            faces1 = torch.tensor(
                [
                    [ 1, 0,  2],  # noqa: E241, E201
                    [ 4, 3,  5],  # noqa: E241, E201
                    [ 7, 6,  8],  # noqa: E241, E201
                    [10, 9, 11]   # noqa: E241, E201
                ],
                dtype=torch.int64,
                device=device,
            )
            # fmt: on
            meshes = Meshes(verts=[verts1], faces=[faces1])
            args1 = (meshes, image_size, blur_radius, faces_per_pixel)
            verts2 = verts1.clone().detach()
            verts2.requires_grad = True
            meshes2 = Meshes(verts=[verts2], faces=[faces1])
            args2 = (meshes2, image_size, blur_radius, faces_per_pixel)
            self._compare_impls(
                rasterize_meshes_python,
                rasterize_meshes,
                args1,
                args2,
                verts1,
                verts2,
                compare_grads=compare_grads,
            )

            # Icosphere
            meshes = ico_sphere(device=device)
            verts1, faces1 = meshes.get_mesh_verts_faces(0)
            verts1.requires_grad = True
            meshes = Meshes(verts=[verts1], faces=[faces1])
            args1 = (meshes, image_size, blur_radius, faces_per_pixel)
            verts2 = verts1.detach().clone()
            verts2.requires_grad = True
            meshes2 = Meshes(verts=[verts2], faces=[faces1])
            args2 = (meshes2, image_size, blur_radius, faces_per_pixel)
            self._compare_impls(
                rasterize_meshes_python,
                rasterize_meshes,
                args1,
                args2,
                verts1,
                verts2,
                compare_grads=compare_grads,
            )

    def test_cpu_vs_cuda_naive(self):
        """
        Compare naive versions of cuda and cpp
        """

        torch.manual_seed(231)
        image_size = 64
181
        radius = 0.1**2
facebook-github-bot's avatar
facebook-github-bot committed
182
183
184
185
186
187
188
        faces_per_pixel = 3
        device = torch.device("cpu")
        meshes_cpu = ico_sphere(0, device)
        verts1, faces1 = meshes_cpu.get_mesh_verts_faces(0)
        verts1.requires_grad = True
        meshes_cpu = Meshes(verts=[verts1], faces=[faces1])

Nikhila Ravi's avatar
Nikhila Ravi committed
189
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
190
191
192
193
194
        meshes_cuda = ico_sphere(0, device)
        verts2, faces2 = meshes_cuda.get_mesh_verts_faces(0)
        verts2.requires_grad = True
        meshes_cuda = Meshes(verts=[verts2], faces=[faces2])

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
        barycentric_clip = True
        args_cpu = (
            meshes_cpu,
            image_size,
            radius,
            faces_per_pixel,
            None,
            None,
            False,
            barycentric_clip,
            False,
        )
        args_cuda = (
            meshes_cuda,
            image_size,
            radius,
            faces_per_pixel,
            0,
            0,
            False,
            barycentric_clip,
            False,
        )
facebook-github-bot's avatar
facebook-github-bot committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        self._compare_impls(
            rasterize_meshes,
            rasterize_meshes,
            args_cpu,
            args_cuda,
            verts1,
            verts2,
            compare_grads=True,
        )

    def test_coarse_cpu(self):
        return self._test_coarse_rasterize(torch.device("cpu"))

    def test_coarse_cuda(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
232
        return self._test_coarse_rasterize(get_random_cuda_device())
facebook-github-bot's avatar
facebook-github-bot committed
233
234
235
236
237

    def test_cpp_vs_cuda_naive_vs_cuda_binned(self):
        # Make sure that the backward pass runs for all pathways
        image_size = 64  # test is too slow for very large images.
        N = 1
238
        radius = 0.1**2
facebook-github-bot's avatar
facebook-github-bot committed
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
        faces_per_pixel = 3

        grad_zbuf = torch.randn(N, image_size, image_size, faces_per_pixel)
        grad_dist = torch.randn(N, image_size, image_size, faces_per_pixel)
        grad_bary = torch.randn(N, image_size, image_size, faces_per_pixel, 3)

        device = torch.device("cpu")
        meshes = ico_sphere(0, device)
        verts, faces = meshes.get_mesh_verts_faces(0)
        verts.requires_grad = True
        meshes = Meshes(verts=[verts], faces=[faces])

        # Option I: CPU, naive
        args = (meshes, image_size, radius, faces_per_pixel)
        idx1, zbuf1, bary1, dist1 = rasterize_meshes(*args)

        loss = (
            (zbuf1 * grad_zbuf).sum()
            + (dist1 * grad_dist).sum()
            + (bary1 * grad_bary).sum()
        )
        loss.backward()
        idx1 = idx1.data.cpu().clone()
        zbuf1 = zbuf1.data.cpu().clone()
        dist1 = dist1.data.cpu().clone()
        grad1 = verts.grad.data.cpu().clone()

        # Option II: CUDA, naive
Nikhila Ravi's avatar
Nikhila Ravi committed
267
        device = get_random_cuda_device()
facebook-github-bot's avatar
facebook-github-bot committed
268
269
270
271
272
273
274
        meshes = ico_sphere(0, device)
        verts, faces = meshes.get_mesh_verts_faces(0)
        verts.requires_grad = True
        meshes = Meshes(verts=[verts], faces=[faces])

        args = (meshes, image_size, radius, faces_per_pixel, 0, 0)
        idx2, zbuf2, bary2, dist2 = rasterize_meshes(*args)
Nikhila Ravi's avatar
Nikhila Ravi committed
275
276
277
        grad_zbuf = grad_zbuf.to(device)
        grad_dist = grad_dist.to(device)
        grad_bary = grad_bary.to(device)
facebook-github-bot's avatar
facebook-github-bot committed
278
279
280
281
282
283
284
285
286
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
        loss = (
            (zbuf2 * grad_zbuf).sum()
            + (dist2 * grad_dist).sum()
            + (bary2 * grad_bary).sum()
        )
        loss.backward()
        idx2 = idx2.data.cpu().clone()
        zbuf2 = zbuf2.data.cpu().clone()
        dist2 = dist2.data.cpu().clone()
        grad2 = verts.grad.data.cpu().clone()

        # Option III: CUDA, binned
        meshes = ico_sphere(0, device)
        verts, faces = meshes.get_mesh_verts_faces(0)
        verts.requires_grad = True
        meshes = Meshes(verts=[verts], faces=[faces])

        args = (meshes, image_size, radius, faces_per_pixel, 32, 500)
        idx3, zbuf3, bary3, dist3 = rasterize_meshes(*args)

        loss = (
            (zbuf3 * grad_zbuf).sum()
            + (dist3 * grad_dist).sum()
            + (bary3 * grad_bary).sum()
        )
        loss.backward()
        idx3 = idx3.data.cpu().clone()
        zbuf3 = zbuf3.data.cpu().clone()
        dist3 = dist3.data.cpu().clone()
        grad3 = verts.grad.data.cpu().clone()

        # Make sure everything was the same
        self.assertTrue((idx1 == idx2).all().item())
        self.assertTrue((idx1 == idx3).all().item())
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
312
313
314
315
        self.assertClose(zbuf1, zbuf2, atol=1e-6)
        self.assertClose(zbuf1, zbuf3, atol=1e-6)
        self.assertClose(dist1, dist2, atol=1e-6)
        self.assertClose(dist1, dist3, atol=1e-6)
facebook-github-bot's avatar
facebook-github-bot committed
316

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
317
318
319
        self.assertClose(grad1, grad2, rtol=5e-3)  # flaky test
        self.assertClose(grad1, grad3, rtol=5e-3)
        self.assertClose(grad2, grad3, rtol=5e-3)
facebook-github-bot's avatar
facebook-github-bot committed
320
321
322
323

    def test_compare_coarse_cpu_vs_cuda(self):
        torch.manual_seed(231)
        N = 1
324
        image_size = (512, 512)
facebook-github-bot's avatar
facebook-github-bot committed
325
326
327
328
329
330
        blur_radius = 0.0
        bin_size = 32
        max_faces_per_bin = 20

        device = torch.device("cpu")

331
        meshes = ico_sphere(2, device)
facebook-github-bot's avatar
facebook-github-bot committed
332
333
334
335
336
        faces = meshes.faces_packed()
        verts = meshes.verts_packed()
        faces_verts = verts[faces]
        num_faces_per_mesh = meshes.num_faces_per_mesh()
        mesh_to_face_first_idx = meshes.mesh_to_faces_packed_first_idx()
337
338

        bin_faces_cpu = _C._rasterize_meshes_coarse(
facebook-github-bot's avatar
facebook-github-bot committed
339
340
341
342
343
344
345
346
            faces_verts,
            mesh_to_face_first_idx,
            num_faces_per_mesh,
            image_size,
            blur_radius,
            bin_size,
            max_faces_per_bin,
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
347
        device = get_random_cuda_device()
348
        meshes = meshes.clone().to(device)
facebook-github-bot's avatar
facebook-github-bot committed
349
350
351
352
353
354

        faces = meshes.faces_packed()
        verts = meshes.verts_packed()
        faces_verts = verts[faces]
        num_faces_per_mesh = meshes.num_faces_per_mesh()
        mesh_to_face_first_idx = meshes.mesh_to_faces_packed_first_idx()
355
356

        bin_faces_cuda = _C._rasterize_meshes_coarse(
facebook-github-bot's avatar
facebook-github-bot committed
357
358
359
360
361
362
363
364
365
366
367
368
            faces_verts,
            mesh_to_face_first_idx,
            num_faces_per_mesh,
            image_size,
            blur_radius,
            bin_size,
            max_faces_per_bin,
        )

        # Bin faces might not be the same: CUDA version might write them in
        # any order. But if we sort the non-(-1) elements of the CUDA output
        # then they should be the same.
369

facebook-github-bot's avatar
facebook-github-bot committed
370
371
372
373
374
375
376
377
378
        for n in range(N):
            for by in range(bin_faces_cpu.shape[1]):
                for bx in range(bin_faces_cpu.shape[2]):
                    K = (bin_faces_cuda[n, by, bx] != -1).sum().item()
                    idxs_cpu = bin_faces_cpu[n, by, bx].tolist()
                    idxs_cuda = bin_faces_cuda[n, by, bx].tolist()
                    idxs_cuda[:K] = sorted(idxs_cuda[:K])
                    self.assertEqual(idxs_cpu, idxs_cuda)

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
    def test_python_vs_cpp_bary_clip(self):
        torch.manual_seed(232)
        N = 2
        V = 10
        F = 5
        verts1 = torch.randn(N, V, 3, requires_grad=True)
        verts2 = verts1.detach().clone().requires_grad_(True)
        faces = torch.randint(V, size=(N, F, 3))
        meshes1 = Meshes(verts1, faces)
        meshes2 = Meshes(verts2, faces)

        kwargs = {"image_size": 24, "clip_barycentric_coords": True}
        fn1 = functools.partial(rasterize_meshes, meshes1, **kwargs)
        fn2 = functools.partial(rasterize_meshes_python, meshes2, **kwargs)
        args = ()
        self._compare_impls(fn1, fn2, args, args, verts1, verts2, compare_grads=True)

    def test_cpp_vs_cuda_bary_clip(self):
        meshes = ico_sphere(2, device=torch.device("cpu"))
        verts1, faces1 = meshes.get_mesh_verts_faces(0)
        verts1.requires_grad = True
        meshes1 = Meshes(verts=[verts1], faces=[faces1])
        device = get_random_cuda_device()
        verts2 = verts1.detach().to(device).requires_grad_(True)
        faces2 = faces1.detach().clone().to(device)
        meshes2 = Meshes(verts=[verts2], faces=[faces2])

        kwargs = {"image_size": 64, "clip_barycentric_coords": True}
        fn1 = functools.partial(rasterize_meshes, meshes1, **kwargs)
        fn2 = functools.partial(rasterize_meshes, meshes2, bin_size=0, **kwargs)
        args = ()
        self._compare_impls(fn1, fn2, args, args, verts1, verts2, compare_grads=True)

facebook-github-bot's avatar
facebook-github-bot committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
    def test_python_vs_cpp_perspective_correct(self):
        torch.manual_seed(232)
        N = 2
        V = 10
        F = 5
        verts1 = torch.randn(N, V, 3, requires_grad=True)
        verts2 = verts1.detach().clone().requires_grad_(True)
        faces = torch.randint(V, size=(N, F, 3))
        meshes1 = Meshes(verts1, faces)
        meshes2 = Meshes(verts2, faces)

        kwargs = {"image_size": 24, "perspective_correct": True}
        fn1 = functools.partial(rasterize_meshes, meshes1, **kwargs)
        fn2 = functools.partial(rasterize_meshes_python, meshes2, **kwargs)
        args = ()
427
        self._compare_impls(fn1, fn2, args, args, verts1, verts2, compare_grads=True)
facebook-github-bot's avatar
facebook-github-bot committed
428
429
430
431
432
433

    def test_cpp_vs_cuda_perspective_correct(self):
        meshes = ico_sphere(2, device=torch.device("cpu"))
        verts1, faces1 = meshes.get_mesh_verts_faces(0)
        verts1.requires_grad = True
        meshes1 = Meshes(verts=[verts1], faces=[faces1])
Nikhila Ravi's avatar
Nikhila Ravi committed
434
435
436
        device = get_random_cuda_device()
        verts2 = verts1.detach().to(device).requires_grad_(True)
        faces2 = faces1.detach().clone().to(device)
facebook-github-bot's avatar
facebook-github-bot committed
437
438
439
440
441
442
        meshes2 = Meshes(verts=[verts2], faces=[faces2])

        kwargs = {"image_size": 64, "perspective_correct": True}
        fn1 = functools.partial(rasterize_meshes, meshes1, **kwargs)
        fn2 = functools.partial(rasterize_meshes, meshes2, bin_size=0, **kwargs)
        args = ()
443
        self._compare_impls(fn1, fn2, args, args, verts1, verts2, compare_grads=True)
facebook-github-bot's avatar
facebook-github-bot committed
444
445

    def test_cuda_naive_vs_binned_perspective_correct(self):
Nikhila Ravi's avatar
Nikhila Ravi committed
446
447
        device = get_random_cuda_device()
        meshes = ico_sphere(2, device=device)
facebook-github-bot's avatar
facebook-github-bot committed
448
449
450
451
452
453
454
455
456
457
458
        verts1, faces1 = meshes.get_mesh_verts_faces(0)
        verts1.requires_grad = True
        meshes1 = Meshes(verts=[verts1], faces=[faces1])
        verts2 = verts1.detach().clone().requires_grad_(True)
        faces2 = faces1.detach().clone()
        meshes2 = Meshes(verts=[verts2], faces=[faces2])

        kwargs = {"image_size": 64, "perspective_correct": True}
        fn1 = functools.partial(rasterize_meshes, meshes1, bin_size=0, **kwargs)
        fn2 = functools.partial(rasterize_meshes, meshes2, bin_size=8, **kwargs)
        args = ()
459
        self._compare_impls(fn1, fn2, args, args, verts1, verts2, compare_grads=True)
facebook-github-bot's avatar
facebook-github-bot committed
460

461
462
463
464
465
466
467
    def test_bin_size_error(self):
        meshes = ico_sphere(2)
        image_size = 1024
        bin_size = 16
        with self.assertRaisesRegex(ValueError, "bin_size too small"):
            rasterize_meshes(meshes, image_size, 0.0, 2, bin_size)

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    def _test_back_face_culling(self, rasterize_meshes_fn, device, bin_size):
        # Square based pyramid mesh.
        # fmt: off
        verts = torch.tensor([
            [-0.5, 0.0,  0.5],  # noqa: E241 E201 Front right
            [ 0.5, 0.0,  0.5],  # noqa: E241 E201 Front left
            [ 0.5, 0.0,  1.5],  # noqa: E241 E201 Back left
            [-0.5, 0.0,  1.5],  # noqa: E241 E201 Back right
            [ 0.0, 1.0,  1.0]   # noqa: E241 E201 Top point of pyramid
        ], dtype=torch.float32, device=device)

        faces = torch.tensor([
            [2, 1, 0],  # noqa: E241 E201 Square base
            [3, 2, 0],  # noqa: E241 E201 Square base
            [1, 0, 4],  # noqa: E241 E201 Triangle on front
            [2, 4, 3],  # noqa: E241 E201 Triangle on back
            [3, 4, 0],  # noqa: E241 E201 Triangle on left side
            [1, 4, 2]   # noqa: E241 E201 Triangle on right side
        ], dtype=torch.int64, device=device)
        # fmt: on
        mesh = Meshes(verts=[verts], faces=[faces])
        kwargs = {
            "meshes": mesh,
            "image_size": 10,
            "faces_per_pixel": 2,
            "blur_radius": 0.0,
            "perspective_correct": False,
            "cull_backfaces": False,
        }
        if bin_size != -1:
            kwargs["bin_size"] = bin_size

        # fmt: off
        pix_to_face_frontface = torch.tensor([
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1,  2,  2, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1,  2,  2, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1,  2,  2,  2,  2, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1,  2,  2,  2,  2, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]   # noqa: E241 E201
        ], dtype=torch.int64, device=device)
        pix_to_face_backface = torch.tensor([
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1,  3,  3, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1,  3,  3, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1,  3,  3,  3,  3, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1,  3,  3,  3,  3, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241 E201
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]   # noqa: E241 E201
        ], dtype=torch.int64, device=device)
        # fmt: on

Nikhila Ravi's avatar
Nikhila Ravi committed
527
        pix_to_face_padded = -(torch.ones_like(pix_to_face_frontface))
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
        # Run with and without culling
        # Without culling, for k=0, the front face (i.e. face 2) is
        # rasterized and for k=1, the back face (i.e. face 3) is
        # rasterized.
        idx_f, zbuf_f, bary_f, dists_f = rasterize_meshes_fn(**kwargs)
        self.assertTrue(torch.all(idx_f[..., 0].squeeze() == pix_to_face_frontface))
        self.assertTrue(torch.all(idx_f[..., 1].squeeze() == pix_to_face_backface))

        # With culling, for k=0, the front face (i.e. face 2) is
        # rasterized and for k=1, there are no faces rasterized
        kwargs["cull_backfaces"] = True
        idx_t, zbuf_t, bary_t, dists_t = rasterize_meshes_fn(**kwargs)
        self.assertTrue(torch.all(idx_t[..., 0].squeeze() == pix_to_face_frontface))
        self.assertTrue(torch.all(idx_t[..., 1].squeeze() == pix_to_face_padded))

facebook-github-bot's avatar
facebook-github-bot committed
543
544
545
546
547
548
549
550
551
552
553
554
555
    def _compare_impls(
        self,
        fn1,
        fn2,
        args1,
        args2,
        grad_var1=None,
        grad_var2=None,
        compare_grads=False,
    ):
        idx1, zbuf1, bary1, dist1 = fn1(*args1)
        idx2, zbuf2, bary2, dist2 = fn2(*args2)
        self.assertTrue((idx1.cpu() == idx2.cpu()).all().item())
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
556
557
558
        self.assertClose(zbuf1.cpu(), zbuf2.cpu(), rtol=1e-4)
        self.assertClose(dist1.cpu(), dist2.cpu(), rtol=6e-3)
        self.assertClose(bary1.cpu(), bary2.cpu(), rtol=1e-3)
facebook-github-bot's avatar
facebook-github-bot committed
559
560
561
562
563
564
565
566
567
568
569
570
571
        if not compare_grads:
            return

        # Compare gradients.
        torch.manual_seed(231)
        grad_zbuf = torch.randn_like(zbuf1)
        grad_dist = torch.randn_like(dist1)
        grad_bary = torch.randn_like(bary1)
        loss1 = (
            (dist1 * grad_dist).sum()
            + (zbuf1 * grad_zbuf).sum()
            + (bary1 * grad_bary).sum()
        )
572
573
574
575

        # avoid gradient error if rasterize_meshes_python() culls all triangles
        loss1 += grad_var1.sum() * 0.0

facebook-github-bot's avatar
facebook-github-bot committed
576
577
578
579
580
581
582
583
584
585
586
        loss1.backward()
        grad_verts1 = grad_var1.grad.data.clone().cpu()

        grad_zbuf = grad_zbuf.to(zbuf2)
        grad_dist = grad_dist.to(dist2)
        grad_bary = grad_bary.to(bary2)
        loss2 = (
            (dist2 * grad_dist).sum()
            + (zbuf2 * grad_zbuf).sum()
            + (bary2 * grad_bary).sum()
        )
587
588
589
590

        # avoid gradient error if rasterize_meshes_python() culls all triangles
        loss2 += grad_var2.sum() * 0.0

facebook-github-bot's avatar
facebook-github-bot committed
591
592
593
        grad_var1.grad.data.zero_()
        loss2.backward()
        grad_verts2 = grad_var2.grad.data.clone().cpu()
594
        self.assertClose(grad_verts1, grad_verts2, rtol=2e-3)
facebook-github-bot's avatar
facebook-github-bot committed
595

596
    def _test_perspective_correct(self, rasterize_meshes_fn, device, bin_size=None):
facebook-github-bot's avatar
facebook-github-bot committed
597
598
        # fmt: off
        verts = torch.tensor([
Nikhila Ravi's avatar
Nikhila Ravi committed
599
600
601
            [-0.4, -0.4, 10],  # noqa: E241, E201
            [ 0.4, -0.4, 10],  # noqa: E241, E201
            [ 0.0,  0.4, 20],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
        ], dtype=torch.float32, device=device)
        # fmt: on
        faces = torch.tensor([[0, 1, 2]], device=device)
        meshes = Meshes(verts=[verts], faces=[faces])
        kwargs = {
            "meshes": meshes,
            "image_size": 11,
            "faces_per_pixel": 1,
            "blur_radius": 0.2,
            "perspective_correct": False,
        }
        if bin_size != -1:
            kwargs["bin_size"] = bin_size

        # Run with and without perspective correction
        idx_f, zbuf_f, bary_f, dists_f = rasterize_meshes_fn(**kwargs)
618

facebook-github-bot's avatar
facebook-github-bot committed
619
620
621
        kwargs["perspective_correct"] = True
        idx_t, zbuf_t, bary_t, dists_t = rasterize_meshes_fn(**kwargs)

622
        # Expected output tensors in the format with axes +X left, +Y up, +Z in
facebook-github-bot's avatar
facebook-github-bot committed
623
624
625
626
        # idx and dists should be the same with or without perspecitve correction
        # fmt: off
        idx_expected = torch.tensor([
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
627
628
629
630
            [-1, -1, -1, -1,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
            [-1, -1, -1,  0,  0,  0,  0,  0, -1, -1, -1],  # noqa: E241, E201
            [-1, -1, -1,  0,  0,  0,  0,  0, -1, -1, -1],  # noqa: E241, E201
            [-1, -1,  0,  0,  0,  0,  0,  0,  0, -1, -1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
631
632
633
634
635
            [-1, -1,  0,  0,  0,  0,  0,  0,  0, -1, -1],  # noqa: E241, E201
            [-1,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1],  # noqa: E241, E201
            [-1,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1],  # noqa: E241, E201
            [-1,  0,  0,  0,  0,  0,  0,  0,  0,  0, -1],  # noqa: E241, E201
            [-1, -1,  0,  0,  0,  0,  0,  0,  0, -1, -1],  # noqa: E241, E201
636
            [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]   # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
637
        ], dtype=torch.int64, device=device).view(1, 11, 11, 1)
638

facebook-github-bot's avatar
facebook-github-bot committed
639
        dists_expected = torch.tensor([
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
640
641
642
643
644
645
646
647
648
649
650
            [-1.,     -1.,     -1.,     -1.,    -1.,     -1.,     -1.,     -1.,     -1.,   -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1.,     -1., 0.1402,  0.1071,  0.1402,     -1.,     -1.,   -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1., -    1., 0.1523,  0.0542,  0.0212,  0.0542,  0.1523,     -1.,   -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1., 0.0955,  0.0214, -0.0003,  0.0214,  0.0955,     -1.,   -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1., 0.1523,  0.0518,  0.0042, -0.0095,  0.0042,  0.0518, 0.1523,    -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1., 0.0955,  0.0214, -0.0003,  -0.032, -0.0003,  0.0214, 0.0955,    -1., -1.],  # noqa: E241, E201, B950
            [-1., 0.1523,  0.0518,  0.0042, -0.0095, -0.0476, -0.0095,  0.0042, 0.0518, 0.1523, -1.],  # noqa: E241, E201, B950
            [-1., 0.1084,  0.0225, -0.0003, -0.0013, -0.0013, -0.0013, -0.0003, 0.0225, 0.1084, -1.],  # noqa: E241, E201, B950
            [-1., 0.1283,  0.0423,  0.0212,  0.0212,  0.0212,  0.0212,  0.0212, 0.0423, 0.1283, -1.],  # noqa: E241, E201, B950
            [-1.,     -1., 0.1283,  0.1071,  0.1071,  0.1071,  0.1071,  0.1071, 0.1283,    -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,    -1.,   -1., -1.]   # noqa: E241, E201, B950
facebook-github-bot's avatar
facebook-github-bot committed
651
652
653
654
        ], dtype=torch.float32, device=device).view(1, 11, 11, 1)

        # zbuf and barycentric will be different with perspective correction
        zbuf_f_expected = torch.tensor([
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
655
656
657
658
659
660
661
662
663
664
665
            [-1.,      -1.,     -1.,     -1.,     -1.,     -1.,      -1.,    -1.,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,     -1.,     -1., 24.0909, 24.0909, 24.0909,     -1.,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,     -1., 21.8182, 21.8182, 21.8182, 21.8182, 21.8182,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,     -1., 19.5455, 19.5455, 19.5455, 19.5455, 19.5455,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1., 17.2727, 17.2727, 17.2727, 17.2727, 17.2727, 17.2727, 17.2727,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,      15.,     15.,     15.,     15.,     15.,    15.,     15.,     -1., -1.],  # noqa: E241, E201, B950
            [-1., 12.7273,  12.7273, 12.7273, 12.7273, 12.7273, 12.7273, 12.7273, 12.7273, 12.7273, -1.],  # noqa: E241, E201, B950
            [-1., 10.4545,  10.4545, 10.4545, 10.4545, 10.4545, 10.4545, 10.4545, 10.4545, 10.4545, -1.],  # noqa: E241, E201, B950
            [-1.,  8.1818,   8.1818,  8.1818,  8.1818,  8.1818,  8.1818,  8.1818,  8.1818,  8.1818, -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,  5.9091,  5.9091,  5.9091,  5.9091,  5.9091,  5.9091,  5.9091,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,       -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,    -1., -1.],  # noqa: E241, E201, B950
facebook-github-bot's avatar
facebook-github-bot committed
666
        ], dtype=torch.float32, device=device).view(1, 11, 11, 1)
667

facebook-github-bot's avatar
facebook-github-bot committed
668
        zbuf_t_expected = torch.tensor([
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
669
670
671
672
673
674
675
676
677
678
679
            [-1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1.,     -1., 33.8461, 33.8462, 33.8462,     -1.,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1., 24.4444, 24.4444, 24.4444, 24.4444, 24.4444,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1.,     -1., 19.1304, 19.1304, 19.1304, 19.1304, 19.1304,     -1.,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1., 15.7143, 15.7143, 15.7143, 15.7143, 15.7143, 15.7143, 15.7143,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,     -1., 13.3333, 13.3333, 13.3333, 13.3333, 13.3333, 13.3333, 13.3333,     -1., -1.],  # noqa: E241, E201, B950
            [-1., 11.5789, 11.5789, 11.5789, 11.5789, 11.5789, 11.5789, 11.5789, 11.5789, 11.5789, -1.],  # noqa: E241, E201, B950
            [-1., 10.2326, 10.2326, 10.2326, 10.2326, 10.2326, 10.2326, 10.2326, 10.2326, 10.2326, -1.],  # noqa: E241, E201, B950
            [-1.,  9.1667,  9.1667,  9.1667,  9.1667,  9.1667,  9.1667,  9.1667,  9.1667,  9.1667, -1.],  # noqa: E241, E201, B950
            [-1.,      -1., 8.3019,  8.3019,  8.3019,  8.3019,  8.3019,  8.3019,  8.3019,     -1., -1.],  # noqa: E241, E201, B950
            [-1.,      -1.,     -1.,    -1.,     -1.,     -1.,     -1.,     -1.,     -1.,     -1., -1.]   # noqa: E241, E201, B950
facebook-github-bot's avatar
facebook-github-bot committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        ], dtype=torch.float32, device=device).view(1, 11, 11, 1)
        # fmt: on

        self.assertTrue(torch.all(idx_f == idx_expected).item())
        self.assertTrue(torch.all(idx_t == idx_expected).item())
        dists_t_max_diff = (dists_t - dists_expected).abs().max().item()
        dists_f_max_diff = (dists_f - dists_expected).abs().max().item()
        self.assertLess(dists_t_max_diff, 1e-4)
        self.assertLess(dists_f_max_diff, 1e-4)
        zbuf_f_max_diff = (zbuf_f - zbuf_f_expected).abs().max().item()
        zbuf_t_max_diff = (zbuf_t - zbuf_t_expected).abs().max().item()
        self.assertLess(zbuf_f_max_diff, 1e-4)
        self.assertLess(zbuf_t_max_diff, 1e-4)

        # Check barycentrics by using them to re-compute zbuf
        z0 = verts[0, 2]
        z1 = verts[1, 2]
        z2 = verts[2, 2]
        w0_f, w1_f, w2_f = bary_f.unbind(dim=4)
        w0_t, w1_t, w2_t = bary_t.unbind(dim=4)
        zbuf_f_bary = w0_f * z0 + w1_f * z1 + w2_f * z2
        zbuf_t_bary = w0_t * z0 + w1_t * z1 + w2_t * z2
        mask = idx_expected != -1
703
704
        zbuf_f_bary_diff = (zbuf_f_bary[mask] - zbuf_f_expected[mask]).abs().max()
        zbuf_t_bary_diff = (zbuf_t_bary[mask] - zbuf_t_expected[mask]).abs().max()
facebook-github-bot's avatar
facebook-github-bot committed
705
706
707
        self.assertLess(zbuf_f_bary_diff, 1e-4)
        self.assertLess(zbuf_t_bary_diff, 1e-4)

708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
    def _test_barycentric_clipping(self, rasterize_meshes_fn, device, bin_size=None):
        # fmt: off
        verts = torch.tensor([
            [-0.4, -0.4, 10],  # noqa: E241, E201
            [ 0.4, -0.4, 10],  # noqa: E241, E201
            [ 0.0,  0.4, 20],  # noqa: E241, E201
        ], dtype=torch.float32, device=device)
        # fmt: on
        faces = torch.tensor([[0, 1, 2]], device=device)
        meshes = Meshes(verts=[verts], faces=[faces])
        kwargs = {
            "meshes": meshes,
            "image_size": 5,
            "faces_per_pixel": 1,
            "blur_radius": 0.2,
            "perspective_correct": False,
            "clip_barycentric_coords": False,  # Initially set this to false
        }
        if bin_size != -1:
            kwargs["bin_size"] = bin_size

        # Run with and without perspective correction
        idx_f, zbuf_f, bary_f, dists_f = rasterize_meshes_fn(**kwargs)

        # fmt: off
        expected_bary = torch.tensor([
            [
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [-0.2500, -0.2500,  1.5000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000]   # noqa: E241, E201
            ],
            [
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [-0.5000,  0.5000,  1.0000],  # noqa: E241, E201
                [-0.0000, -0.0000,  1.0000],  # noqa: E241, E201
                [ 0.5000, -0.5000,  1.0000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000]   # noqa: E241, E201
            ],
            [
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [-0.2500,  0.7500,  0.5000],  # noqa: E241, E201
                [ 0.2500,  0.2500,  0.5000],  # noqa: E241, E201
                [ 0.7500, -0.2500,  0.5000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000]   # noqa: E241, E201
            ],
            [
                [-0.5000,  1.5000, -0.0000],  # noqa: E241, E201
                [-0.0000,  1.0000, -0.0000],  # noqa: E241, E201
                [ 0.5000,  0.5000, -0.0000],  # noqa: E241, E201
                [ 1.0000, -0.0000, -0.0000],  # noqa: E241, E201
                [ 1.5000, -0.5000,  0.0000]   # noqa: E241, E201
            ],
            [
                [-1.0000, -1.0000, -1.0000],  # noqa: E241, E201
                [ 0.2500,  1.2500, -0.5000],  # noqa: E241, E201
                [ 0.7500,  0.7500, -0.5000],  # noqa: E241, E201
                [ 1.2500,  0.2500, -0.5000],  # noqa: E241, E201
                [-1.0000, -1.0000, -1.0000]   # noqa: E241, E201
            ]
        ], dtype=torch.float32, device=device).view(1, 5, 5, 1, 3)
        # fmt: on

        self.assertClose(expected_bary, bary_f, atol=1e-4)

        # calculate the expected clipped barycentrics and zbuf
        expected_bary_clipped = _clip_barycentric_coordinates(expected_bary)
        expected_z_clipped = _interpolate_zbuf(idx_f, expected_bary_clipped, meshes)

        kwargs["clip_barycentric_coords"] = True
        idx_t, zbuf_t, bary_t, dists_t = rasterize_meshes_fn(**kwargs)

        self.assertClose(expected_bary_clipped, bary_t, atol=1e-4)
        self.assertClose(expected_z_clipped, zbuf_t, atol=1e-4)

facebook-github-bot's avatar
facebook-github-bot committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    def _test_behind_camera(self, rasterize_meshes_fn, device, bin_size=None):
        """
        All verts are behind the camera so nothing should get rasterized.
        """
        N = 1
        # fmt: off
        verts = torch.tensor(
            [
                [ -0.5, 0.0, -0.1],  # noqa: E241, E201
                [  0.0, 0.6, -0.1],  # noqa: E241, E201
                [  0.5, 0.0, -0.1],  # noqa: E241, E201
                [-0.25, 0.0, -0.9],  # noqa: E241, E201
                [ 0.25, 0.5, -0.9],  # noqa: E241, E201
                [ 0.75, 0.0, -0.9],  # noqa: E241, E201
                [ -0.4, 0.0, -0.5],  # noqa: E241, E201
                [  0.6, 0.6, -0.5],  # noqa: E241, E201
                [  0.8, 0.0, -0.5],  # noqa: E241, E201
                [ -0.2, 0.0, -0.5],  # noqa: E241, E201
                [  0.3, 0.6, -0.5],  # noqa: E241, E201
                [  0.4, 0.0, -0.5],  # noqa: E241, E201
            ],
            dtype=torch.float32,
            device=device,
        )
        # fmt: on
        faces = torch.tensor(
            [[1, 0, 2], [4, 3, 5], [7, 6, 8], [10, 9, 11]],
            dtype=torch.int64,
            device=device,
        )
        meshes = Meshes(verts=[verts], faces=[faces])
        image_size = 16
        faces_per_pixel = 1
        radius = 0.2
        idx_expected = torch.full(
            (N, image_size, image_size, faces_per_pixel),
            fill_value=-1,
            dtype=torch.int64,
            device=device,
        )
        bary_expected = torch.full(
            (N, image_size, image_size, faces_per_pixel, 3),
            fill_value=-1,
            dtype=torch.float32,
            device=device,
        )
        zbuf_expected = torch.full(
            (N, image_size, image_size, faces_per_pixel),
            fill_value=-1,
            dtype=torch.float32,
            device=device,
        )
        dists_expected = zbuf_expected.clone()
        if bin_size == -1:
            # naive python version with no binning
            idx, zbuf, bary, dists = rasterize_meshes_fn(
                meshes, image_size, radius, faces_per_pixel
            )
        else:
            idx, zbuf, bary, dists = rasterize_meshes_fn(
                meshes, image_size, radius, faces_per_pixel, bin_size
            )
        idx_same = (idx == idx_expected).all().item()
        zbuf_same = (zbuf == zbuf_expected).all().item()
        self.assertTrue(idx_same)
        self.assertTrue(zbuf_same)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
850
851
        self.assertClose(bary, bary_expected)
        self.assertClose(dists, dists_expected)
facebook-github-bot's avatar
facebook-github-bot committed
852
853
854
855

    def _simple_triangle_raster(self, raster_fn, device, bin_size=None):
        image_size = 10

856
857
        # Mesh with a single non-symmetrical face - this will help
        # check that the XY directions are correctly oriented.
facebook-github-bot's avatar
facebook-github-bot committed
858
        verts0 = torch.tensor(
859
            [[-0.3, -0.4, 0.1], [0.0, 0.6, 0.1], [0.9, -0.4, 0.1]],
facebook-github-bot's avatar
facebook-github-bot committed
860
861
862
863
864
865
866
867
868
            dtype=torch.float32,
            device=device,
        )
        faces0 = torch.tensor([[1, 0, 2]], dtype=torch.int64, device=device)

        # Mesh with two overlapping faces.
        # fmt: off
        verts1 = torch.tensor(
            [
869
                [-0.9, -0.2, 0.1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
870
871
872
873
874
875
876
877
878
879
880
881
882
883
                [ 0.0,  0.6, 0.1],  # noqa: E241, E201
                [ 0.7, -0.4, 0.1],  # noqa: E241, E201
                [-0.7,  0.4, 0.5],  # noqa: E241, E201
                [ 0.0, -0.6, 0.5],  # noqa: E241, E201
                [ 0.7,  0.4, 0.5],  # noqa: E241, E201
            ],
            dtype=torch.float32,
            device=device,
        )
        # fmt on
        faces1 = torch.tensor(
            [[1, 0, 2], [3, 4, 5]], dtype=torch.int64, device=device
        )

884
885
        # Expected output tensors in the format with axes +X left, +Y up, +Z in
        # k = 0, closest point.
facebook-github-bot's avatar
facebook-github-bot committed
886
887
888
889
890
891
892
        # fmt off
        expected_p2face_k0 = torch.tensor(
            [
                [
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
893
894
895
896
                    [-1, -1, -1, -1,  0, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1,  0,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  0,  0,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
897
898
899
900
901
902
903
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                ],
                [
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
904
905
906
907
908
                    [-1, -1, -1, -1, -1,  1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1,  2,  2,  1,  1,  1,  2, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1,  1,  1,  1,  1,  1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1,  1,  1,  1,  1,  1,  1, -1],  # noqa: E241, E201
                    [-1, -1,  1,  1,  1,  2, -1, -1, -1, -1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
909
910
911
912
913
914
915
916
917
918
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                ],
            ],
            dtype=torch.int64,
            device=device,
        )
        expected_zbuf_k0 = torch.tensor(
            [
Nikhila Ravi's avatar
Nikhila Ravi committed
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
                [
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1, 0.1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1, 0.1, 0.1, 0.1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1, 0.1, 0.1, 0.1, 0.1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1, 0.1, 0.1, 0.1, 0.1, 0.1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1],  # noqa: E241, E201
                    [-1,  -1,  -1,  -1,  -1,  -1, -1, -1, -1, -1]   # noqa: E241, E201
                ],
                [
                    [-1, -1,  -1,  -1,  -1, -1,   -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1,  -1,  -1, -1,   -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1,  -1,  -1, 0.1,  -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1, 0.5, 0.5, 0.1, 0.1, 0.1, 0.5,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1, 0.1, 0.1, 0.1, 0.1, 0.1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -1],  # noqa: E241, E201
                    [-1, -1, 0.1, 0.1, 0.1, 0.5,  -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, -1],  # noqa: E241, E201
                    [-1, -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, -1]   # noqa: E241, E201
                ]
facebook-github-bot's avatar
facebook-github-bot committed
943
944
945
946
947
948
949
950
951
            ],
            device=device,
        )
        # fmt: on

        meshes = Meshes(verts=[verts0, verts1], faces=[faces0, faces1])

        # k = 1, second closest point.
        expected_p2face_k1 = expected_p2face_k0.clone()
952
        expected_p2face_k1[0, :] = torch.ones_like(expected_p2face_k1[0, :]) * -1
facebook-github-bot's avatar
facebook-github-bot committed
953
954
955

        # fmt: off
        expected_p2face_k1[1, :] = torch.tensor(
Nikhila Ravi's avatar
Nikhila Ravi committed
956
957
958
959
960
961
962
963
964
965
966
967
            [
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1,  2,  2,  2, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1,  2,  2,  2,  2, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1,  2,  2,  2,  2, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1,  2, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]   # noqa: E241, E201
            ],
facebook-github-bot's avatar
facebook-github-bot committed
968
969
970
971
972
973
974
            dtype=torch.int64,
            device=device,
        )
        expected_zbuf_k1 = expected_zbuf_k0.clone()
        expected_zbuf_k1[0, :] = torch.ones_like(expected_zbuf_k1[0, :]) * -1
        expected_zbuf_k1[1, :] = torch.tensor(
            [
975
976
977
978
979
980
981
982
983
984
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  0.5, 0.5,  0.5, -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  0.5,  0.5, 0.5,  0.5, -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  0.5,  0.5, 0.5,  0.5, -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  0.5,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1., -1., -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.]   # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
985
986
987
988
989
            ],
            dtype=torch.float32,
            device=device,
        )
        # fmt: on
990
991
992
993

        #  Coordinate conventions +Y up, +Z in, +X left
        if bin_size == -1:
            # simple python, no bin_size
994
            p2face, zbuf, bary, pix_dists = raster_fn(meshes, image_size, 0.0, 2)
995
996
997
998
999
        else:
            p2face, zbuf, bary, pix_dists = raster_fn(
                meshes, image_size, 0.0, 2, bin_size
            )

Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
1000
1001
1002
1003
        self.assertClose(p2face[..., 0], expected_p2face_k0)
        self.assertClose(zbuf[..., 0], expected_zbuf_k0)
        self.assertClose(p2face[..., 1], expected_p2face_k1)
        self.assertClose(zbuf[..., 1], expected_zbuf_k1)
facebook-github-bot's avatar
facebook-github-bot committed
1004
1005
1006
1007
1008
1009
1010

    def _simple_blurry_raster(self, raster_fn, device, bin_size=None):
        """
        Check that pix_to_face, dist and zbuf values are invariant to the
        ordering of faces.
        """
        image_size = 10
1011
        blur_radius = 0.12**2
facebook-github-bot's avatar
facebook-github-bot committed
1012
1013
1014
1015
1016
        faces_per_pixel = 1

        # fmt: off
        verts = torch.tensor(
            [
1017
                [ -0.3, 0.0,  0.1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
1018
                [  0.0, 0.6,  0.1],  # noqa: E241, E201
1019
                [  0.8, 0.0,  0.1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
                [-0.25, 0.0,  0.9],  # noqa: E241, E201
                [0.25,  0.5,  0.9],  # noqa: E241, E201
                [0.75,  0.0,  0.9],  # noqa: E241, E201
                [-0.4,  0.0,  0.5],  # noqa: E241, E201
                [ 0.6,  0.6,  0.5],  # noqa: E241, E201
                [ 0.8,  0.0,  0.5],  # noqa: E241, E201
                [-0.2,  0.0, -0.5],  # noqa: E241, E201  face behind the camera
                [ 0.3,  0.6, -0.5],  # noqa: E241, E201
                [ 0.4,  0.0, -0.5],  # noqa: E241, E201
            ],
            dtype=torch.float32,
            device=device,
        )
1033
1034
        # Face with index 0 is non symmetric about the X and Y axis to
        # test that the positive Y and X directions are correct in the output.
facebook-github-bot's avatar
facebook-github-bot committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
        faces_packed = torch.tensor(
            [[1, 0, 2], [4, 3, 5], [7, 6, 8], [10, 9, 11]],
            dtype=torch.int64,
            device=device,
        )
        expected_p2f = torch.tensor(
            [
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
1044
1045
1046
1047
                [-1,  2,  2,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
                [-1,  2,  0,  0,  0,  0, -1, -1, -1, -1],  # noqa: E241, E201
                [-1,  0,  0,  0,  0,  0,  0, -1, -1, -1],  # noqa: E241, E201
                [-1,  0,  0,  0,  0,  0,  0, -1, -1, -1],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
                [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],  # noqa: E241, E201
            ],
            dtype=torch.int64,
            device=device,
        )
        expected_zbuf = torch.tensor(
            [
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,  0.5,  0.5,  0.1,  0.1,  0.1,  -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,  0.5,  0.1,  0.1,  0.1,  0.1,  -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1, -1., -1., -1.],  # noqa: E241, E201
                [-1.,  0.1,  0.1,  0.1,  0.1,  0.1,  0.1, -1., -1., -1.],  # noqa: E241, E201
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.],  # noqa: E241, E201
                [-1.,   -1.,  -1.,  -1.,  -1.,  -1., -1., -1., -1., -1.]   # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
            ],
            dtype=torch.float32,
            device=device,
        )
        # fmt: on

        for i, order in enumerate([[0, 1, 2], [1, 2, 0], [2, 0, 1]]):
            faces = faces_packed[order]  # rearrange order of faces.
            mesh = Meshes(verts=[verts], faces=[faces])
            if bin_size == -1:
1078
                # simple python, no bin size arg
facebook-github-bot's avatar
facebook-github-bot committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
                pix_to_face, zbuf, bary_coords, dists = raster_fn(
                    mesh, image_size, blur_radius, faces_per_pixel
                )
            else:
                pix_to_face, zbuf, bary_coords, dists = raster_fn(
                    mesh, image_size, blur_radius, faces_per_pixel, bin_size
                )
            if i == 0:
                expected_dists = dists
            p2f = expected_p2f.clone()
            p2f[expected_p2f == 0] = order.index(0)
            p2f[expected_p2f == 1] = order.index(1)
            p2f[expected_p2f == 2] = order.index(2)
Jeremy Reizenstein's avatar
Jeremy Reizenstein committed
1092
1093
1094
            self.assertClose(pix_to_face.squeeze(), p2f)
            self.assertClose(zbuf.squeeze(), expected_zbuf, rtol=1e-5)
            self.assertClose(dists, expected_dists)
facebook-github-bot's avatar
facebook-github-bot committed
1095
1096

    def _test_coarse_rasterize(self, device):
1097
        image_size = (16, 16)
1098
1099
1100
        # No blurring. This test checks that the XY directions are
        # correctly oriented.
        blur_radius = 0.0
facebook-github-bot's avatar
facebook-github-bot committed
1101
1102
1103
1104
1105
1106
        bin_size = 8
        max_faces_per_bin = 3

        # fmt: off
        verts = torch.tensor(
            [
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
                [-0.5,   0.1,  0.1],  # noqa: E241, E201
                [-0.3,   0.6,  0.1],  # noqa: E241, E201
                [-0.1,   0.1,  0.1],  # noqa: E241, E201
                [-0.3,  -0.1,  0.4],  # noqa: E241, E201
                [ 0.3,   0.5,  0.4],  # noqa: E241, E201
                [0.75,  -0.1,  0.4],  # noqa: E241, E201
                [ 0.2,  -0.3,  0.9],  # noqa: E241, E201
                [ 0.3,  -0.7,  0.9],  # noqa: E241, E201
                [ 0.6,  -0.3,  0.9],  # noqa: E241, E201
                [-0.4,   0.0, -1.5],  # noqa: E241, E201
                [ 0.6,   0.6, -1.5],  # noqa: E241, E201
                [ 0.8,   0.0, -1.5],  # noqa: E241, E201
facebook-github-bot's avatar
facebook-github-bot committed
1119
1120
1121
            ],
            device=device,
        )
1122
1123
        # Expected faces using axes convention +Y down, + X right, +Z in
        # Non symmetrical triangles i.e face 0 and 3 are in one bin only
facebook-github-bot's avatar
facebook-github-bot committed
1124
1125
        faces = torch.tensor(
            [
1126
1127
1128
                [ 1, 0,  2],  # noqa: E241, E201  bin 01 only
                [ 4, 3,  5],  # noqa: E241, E201  all bins
                [ 7, 6,  8],  # noqa: E241, E201  bin 10 only
facebook-github-bot's avatar
facebook-github-bot committed
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
                [10, 9, 11],  # noqa: E241, E201  negative z, should not appear.
            ],
            dtype=torch.int64,
            device=device,
        )
        # fmt: on

        meshes = Meshes(verts=[verts], faces=[faces])
        faces_verts = verts[faces]
        num_faces_per_mesh = meshes.num_faces_per_mesh()
        mesh_to_face_first_idx = meshes.mesh_to_faces_packed_first_idx()

1141
        # Expected faces using axes convention +Y down, + X right, + Z in
facebook-github-bot's avatar
facebook-github-bot committed
1142
        bin_faces_expected = (
1143
            torch.ones((1, 2, 2, max_faces_per_bin), dtype=torch.int32, device=device)
facebook-github-bot's avatar
facebook-github-bot committed
1144
1145
            * -1
        )
1146
        bin_faces_expected[0, 1, 1, 0] = torch.tensor([1])
Nikhila Ravi's avatar
Nikhila Ravi committed
1147
1148
1149
        bin_faces_expected[0, 0, 1, 0:2] = torch.tensor([1, 2])
        bin_faces_expected[0, 1, 0, 0:2] = torch.tensor([0, 1])
        bin_faces_expected[0, 0, 0, 0] = torch.tensor([1])
1150
1151

        # +Y up, +X left, +Z in
facebook-github-bot's avatar
facebook-github-bot committed
1152
1153
1154
1155
1156
1157
1158
1159
1160
        bin_faces = _C._rasterize_meshes_coarse(
            faces_verts,
            mesh_to_face_first_idx,
            num_faces_per_mesh,
            image_size,
            blur_radius,
            bin_size,
            max_faces_per_bin,
        )
Nikhila Ravi's avatar
Nikhila Ravi committed
1161

1162
        bin_faces_same = (bin_faces.squeeze() == bin_faces_expected).all()
facebook-github-bot's avatar
facebook-github-bot committed
1163
1164
        self.assertTrue(bin_faces_same.item() == 1)

1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
    def test_order_of_ties(self):
        # Tied faces are rasterized in index order
        # We rasterize a mesh with many faces.
        device = torch.device("cuda:0")
        verts = -5 * torch.eye(3, dtype=torch.float32, device=device)[None]
        faces = torch.arange(3, device=device, dtype=torch.int64).expand(1, 100, 3)
        mesh = Meshes(verts=verts, faces=faces)

        R, T = look_at_view_transform(2.7, 0.0, 0.0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T)

        raster_settings = RasterizationSettings(
            image_size=28, faces_per_pixel=100, bin_size=0
        )
        rasterizer = MeshRasterizer(raster_settings=raster_settings)

        out = rasterizer(mesh, cameras=cameras)
        self.assertClose(
            out.pix_to_face[0, 14:, :14],
            torch.arange(100, device=device).expand(14, 14, 100),
        )

facebook-github-bot's avatar
facebook-github-bot committed
1187
1188
    @staticmethod
    def rasterize_meshes_python_with_init(
Nikhila Ravi's avatar
Nikhila Ravi committed
1189
1190
1191
1192
1193
        num_meshes: int,
        ico_level: int,
        image_size: int,
        blur_radius: float,
        faces_per_pixel: int,
facebook-github-bot's avatar
facebook-github-bot committed
1194
1195
1196
1197
1198
1199
    ):
        device = torch.device("cpu")
        meshes = ico_sphere(ico_level, device)
        meshes_batch = meshes.extend(num_meshes)

        def rasterize():
Nikhila Ravi's avatar
Nikhila Ravi committed
1200
1201
1202
            rasterize_meshes_python(
                meshes_batch, image_size, blur_radius, faces_per_pixel
            )
facebook-github-bot's avatar
facebook-github-bot committed
1203
1204
1205
1206
1207

        return rasterize

    @staticmethod
    def rasterize_meshes_cpu_with_init(
Nikhila Ravi's avatar
Nikhila Ravi committed
1208
1209
1210
1211
1212
        num_meshes: int,
        ico_level: int,
        image_size: int,
        blur_radius: float,
        faces_per_pixel: int,
facebook-github-bot's avatar
facebook-github-bot committed
1213
1214
1215
1216
1217
    ):
        meshes = ico_sphere(ico_level, torch.device("cpu"))
        meshes_batch = meshes.extend(num_meshes)

        def rasterize():
Nikhila Ravi's avatar
Nikhila Ravi committed
1218
1219
1220
1221
1222
1223
1224
            rasterize_meshes(
                meshes_batch,
                image_size,
                blur_radius,
                faces_per_pixel=faces_per_pixel,
                bin_size=0,
            )
facebook-github-bot's avatar
facebook-github-bot committed
1225
1226
1227
1228
1229
1230
1231
1232
1233

        return rasterize

    @staticmethod
    def rasterize_meshes_cuda_with_init(
        num_meshes: int,
        ico_level: int,
        image_size: int,
        blur_radius: float,
Nikhila Ravi's avatar
Nikhila Ravi committed
1234
        faces_per_pixel: int,
facebook-github-bot's avatar
facebook-github-bot committed
1235
    ):
Nikhila Ravi's avatar
Nikhila Ravi committed
1236
1237
        device = get_random_cuda_device()
        meshes = ico_sphere(ico_level, device)
facebook-github-bot's avatar
facebook-github-bot committed
1238
        meshes_batch = meshes.extend(num_meshes)
Nikhila Ravi's avatar
Nikhila Ravi committed
1239
        torch.cuda.synchronize(device)
facebook-github-bot's avatar
facebook-github-bot committed
1240
1241

        def rasterize():
Nikhila Ravi's avatar
Nikhila Ravi committed
1242
1243
            rasterize_meshes(meshes_batch, image_size, blur_radius, faces_per_pixel)
            torch.cuda.synchronize(device)
facebook-github-bot's avatar
facebook-github-bot committed
1244
1245

        return rasterize
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292

    @staticmethod
    def bm_rasterize_meshes_with_clipping(
        num_meshes: int,
        ico_level: int,
        image_size: int,
        blur_radius: float,
        faces_per_pixel: int,
        dist: float,
    ):
        device = get_random_cuda_device()
        meshes = ico_sphere(ico_level, device)
        meshes_batch = meshes.extend(num_meshes)

        settings = RasterizationSettings(
            image_size=image_size,
            blur_radius=blur_radius,
            faces_per_pixel=faces_per_pixel,
            z_clip_value=1e-2,
            perspective_correct=True,
            cull_to_frustum=True,
        )

        # The camera is positioned so that the image plane intersects
        # the mesh and some faces are partially behind the image plane.
        R, T = look_at_view_transform(dist, 0, 0)
        cameras = FoVPerspectiveCameras(device=device, R=R, T=T, fov=90)
        rasterizer = MeshRasterizer(raster_settings=settings, cameras=cameras)

        # Transform the meshes to projec them onto the image plane
        meshes_screen = rasterizer.transform(meshes_batch)
        torch.cuda.synchronize(device)

        def rasterize():
            # Only measure rasterization speed (including clipping)
            rasterize_meshes(
                meshes_screen,
                image_size,
                blur_radius,
                faces_per_pixel,
                z_clip_value=1e-2,
                perspective_correct=True,
                cull_to_frustum=True,
            )
            torch.cuda.synchronize(device)

        return rasterize