savoji commited on
Commit
782bbfd
·
verified ·
1 Parent(s): 3845b05

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic.py +76 -0
  2. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic_unified.py +89 -0
  3. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_cam_unified.py +230 -0
  4. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/datasets.rst +9 -0
  5. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/loss.rst +9 -0
  6. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/ops.rst +6 -0
  7. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_utils.rst +9 -0
  8. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/fisheyecameras.rst +9 -0
  9. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/index.rst +11 -0
  10. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/raysampling.rst +9 -0
  11. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/renderer.rst +9 -0
  12. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/sample_pdf.rst +9 -0
  13. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/utils.rst +9 -0
  14. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/index.rst +7 -0
  15. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/opengl_utils.rst +9 -0
  16. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/rasterizer_opengl.rst +9 -0
  17. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/index.rst +7 -0
  18. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/renderer.rst +9 -0
  19. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/unified.rst +9 -0
  20. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/splatter_blend.rst +9 -0
  21. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/structures.rst +8 -0
  22. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/transforms.rst +7 -0
  23. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/utils.rst +7 -0
  24. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/index.rst +7 -0
  25. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/plotly_vis.rst +9 -0
  26. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/texture_vis.rst +9 -0
  27. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/batching.md +32 -0
  28. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/cameras.md +101 -0
  29. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/datasets.md +20 -0
  30. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/io.md +34 -0
  31. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/iou3d.md +93 -0
  32. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/meshes_io.md +75 -0
  33. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/renderer.md +76 -0
  34. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/why_pytorch3d.md +12 -0
  35. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_config_system.ipynb +1247 -0
  36. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_volumes.ipynb +902 -0
  37. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_colored_points.ipynb +485 -0
  38. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_densepose.ipynb +441 -0
  39. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__init__.py +12 -0
  40. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__pycache__/datatypes.cpython-310.pyc +0 -0
  41. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/compat.py +45 -0
  42. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/datatypes.py +60 -0
  43. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/linear_with_repeat.py +95 -0
  44. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__init__.py +10 -0
  45. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pyc +0 -0
  46. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pyc +0 -0
  47. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pyc +0 -0
  48. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/utils.py +33 -0
  49. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.cu +235 -0
  50. project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.h +107 -0
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """
9
+ This example demonstrates the most trivial, direct interface of the pulsar
10
+ sphere renderer. It renders and saves an image with 10 random spheres.
11
+ Output: basic.png.
12
+ """
13
+ import logging
14
+ import math
15
+ from os import path
16
+
17
+ import imageio
18
+ import torch
19
+ from pytorch3d.renderer.points.pulsar import Renderer
20
+
21
+
22
+ LOGGER = logging.getLogger(__name__)
23
+
24
+
25
+ def cli():
26
+ """
27
+ Basic example for the pulsar sphere renderer.
28
+
29
+ Writes to `basic.png`.
30
+ """
31
+ LOGGER.info("Rendering on GPU...")
32
+ torch.manual_seed(1)
33
+ n_points = 10
34
+ width = 1_000
35
+ height = 1_000
36
+ device = torch.device("cuda")
37
+ # The PyTorch3D system is right handed; in pulsar you can choose the handedness.
38
+ # For easy reproducibility we use a right handed coordinate system here.
39
+ renderer = Renderer(width, height, n_points, right_handed_system=True).to(device)
40
+ # Generate sample data.
41
+ vert_pos = torch.rand(n_points, 3, dtype=torch.float32, device=device) * 10.0
42
+ vert_pos[:, 2] += 25.0
43
+ vert_pos[:, :2] -= 5.0
44
+ vert_col = torch.rand(n_points, 3, dtype=torch.float32, device=device)
45
+ vert_rad = torch.rand(n_points, dtype=torch.float32, device=device)
46
+ cam_params = torch.tensor(
47
+ [
48
+ 0.0,
49
+ 0.0,
50
+ 0.0, # Position 0, 0, 0 (x, y, z).
51
+ 0.0,
52
+ math.pi, # Because of the right handed system, the camera must look 'back'.
53
+ 0.0, # Rotation 0, 0, 0 (in axis-angle format).
54
+ 5.0, # Focal length in world size.
55
+ 2.0, # Sensor size in world size.
56
+ ],
57
+ dtype=torch.float32,
58
+ device=device,
59
+ )
60
+ # Render.
61
+ image = renderer(
62
+ vert_pos,
63
+ vert_col,
64
+ vert_rad,
65
+ cam_params,
66
+ 1.0e-1, # Renderer blending parameter gamma, in [1., 1e-5].
67
+ 45.0, # Maximum depth.
68
+ )
69
+ LOGGER.info("Writing image to `%s`.", path.abspath("basic.png"))
70
+ imageio.imsave("basic.png", (image.cpu().detach() * 255.0).to(torch.uint8).numpy())
71
+ LOGGER.info("Done.")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ logging.basicConfig(level=logging.INFO)
76
+ cli()
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic_unified.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """
9
+ This example demonstrates the most trivial use of the pulsar PyTorch3D
10
+ interface for sphere renderering. It renders and saves an image with
11
+ 10 random spheres.
12
+ Output: basic-pt3d.png.
13
+ """
14
+ import logging
15
+ from os import path
16
+
17
+ import imageio
18
+ import torch
19
+ from pytorch3d.renderer import (
20
+ PerspectiveCameras,
21
+ PointsRasterizationSettings,
22
+ PointsRasterizer,
23
+ PulsarPointsRenderer,
24
+ )
25
+ from pytorch3d.structures import Pointclouds
26
+
27
+
28
+ LOGGER = logging.getLogger(__name__)
29
+
30
+
31
+ def cli():
32
+ """
33
+ Basic example for the pulsar sphere renderer using the PyTorch3D interface.
34
+
35
+ Writes to `basic-pt3d.png`.
36
+ """
37
+ LOGGER.info("Rendering on GPU...")
38
+ torch.manual_seed(1)
39
+ n_points = 10
40
+ width = 1_000
41
+ height = 1_000
42
+ device = torch.device("cuda")
43
+ # Generate sample data.
44
+ vert_pos = torch.rand(n_points, 3, dtype=torch.float32, device=device) * 10.0
45
+ vert_pos[:, 2] += 25.0
46
+ vert_pos[:, :2] -= 5.0
47
+ vert_col = torch.rand(n_points, 3, dtype=torch.float32, device=device)
48
+ pcl = Pointclouds(points=vert_pos[None, ...], features=vert_col[None, ...])
49
+ # Alternatively, you can also use the look_at_view_transform to get R and T:
50
+ # R, T = look_at_view_transform(
51
+ # dist=30.0, elev=0.0, azim=180.0, at=((0.0, 0.0, 30.0),), up=((0, 1, 0),),
52
+ # )
53
+ cameras = PerspectiveCameras(
54
+ # The focal length must be double the size for PyTorch3D because of the NDC
55
+ # coordinates spanning a range of two - and they must be normalized by the
56
+ # sensor width (see the pulsar example). This means we need here
57
+ # 5.0 * 2.0 / 2.0 to get the equivalent results as in pulsar.
58
+ focal_length=(5.0 * 2.0 / 2.0,),
59
+ R=torch.eye(3, dtype=torch.float32, device=device)[None, ...],
60
+ T=torch.zeros((1, 3), dtype=torch.float32, device=device),
61
+ image_size=((height, width),),
62
+ device=device,
63
+ )
64
+ vert_rad = torch.rand(n_points, dtype=torch.float32, device=device)
65
+ raster_settings = PointsRasterizationSettings(
66
+ image_size=(height, width),
67
+ radius=vert_rad,
68
+ )
69
+ rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)
70
+ renderer = PulsarPointsRenderer(rasterizer=rasterizer).to(device)
71
+ # Render.
72
+ image = renderer(
73
+ pcl,
74
+ gamma=(1.0e-1,), # Renderer blending parameter gamma, in [1., 1e-5].
75
+ znear=(1.0,),
76
+ zfar=(45.0,),
77
+ radius_world=True,
78
+ bg_col=torch.ones((3,), dtype=torch.float32, device=device),
79
+ )[0]
80
+ LOGGER.info("Writing image to `%s`.", path.abspath("basic-pt3d.png"))
81
+ imageio.imsave(
82
+ "basic-pt3d.png", (image.cpu().detach() * 255.0).to(torch.uint8).numpy()
83
+ )
84
+ LOGGER.info("Done.")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ logging.basicConfig(level=logging.INFO)
89
+ cli()
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_cam_unified.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """
9
+ This example demonstrates camera parameter optimization with the pulsar
10
+ PyTorch3D interface. For this, a reference image has been pre-generated
11
+ (you can find it at `../../tests/pulsar/reference/examples_TestRenderer_test_cam.png`).
12
+ The same scene parameterization is loaded and the camera parameters
13
+ distorted. Gradient-based optimization is used to converge towards the
14
+ original camera parameters.
15
+ Output: cam-pt3d.gif
16
+ """
17
+ import logging
18
+ from os import path
19
+
20
+ import cv2
21
+ import imageio
22
+ import numpy as np
23
+ import torch
24
+ from pytorch3d.renderer.cameras import PerspectiveCameras
25
+ from pytorch3d.renderer.points import (
26
+ PointsRasterizationSettings,
27
+ PointsRasterizer,
28
+ PulsarPointsRenderer,
29
+ )
30
+ from pytorch3d.structures.pointclouds import Pointclouds
31
+ from pytorch3d.transforms import axis_angle_to_matrix
32
+ from torch import nn, optim
33
+
34
+
35
+ LOGGER = logging.getLogger(__name__)
36
+ N_POINTS = 20
37
+ WIDTH = 1_000
38
+ HEIGHT = 1_000
39
+ DEVICE = torch.device("cuda")
40
+
41
+
42
+ class SceneModel(nn.Module):
43
+ """
44
+ A simple scene model to demonstrate use of pulsar in PyTorch modules.
45
+
46
+ The scene model is parameterized with sphere locations (vert_pos),
47
+ channel content (vert_col), radiuses (vert_rad), camera position (cam_pos),
48
+ camera rotation (cam_rot) and sensor focal length and width (cam_sensor).
49
+
50
+ The forward method of the model renders this scene description. Any
51
+ of these parameters could instead be passed as inputs to the forward
52
+ method and come from a different model.
53
+ """
54
+
55
+ def __init__(self):
56
+ super(SceneModel, self).__init__()
57
+ self.gamma = 0.1
58
+ # Points.
59
+ torch.manual_seed(1)
60
+ vert_pos = torch.rand(N_POINTS, 3, dtype=torch.float32) * 10.0
61
+ vert_pos[:, 2] += 25.0
62
+ vert_pos[:, :2] -= 5.0
63
+ self.register_parameter("vert_pos", nn.Parameter(vert_pos, requires_grad=False))
64
+ self.register_parameter(
65
+ "vert_col",
66
+ nn.Parameter(
67
+ torch.rand(N_POINTS, 3, dtype=torch.float32),
68
+ requires_grad=False,
69
+ ),
70
+ )
71
+ self.register_parameter(
72
+ "vert_rad",
73
+ nn.Parameter(
74
+ torch.rand(N_POINTS, dtype=torch.float32),
75
+ requires_grad=False,
76
+ ),
77
+ )
78
+ self.register_parameter(
79
+ "cam_pos",
80
+ nn.Parameter(
81
+ torch.tensor([0.1, 0.1, 0.0], dtype=torch.float32),
82
+ requires_grad=True,
83
+ ),
84
+ )
85
+ self.register_parameter(
86
+ "cam_rot",
87
+ # We're using the 6D rot. representation for better gradients.
88
+ nn.Parameter(
89
+ axis_angle_to_matrix(
90
+ torch.tensor(
91
+ [
92
+ [0.02, 0.02, 0.01],
93
+ ],
94
+ dtype=torch.float32,
95
+ )
96
+ )[0],
97
+ requires_grad=True,
98
+ ),
99
+ )
100
+ self.register_parameter(
101
+ "focal_length",
102
+ nn.Parameter(
103
+ torch.tensor(
104
+ [
105
+ 4.8 * 2.0 / 2.0,
106
+ ],
107
+ dtype=torch.float32,
108
+ ),
109
+ requires_grad=True,
110
+ ),
111
+ )
112
+ self.cameras = PerspectiveCameras(
113
+ # The focal length must be double the size for PyTorch3D because of the NDC
114
+ # coordinates spanning a range of two - and they must be normalized by the
115
+ # sensor width (see the pulsar example). This means we need here
116
+ # 5.0 * 2.0 / 2.0 to get the equivalent results as in pulsar.
117
+ #
118
+ # R, T and f are provided here, but will be provided again
119
+ # at every call to the forward method. The reason are problems
120
+ # with PyTorch which makes device placement for gradients problematic
121
+ # for tensors which are themselves on a 'gradient path' but not
122
+ # leafs in the calculation tree. This will be addressed by an architectural
123
+ # change in PyTorch3D in the future. Until then, this workaround is
124
+ # recommended.
125
+ focal_length=self.focal_length,
126
+ R=self.cam_rot[None, ...],
127
+ T=self.cam_pos[None, ...],
128
+ image_size=((HEIGHT, WIDTH),),
129
+ device=DEVICE,
130
+ )
131
+ raster_settings = PointsRasterizationSettings(
132
+ image_size=(HEIGHT, WIDTH),
133
+ radius=self.vert_rad,
134
+ )
135
+ rasterizer = PointsRasterizer(
136
+ cameras=self.cameras, raster_settings=raster_settings
137
+ )
138
+ self.renderer = PulsarPointsRenderer(rasterizer=rasterizer)
139
+
140
+ def forward(self):
141
+ # The Pointclouds object creates copies of it's arguments - that's why
142
+ # we have to create a new object in every forward step.
143
+ pcl = Pointclouds(
144
+ points=self.vert_pos[None, ...], features=self.vert_col[None, ...]
145
+ )
146
+ return self.renderer(
147
+ pcl,
148
+ gamma=(self.gamma,),
149
+ zfar=(45.0,),
150
+ znear=(1.0,),
151
+ radius_world=True,
152
+ bg_col=torch.ones((3,), dtype=torch.float32, device=DEVICE),
153
+ # As mentioned above: workaround for device placement of gradients for
154
+ # camera parameters.
155
+ focal_length=self.focal_length,
156
+ R=self.cam_rot[None, ...],
157
+ T=self.cam_pos[None, ...],
158
+ )[0]
159
+
160
+
161
+ def cli():
162
+ """
163
+ Camera optimization example using pulsar.
164
+
165
+ Writes to `cam.gif`.
166
+ """
167
+ LOGGER.info("Loading reference...")
168
+ # Load reference.
169
+ ref = (
170
+ torch.from_numpy(
171
+ imageio.imread(
172
+ "../../tests/pulsar/reference/examples_TestRenderer_test_cam.png"
173
+ )[:, ::-1, :].copy()
174
+ ).to(torch.float32)
175
+ / 255.0
176
+ ).to(DEVICE)
177
+ # Set up model.
178
+ model = SceneModel().to(DEVICE)
179
+ # Optimizer.
180
+ optimizer = optim.SGD(
181
+ [
182
+ {"params": [model.cam_pos], "lr": 1e-4},
183
+ {"params": [model.cam_rot], "lr": 5e-6},
184
+ # Using a higher lr for the focal length here, because
185
+ # the sensor width can not be optimized directly.
186
+ {"params": [model.focal_length], "lr": 1e-3},
187
+ ]
188
+ )
189
+
190
+ LOGGER.info("Writing video to `%s`.", path.abspath("cam-pt3d.gif"))
191
+ writer = imageio.get_writer("cam-pt3d.gif", format="gif", fps=25)
192
+
193
+ # Optimize.
194
+ for i in range(300):
195
+ optimizer.zero_grad()
196
+ result = model()
197
+ # Visualize.
198
+ result_im = (result.cpu().detach().numpy() * 255).astype(np.uint8)
199
+ cv2.imshow("opt", result_im[:, :, ::-1])
200
+ writer.append_data(result_im)
201
+ overlay_img = np.ascontiguousarray(
202
+ ((result * 0.5 + ref * 0.5).cpu().detach().numpy() * 255).astype(np.uint8)[
203
+ :, :, ::-1
204
+ ]
205
+ )
206
+ overlay_img = cv2.putText(
207
+ overlay_img,
208
+ "Step %d" % (i),
209
+ (10, 40),
210
+ cv2.FONT_HERSHEY_SIMPLEX,
211
+ 1,
212
+ (0, 0, 0),
213
+ 2,
214
+ cv2.LINE_AA,
215
+ False,
216
+ )
217
+ cv2.imshow("overlay", overlay_img)
218
+ cv2.waitKey(1)
219
+ # Update.
220
+ loss = ((result - ref) ** 2).sum()
221
+ LOGGER.info("loss %d: %f", i, loss.item())
222
+ loss.backward()
223
+ optimizer.step()
224
+ writer.close()
225
+ LOGGER.info("Done.")
226
+
227
+
228
+ if __name__ == "__main__":
229
+ logging.basicConfig(level=logging.INFO)
230
+ cli()
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/datasets.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.datasets
2
+ ===========================
3
+
4
+ Dataset loaders for datasets including ShapeNetCore.
5
+
6
+ .. automodule:: pytorch3d.datasets
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/loss.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.loss
2
+ ====================
3
+
4
+ Loss functions for meshes and point clouds.
5
+
6
+ .. automodule:: pytorch3d.loss
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/ops.rst ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ pytorch3d.ops
2
+ ===========================
3
+
4
+ .. automodule:: pytorch3d.ops
5
+ :members:
6
+ :undoc-members:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_utils.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.camera_utils
2
+ ===============================
3
+
4
+ camera_utils
5
+
6
+ .. automodule:: pytorch3d.renderer.camera_utils
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/fisheyecameras.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.fisheyecameras
2
+ =================================
3
+
4
+ fisheyecameras
5
+
6
+ .. automodule:: pytorch3d.renderer.fisheyecameras
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/index.rst ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.implicit
2
+ ===========================
3
+
4
+ .. toctree::
5
+
6
+ harmonic_embedding
7
+ raymarching
8
+ raysampling
9
+ renderer
10
+ sample_pdf
11
+ utils
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/raysampling.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.implicit.raysampling
2
+ =======================================
3
+
4
+ raysampling
5
+
6
+ .. automodule:: pytorch3d.renderer.implicit.raysampling
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/renderer.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.implicit.renderer
2
+ ====================================
3
+
4
+ renderer
5
+
6
+ .. automodule:: pytorch3d.renderer.implicit.renderer
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/sample_pdf.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.implicit.sample_pdf
2
+ ======================================
3
+
4
+ sample_pdf
5
+
6
+ .. automodule:: pytorch3d.renderer.implicit.sample_pdf
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/utils.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.implicit.utils
2
+ =================================
3
+
4
+ utils
5
+
6
+ .. automodule:: pytorch3d.renderer.implicit.utils
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/index.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.opengl
2
+ =========================
3
+
4
+ .. toctree::
5
+
6
+ opengl_utils
7
+ rasterizer_opengl
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/opengl_utils.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.opengl.opengl_utils
2
+ ======================================
3
+
4
+ opengl_utils
5
+
6
+ .. automodule:: pytorch3d.renderer.opengl.opengl_utils
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/rasterizer_opengl.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.opengl.rasterizer_opengl
2
+ ===========================================
3
+
4
+ rasterizer_opengl
5
+
6
+ .. automodule:: pytorch3d.renderer.opengl.rasterizer_opengl
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/index.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.points.pulsar
2
+ ================================
3
+
4
+ .. toctree::
5
+
6
+ renderer
7
+ unified
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/renderer.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.points.pulsar.renderer
2
+ =========================================
3
+
4
+ renderer
5
+
6
+ .. automodule:: pytorch3d.renderer.points.pulsar.renderer
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/unified.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.points.pulsar.unified
2
+ ========================================
3
+
4
+ unified
5
+
6
+ .. automodule:: pytorch3d.renderer.points.pulsar.unified
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/splatter_blend.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.renderer.splatter_blend
2
+ =================================
3
+
4
+ splatter_blend
5
+
6
+ .. automodule:: pytorch3d.renderer.splatter_blend
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/structures.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.structures
2
+ ====================
3
+
4
+ .. automodule:: pytorch3d.structures
5
+ :members:
6
+ :undoc-members:
7
+
8
+
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/transforms.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pytorch3d.transforms
2
+ ===========================
3
+
4
+ .. automodule:: pytorch3d.transforms
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/utils.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pytorch3d.utils
2
+ ====================
3
+
4
+ .. automodule:: pytorch3d.utils
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/index.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pytorch3d.vis
2
+ =============
3
+
4
+ .. toctree::
5
+
6
+ plotly_vis
7
+ texture_vis
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/plotly_vis.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.vis.plotly_vis
2
+ ========================
3
+
4
+ plotly_vis
5
+
6
+ .. automodule:: pytorch3d.vis.plotly_vis
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/texture_vis.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pytorch3d.vis.texture_vis
2
+ =========================
3
+
4
+ texture_vis
5
+
6
+ .. automodule:: pytorch3d.vis.texture_vis
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/batching.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: Batching
4
+ ---
5
+
6
+ # Batching
7
+
8
+ In deep learning, every optimization step operates on multiple input examples for robust training. Thus, efficient batching is crucial. For image inputs, batching is straightforward; N images are resized to the same height and width and stacked as a 4 dimensional tensor of shape `N x 3 x H x W`. For meshes, batching is less straightforward.
9
+
10
+ <img src="assets/batch_intro.png" alt="batch_intro" align="middle"/>
11
+
12
+ ## Batch modes for meshes
13
+
14
+ Assume you want to construct a batch containing two meshes, with `mesh1 = (v1: V1 x 3, f1: F1 x 3)` containing `V1` vertices and `F1` faces, and `mesh2 = (v2: V2 x 3, f2: F2 x 3)` with `V2 (!= V1)` vertices and `F2 (!= F1)` faces. The [Meshes][meshes] data structure provides three different ways to batch *heterogeneous* meshes. If `meshes = Meshes(verts = [v1, v2], faces = [f1, f2])` is an instantiation of the data structure, then
15
+
16
+ * List: Returns the examples in the batch as a list of tensors. Specifically, `meshes.verts_list()` returns the list of vertices `[v1, v2]`. Similarly, `meshes.faces_list()` returns the list of faces `[f1, f2]`.
17
+ * Padded: The padded representation constructs a tensor by padding the extra values. Specifically, `meshes.verts_padded()` returns a tensor of shape `2 x max(V1, V2) x 3` and pads the extra vertices with `0`s. Similarly, `meshes.faces_padded()` returns a tensor of shape `2 x max(F1, F2) x 3` and pads the extra faces with `-1`s.
18
+ * Packed: The packed representation concatenates the examples in the batch into a tensor. In particular, `meshes.verts_packed()` returns a tensor of shape `(V1 + V2) x 3`. Similarly, `meshes.faces_packed()` returns a tensor of shape `(F1 + F2) x 3` for the faces. In the packed mode, auxiliary variables are computed that enable efficient conversion between packed and padded or list modes.
19
+
20
+ <img src="assets/batch_modes.gif" alt="batch_modes" height="450" align="middle" />
21
+
22
+ ## Use cases for batch modes
23
+
24
+ The need for different mesh batch modes is inherent to the way PyTorch operators are implemented. To fully utilize the optimized PyTorch ops, the [Meshes][meshes] data structure allows for efficient conversion between the different batch modes. This is crucial when aiming for a fast and efficient training cycle. An example of this is [Mesh R-CNN][meshrcnn]. Here, in the same forward pass different parts of the network assume different inputs, which are computed by converting between the different batch modes. In particular, [vert_align][vert_align] assumes a *padded* input tensor while immediately after [graph_conv][graphconv] assumes a *packed* input tensor.
25
+
26
+ <img src="assets/meshrcnn.png" alt="meshrcnn" width="700" align="middle" />
27
+
28
+
29
+ [meshes]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py
30
+ [graphconv]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/graph_conv.py
31
+ [vert_align]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/vert_align.py
32
+ [meshrcnn]: https://github.com/facebookresearch/meshrcnn
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/cameras.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: Cameras
4
+ ---
5
+
6
+ # Cameras
7
+
8
+ ## Camera Coordinate Systems
9
+
10
+ When working with 3D data, there are 4 coordinate systems users need to know
11
+ * **World coordinate system**
12
+ This is the system the object/scene lives - the world.
13
+ * **Camera view coordinate system**
14
+ This is the system that has its origin on the image plane and the `Z`-axis perpendicular to the image plane. In PyTorch3D, we assume that `+X` points left, and `+Y` points up and `+Z` points out from the image plane. The transformation from world to view happens after applying a rotation (`R`) and translation (`T`).
15
+ * **NDC coordinate system**
16
+ This is the normalized coordinate system that confines in a volume the rendered part of the object/scene. Also known as view volume. For square images, under the PyTorch3D convention, `(+1, +1, znear)` is the top left near corner, and `(-1, -1, zfar)` is the bottom right far corner of the volume. For non-square images, the side of the volume in `XY` with the smallest length ranges from `[-1, 1]` while the larger side from `[-s, s]`, where `s` is the aspect ratio and `s > 1` (larger divided by smaller side).
17
+ The transformation from view to NDC happens after applying the camera projection matrix (`P`).
18
+ * **Screen coordinate system**
19
+ This is another representation of the view volume with the `XY` coordinates defined in pixel space instead of a normalized space. (0,0) is the top left corner of the top left pixel
20
+ and (W,H) is the bottom right corner of the bottom right pixel.
21
+
22
+ An illustration of the 4 coordinate systems is shown below
23
+ ![cameras](https://user-images.githubusercontent.com/669761/145090051-67b506d7-6d73-4826-a677-5873b7cb92ba.png)
24
+
25
+ ## Defining Cameras in PyTorch3D
26
+
27
+ Cameras in PyTorch3D transform an object/scene from world to view by first transforming the object/scene to view (via transforms `R` and `T`) and then projecting the 3D object/scene to a normalized space via the projection matrix `P = K[R | T]`, where `K` is the intrinsic matrix. The camera parameters in `K` define the normalized space. If users define the camera parameters in NDC space, then the transform projects points to NDC. If the camera parameters are defined in screen space, the transformed points are in screen space.
28
+
29
+ Note that the base `CamerasBase` class makes no assumptions about the coordinate systems. All the above transforms are geometric transforms defined purely by `R`, `T` and `K`. This means that users can define cameras in any coordinate system and for any transforms. The method `transform_points` will apply `K` , `R` and `T` to the input points as a simple matrix transformation. However, if users wish to use cameras with the PyTorch3D renderer, they need to abide to PyTorch3D's coordinate system assumptions (read below).
30
+
31
+ We provide instantiations of common camera types in PyTorch3D and how users can flexibly define the projection space below.
32
+
33
+ ## Interfacing with the PyTorch3D Renderer
34
+
35
+ The PyTorch3D renderer for both meshes and point clouds assumes that the camera transformed points, meaning the points passed as input to the rasterizer, are in PyTorch3D's NDC space. So to get the expected rendering outcome, users need to make sure that their 3D input data and cameras abide by these PyTorch3D coordinate system assumptions. The PyTorch3D coordinate system assumes `+X:left`, `+Y: up` and `+Z: from us to scene` (right-handed) . Confusions regarding coordinate systems are common so we advise that you spend some time understanding your data and the coordinate system they live in and transform them accordingly before using the PyTorch3D renderer.
36
+
37
+ Examples of cameras and how they interface with the PyTorch3D renderer can be found in our tutorials.
38
+
39
+ ### Camera Types
40
+
41
+ All cameras inherit from `CamerasBase` which is a base class for all cameras. PyTorch3D provides four different camera types. The `CamerasBase` defines methods that are common to all camera models:
42
+ * `get_camera_center` that returns the optical center of the camera in world coordinates
43
+ * `get_world_to_view_transform` which returns a 3D transform from world coordinates to the camera view coordinates `(R, T)`
44
+ * `get_full_projection_transform` which composes the projection transform (`K`) with the world-to-view transform `(R, T)`
45
+ * `transform_points` which takes a set of input points in world coordinates and projects to NDC coordinates ranging from [-1, -1, znear] to [+1, +1, zfar].
46
+ * `get_ndc_camera_transform` which defines the conversion to PyTorch3D's NDC space and is called when interfacing with the PyTorch3D renderer. If the camera is defined in NDC space, then the identity transform is returned. If the cameras is defined in screen space, the conversion from screen to NDC is returned. If users define their own camera in screen space, they need to think of the screen to NDC conversion. We provide examples for the `PerspectiveCameras` and `OrthographicCameras`.
47
+ * `transform_points_ndc` which takes a set of points in world coordinates and projects them to PyTorch3D's NDC space
48
+ * `transform_points_screen` which takes a set of input points in world coordinates and projects them to the screen coordinates ranging from [0, 0, znear] to [W, H, zfar]
49
+
50
+ Users can easily customize their own cameras. For each new camera, users should implement the `get_projection_transform` routine that returns the mapping `P` from camera view coordinates to NDC coordinates.
51
+
52
+ #### FoVPerspectiveCameras, FoVOrthographicCameras
53
+ These two cameras follow the OpenGL convention for perspective and orthographic cameras respectively. The user provides the near `znear` and far `zfar` field which confines the view volume in the `Z` axis. The view volume in the `XY` plane is defined by field of view angle (`fov`) in the case of `FoVPerspectiveCameras` and by `min_x, min_y, max_x, max_y` in the case of `FoVOrthographicCameras`.
54
+ These cameras are by default in NDC space.
55
+
56
+ #### PerspectiveCameras, OrthographicCameras
57
+ These two cameras follow the Multi-View Geometry convention for cameras. The user provides the focal length (`fx`, `fy`) and the principal point (`px`, `py`). For example, `camera = PerspectiveCameras(focal_length=((fx, fy),), principal_point=((px, py),))`
58
+
59
+ The camera projection of a 3D point `(X, Y, Z)` in view coordinates to a point `(x, y, z)` in projection space (either NDC or screen) is
60
+
61
+ ```
62
+ # for perspective camera
63
+ x = fx * X / Z + px
64
+ y = fy * Y / Z + py
65
+ z = 1 / Z
66
+
67
+ # for orthographic camera
68
+ x = fx * X + px
69
+ y = fy * Y + py
70
+ z = Z
71
+ ```
72
+
73
+ The user can define the camera parameters in NDC or in screen space. Screen space camera parameters are common and for that case the user needs to set `in_ndc` to `False` and also provide the `image_size=(height, width)` of the screen, aka the image.
74
+
75
+ The `get_ndc_camera_transform` provides the transform from screen to NDC space in PyTorch3D. Note that the screen space assumes that the principal point is provided in the space with `+X left`, `+Y down` and origin at the top left corner of the image. To convert to NDC we need to account for the scaling of the normalized space as well as the change in `XY` direction.
76
+
77
+ Below are example of equivalent `PerspectiveCameras` instantiations in NDC and screen space, respectively.
78
+
79
+ ```python
80
+ # NDC space camera
81
+ fcl_ndc = (1.2,)
82
+ prp_ndc = ((0.2, 0.5),)
83
+ cameras_ndc = PerspectiveCameras(focal_length=fcl_ndc, principal_point=prp_ndc)
84
+
85
+ # Screen space camera
86
+ image_size = ((128, 256),) # (h, w)
87
+ fcl_screen = (76.8,) # fcl_ndc * min(image_size) / 2
88
+ prp_screen = ((115.2, 32), ) # w / 2 - px_ndc * min(image_size) / 2, h / 2 - py_ndc * min(image_size) / 2
89
+ cameras_screen = PerspectiveCameras(focal_length=fcl_screen, principal_point=prp_screen, in_ndc=False, image_size=image_size)
90
+ ```
91
+
92
+ The relationship between screen and NDC specifications of a camera's `focal_length` and `principal_point` is given by the following equations, where `s = min(image_width, image_height)`.
93
+ The transformation of x and y coordinates between screen and NDC is exactly the same as for px and py.
94
+
95
+ ```
96
+ fx_ndc = fx_screen * 2.0 / s
97
+ fy_ndc = fy_screen * 2.0 / s
98
+
99
+ px_ndc = - (px_screen - image_width / 2.0) * 2.0 / s
100
+ py_ndc = - (py_screen - image_height / 2.0) * 2.0 / s
101
+ ```
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/datasets.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: Data loaders
4
+ ---
5
+
6
+ # Data loaders for common 3D Datasets
7
+
8
+ ### ShapetNetCore
9
+
10
+ ShapeNet is a dataset of 3D CAD models. ShapeNetCore is a subset of the ShapeNet dataset and can be downloaded from https://www.shapenet.org/. There are two versions ShapeNetCore: v1 (55 categories) and v2 (57 categories).
11
+
12
+ The PyTorch3D [ShapeNetCore data loader](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/datasets/shapenet/shapenet_core.py) inherits from `torch.utils.data.Dataset`. It takes the path where the ShapeNetCore dataset is stored locally and loads models in the dataset. The ShapeNetCore class loads and returns models with their `categories`, `model_ids`, `vertices` and `faces`. The `ShapeNetCore` data loader also has a customized `render` function that renders models by the specified `model_ids (List[int])`, `categories (List[str])` or `indices (List[int])` with PyTorch3D's differentiable renderer.
13
+
14
+ The loaded dataset can be passed to `torch.utils.data.DataLoader` with PyTorch3D's customized collate_fn: `collate_batched_meshes` from the `pytorch3d.dataset.utils` module. The `vertices` and `faces` of the models are used to construct a [Meshes](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py) object representing the batched meshes. This `Meshes` representation can be easily used with other ops and rendering in PyTorch3D.
15
+
16
+ ### R2N2
17
+
18
+ The R2N2 dataset contains 13 categories that are a subset of the ShapeNetCore v.1 dataset. The R2N2 dataset also contains its own 24 renderings of each object and voxelized models. The R2N2 Dataset can be downloaded following the instructions [here](http://3d-r2n2.stanford.edu/).
19
+
20
+ The PyTorch3D [R2N2 data loader](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/datasets/r2n2/r2n2.py) is initialized with the paths to the ShapeNet dataset, the R2N2 dataset and the splits file for R2N2. Just like `ShapeNetCore`, it can be passed to `torch.utils.data.DataLoader` with a customized collate_fn: `collate_batched_R2N2` from the `pytorch3d.dataset.r2n2.utils` module. It returns all the data that `ShapeNetCore` returns, and in addition, it returns the R2N2 renderings (24 views for each model) along with the camera calibration matrices and a voxel representation for each model. Similar to `ShapeNetCore`, it has a customized `render` function that supports rendering specified models with the PyTorch3D differentiable renderer. In addition, it supports rendering models with the same orientations as R2N2's original renderings.
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/io.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: File IO
4
+ ---
5
+
6
+ # File IO
7
+ There is a flexible interface for loading and saving point clouds and meshes from different formats.
8
+
9
+ The main usage is via the `pytorch3d.io.IO` object, and its methods
10
+ `load_mesh`, `save_mesh`, `load_pointcloud` and `save_pointcloud`.
11
+
12
+ For example, to load a mesh you might do
13
+ ```
14
+ from pytorch3d.io import IO
15
+
16
+ device=torch.device("cuda:0")
17
+ mesh = IO().load_mesh("mymesh.obj", device=device)
18
+ ```
19
+
20
+ and to save a pointcloud you might do
21
+ ```
22
+ pcl = Pointclouds(...)
23
+ IO().save_pointcloud(pcl, "output_pointcloud.ply")
24
+ ```
25
+
26
+ For meshes, this supports OBJ, PLY and OFF files.
27
+
28
+ For pointclouds, this supports PLY files.
29
+
30
+ In addition, there is experimental support for loading meshes from
31
+ [glTF 2 assets](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0)
32
+ stored either in a GLB container file or a glTF JSON file with embedded binary data.
33
+ This must be enabled explicitly, as described in
34
+ `pytorch3d/io/experimental_gltf_io.py`.
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/iou3d.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: IoU3D
4
+ ---
5
+
6
+ # Intersection Over Union of Oriented 3D Boxes: A New Algorithm
7
+
8
+ Author: Georgia Gkioxari
9
+
10
+ Implementation: Georgia Gkioxari and Nikhila Ravi
11
+
12
+ ## Description
13
+
14
+ Intersection over union (IoU) of boxes is widely used as an evaluation metric in object detection ([1][pascalvoc], [2][coco]).
15
+ In 2D, IoU is commonly applied to axis-aligned boxes, namely boxes with edges parallel to the image axis.
16
+ In 3D, boxes are usually not axis aligned and can be oriented in any way in the world.
17
+ We introduce a new algorithm which computes the *exact* IoU of two *oriented 3D boxes*.
18
+
19
+ Our algorithm is based on the simple observation that the intersection of two oriented 3D boxes, `box1` and `box2`, is a convex polyhedron (convex n-gon in 2D) with `n > 2` comprised of connected *planar units*.
20
+ In 3D, these planar units are 3D triangular faces.
21
+ In 2D, they are 2D edges.
22
+ Each planar unit belongs strictly to either `box1` or `box2`.
23
+ Our algorithm finds these units by iterating through the sides of each box.
24
+
25
+ 1. For each 3D triangular face `e` in `box1` we check wether `e` is *inside* `box2`.
26
+ 2. If `e` is not *inside*, then we discard it.
27
+ 3. If `e` is *inside* or *partially inside*, then the part of `e` *inside* `box2` is added to the units that comprise the final intersection shape.
28
+ 4. We repeat for `box2`.
29
+
30
+ Below, we show a visualization of our algorithm for the case of 2D oriented boxes.
31
+
32
+ <p align="center">
33
+ <img src="assets/iou3d.gif" alt="drawing" width="400"/>
34
+ </p>
35
+
36
+ Note that when a box's unit `e` is *partially inside* a `box` then `e` breaks into smaller units. In 2D, `e` is an edge and breaks into smaller edges. In 3D, `e` is a 3D triangular face and is clipped to more and smaller faces by the plane of the `box` it intersects with.
37
+ This is the sole fundamental difference between the algorithms for 2D and 3D.
38
+
39
+ ## Comparison With Other Algorithms
40
+
41
+ Current algorithms for 3D box IoU rely on crude approximations or make box assumptions, for example they restrict the orientation of the 3D boxes.
42
+ [Objectron][objectron] provides a nice discussion on the limitations of prior works.
43
+ [Objectron][objectron] introduces a great algorithm for exact IoU computation of oriented 3D boxes.
44
+ Objectron's algorithm computes the intersection points of two boxes using the [Sutherland-Hodgman algorithm][clipalgo].
45
+ The intersection shape is formed by the convex hull from the intersection points, using the [Qhull library][qhull].
46
+
47
+ Our algorithm has several advantages over Objectron's:
48
+
49
+ * Our algorithm also computes the points of intersection, similar to Objectron, but in addition stores the *planar units* the points belong to. This eliminates the need for convex hull computation which is `O(nlogn)` and relies on a third party library which often crashes with nondescript error messages.
50
+ * Objectron's implementation assumes that boxes are a rotation away from axis aligned. Our algorithm and implementation make no such assumption and work for any 3D boxes.
51
+ * Our implementation supports batching, unlike Objectron which assumes single element inputs for `box1` and `box2`.
52
+ * Our implementation is easily parallelizable and in fact we provide a custom C++/CUDA implementation which is **450 times faster than Objectron**.
53
+
54
+ Below we compare the performance for Objectron (in C++) and our algorithm, in C++ and CUDA. We benchmark for a common use case in object detection where `boxes1` hold M predictions and `boxes2` hold N ground truth 3D boxes in an image and compute the `MxN` IoU matrix. We report the time in ms for `M=N=16`.
55
+
56
+ <p align="center">
57
+ <img src="assets/iou3d_comp.png" alt="drawing" width="400"/>
58
+ </p>
59
+
60
+ ## Usage and Code
61
+
62
+ ```python
63
+ from pytorch3d.ops import box3d_overlap
64
+ # Assume inputs: boxes1 (M, 8, 3) and boxes2 (N, 8, 3)
65
+ intersection_vol, iou_3d = box3d_overlap(boxes1, boxes2)
66
+ ```
67
+
68
+ For more details, read [iou_box3d.py](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/iou_box3d.py).
69
+
70
+ Note that our implementation is not differentiable as of now. We plan to add gradient support soon.
71
+
72
+ We also include have extensive [tests](https://github.com/facebookresearch/pytorch3d/blob/main/tests/test_iou_box3d.py) comparing our implementation with Objectron and MeshLab.
73
+
74
+
75
+ ## Cite
76
+
77
+ If you use our 3D IoU algorithm, please cite PyTorch3D
78
+
79
+ ```bibtex
80
+ @article{ravi2020pytorch3d,
81
+ author = {Nikhila Ravi and Jeremy Reizenstein and David Novotny and Taylor Gordon
82
+ and Wan-Yen Lo and Justin Johnson and Georgia Gkioxari},
83
+ title = {Accelerating 3D Deep Learning with PyTorch3D},
84
+ journal = {arXiv:2007.08501},
85
+ year = {2020},
86
+ }
87
+ ```
88
+
89
+ [pascalvoc]: http://host.robots.ox.ac.uk/pascal/VOC/
90
+ [coco]: https://cocodataset.org/
91
+ [objectron]: https://arxiv.org/abs/2012.09988
92
+ [qhull]: http://www.qhull.org/
93
+ [clipalgo]: https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/meshes_io.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ sidebar_label: Loading from file
3
+ hide_title: true
4
+ ---
5
+
6
+ # Meshes and IO
7
+
8
+ The Meshes object represents a batch of triangulated meshes, and is central to
9
+ much of the functionality of PyTorch3D. There is no insistence that each mesh in
10
+ the batch has the same number of vertices or faces. When available, it can store
11
+ other data which pertains to the mesh, for example face normals, face areas
12
+ and textures.
13
+
14
+ Two common file formats for storing single meshes are ".obj" and ".ply" files,
15
+ and PyTorch3D has functions for reading these.
16
+
17
+ ## OBJ
18
+
19
+ Obj files have a standard way to store extra information about a mesh. Given an
20
+ obj file, it can be read with
21
+
22
+ ```
23
+ verts, faces, aux = load_obj(filename)
24
+ ```
25
+
26
+ which sets `verts` to be a (V,3)-tensor of vertices and `faces.verts_idx` to be
27
+ an (F,3)- tensor of the vertex-indices of each of the corners of the faces.
28
+ Faces which are not triangles will be split into triangles. `aux` is an object
29
+ which may contain normals, uv coordinates, material colors and textures if they
30
+ are present, and `faces` may additionally contain indices into these normals,
31
+ textures and materials in its NamedTuple structure. A Meshes object containing a
32
+ single mesh can be created from just the vertices and faces using
33
+ ```
34
+ meshes = Meshes(verts=[verts], faces=[faces.verts_idx])
35
+ ```
36
+
37
+ If there is texture information in the `.obj` it can be used to initialize a
38
+ `Textures` class which is passed into the `Meshes` constructor. Currently we
39
+ support loading of texture maps for meshes which have one texture map for the
40
+ entire mesh e.g.
41
+
42
+ ```
43
+ verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2)
44
+ faces_uvs = faces.textures_idx[None, ...] # (1, F, 3)
45
+ tex_maps = aux.texture_images
46
+
47
+ # tex_maps is a dictionary of {material name: texture image}.
48
+ # Take the first image:
49
+ texture_image = list(tex_maps.values())[0]
50
+ texture_image = texture_image[None, ...] # (1, H, W, 3)
51
+
52
+ # Create a textures object
53
+ tex = Textures(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)
54
+
55
+ # Initialise the mesh with textures
56
+ meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex)
57
+ ```
58
+
59
+ The `load_objs_as_meshes` function provides this procedure.
60
+
61
+ ## PLY
62
+
63
+ Ply files are flexible in the way they store additional information. PyTorch3D
64
+ provides a function just to read the vertices and faces from a ply file.
65
+ The call
66
+ ```
67
+ verts, faces = load_ply(filename)
68
+ ```
69
+ sets `verts` to be a (V,3)-tensor of vertices and `faces` to be an (F,3)-
70
+ tensor of the vertex-indices of each of the corners of the faces. Faces which
71
+ are not triangles will be split into triangles. A Meshes object containing a
72
+ single mesh can be created from this data using
73
+ ```
74
+ meshes = Meshes(verts=[verts], faces=[faces])
75
+ ```
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/renderer.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: Overview
4
+ ---
5
+
6
+ # Rendering Overview
7
+
8
+ Differentiable rendering is a relatively new and exciting research area in computer vision, bridging the gap between 2D and 3D by allowing 2D image pixels to be related back to 3D properties of a scene.
9
+
10
+ For example, by rendering an image from a 3D shape predicted by a neural network, it is possible to compute a 2D loss with a reference image. Inverting the rendering step means we can relate the 2D loss from the pixels back to the 3D properties of the shape such as the positions of mesh vertices, enabling 3D shapes to be learnt without any explicit 3D supervision.
11
+
12
+ We extensively researched existing codebases for differentiable rendering and found that:
13
+ - the rendering pipeline is complex with more than 7 separate components which need to interoperate and be differentiable
14
+ - popular existing approaches [[1](#1), [2](#2)] are based on the same core implementation which bundles many of the key components into large CUDA kernels which require significant expertise to understand, and has limited scope for extensions
15
+ - existing methods either do not support batching or assume that meshes in a batch have the same number of vertices and faces
16
+ - existing projects only provide CUDA implementations so they cannot be used without GPUs
17
+
18
+ In order to experiment with different approaches, we wanted a modular implementation that is easy to use and extend, and supports [heterogeneous batching](batching.md). Taking inspiration from existing work [[1](#1), [2](#2)], we have created a new, modular, differentiable renderer with **parallel implementations in PyTorch, C++ and CUDA**, as well as comprehensive documentation and tests, with the aim of helping to further research in this field.
19
+
20
+ Our implementation decouples the rasterization and shading steps of rendering. The core rasterization step (based on [[2]](#2)) returns several intermediate variables and has an optimized implementation in CUDA. The rest of the pipeline is implemented purely in PyTorch, and is designed to be customized and extended. With this approach, the PyTorch3D differentiable renderer can be imported as a library.
21
+
22
+ ## <u>Get started</u>
23
+
24
+ To learn about more the implementation and start using the renderer refer to [getting started with renderer](renderer_getting_started.md), which also contains the [architecture overview](assets/architecture_renderer.jpg) and [coordinate transformation conventions](assets/transforms_overview.jpg).
25
+
26
+ ## <u>Tech Report</u>
27
+
28
+ For an in depth explanation of the renderer design, key features and benchmarks please refer to the PyTorch3D Technical Report on ArXiv: [Accelerating 3D Deep Learning with PyTorch3D](https://arxiv.org/abs/2007.08501), for the pulsar backend see here: [Fast Differentiable Raycasting for Neural Rendering using Sphere-based Representations](https://arxiv.org/abs/2004.07484).
29
+
30
+ ---
31
+
32
+ **NOTE: CUDA Memory usage**
33
+
34
+ The main comparison in the Technical Report is with SoftRasterizer [[2](#2)]. The SoftRasterizer forward CUDA kernel only outputs one `(N, H, W, 4)` FloatTensor compared with the PyTorch3D rasterizer forward CUDA kernel which outputs 4 tensors:
35
+
36
+ - `pix_to_face`, LongTensor `(N, H, W, K)`
37
+ - `zbuf`, FloatTensor `(N, H, W, K)`
38
+ - `dist`, FloatTensor `(N, H, W, K)`
39
+ - `bary_coords`, FloatTensor `(N, H, W, K, 3)`
40
+
41
+ where **N** = batch size, **H/W** are image height/width, **K** is the faces per pixel. The PyTorch3D backward pass returns gradients for `zbuf`, `dist` and `bary_coords`.
42
+
43
+ Returning intermediate variables from rasterization has an associated memory cost. We can calculate the theoretical lower bound on the memory usage for the forward and backward pass as follows:
44
+
45
+ ```
46
+ # Assume 4 bytes per float, and 8 bytes for long
47
+
48
+ memory_forward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4 + (N * H * W * K) * 8
49
+ memory_backward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4
50
+
51
+ total_memory = memory_forward_pass + memory_backward_pass
52
+ = (N * H * W * K) * (5 * 4 * 2 + 8)
53
+ = (N * H * W * K) * 48
54
+ ```
55
+
56
+ We need 48 bytes per face per pixel of the rasterized output. In order to remain within bounds for memory usage we can vary the batch size (**N**), image size (**H/W**) and faces per pixel (**K**). For example, for a fixed batch size, if using a larger image size, try reducing the faces per pixel.
57
+
58
+ ---
59
+
60
+ ### References
61
+
62
+ <a id="1">[1]</a> Kato et al, 'Neural 3D Mesh Renderer', CVPR 2018
63
+
64
+ <a id="2">[2]</a> Liu et al, 'Soft Rasterizer: A Differentiable Renderer for Image-based 3D Reasoning', ICCV 2019
65
+
66
+ <a id="3">[3]</a> Loper et al, 'OpenDR: An Approximate Differentiable Renderer', ECCV 2014
67
+
68
+ <a id="4">[4]</a> De La Gorce et al, 'Model-based 3D Hand Pose Estimation from Monocular Video', PAMI 2011
69
+
70
+ <a id="5">[5]</a> Li et al, 'Differentiable Monte Carlo Ray Tracing through Edge Sampling', SIGGRAPH Asia 2018
71
+
72
+ <a id="6">[6]</a> Yifan et al, 'Differentiable Surface Splatting for Point-based Geometry Processing', SIGGRAPH Asia 2019
73
+
74
+ <a id="7">[7]</a> Loubet et al, 'Reparameterizing Discontinuous Integrands for Differentiable Rendering', SIGGRAPH Asia 2019
75
+
76
+ <a id="8">[8]</a> Chen et al, 'Learning to Predict 3D Objects with an Interpolation-based Differentiable Renderer', NeurIPS 2019
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/why_pytorch3d.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ hide_title: true
3
+ sidebar_label: Why PyTorch3D
4
+ ---
5
+
6
+
7
+ # Why PyTorch3D
8
+
9
+
10
+ Our goal with PyTorch3D is to help accelerate research at the intersection of deep learning and 3D. 3D data is more complex than 2D images and while working on projects such as [Mesh R-CNN](https://github.com/facebookresearch/meshrcnn) and [C3DPO](https://github.com/facebookresearch/c3dpo_nrsfm), we encountered several challenges including 3D data representation, batching, and speed. We have developed many useful operators and abstractions for working on 3D deep learning and want to share this with the community to drive novel research in this area.
11
+
12
+ In PyTorch3D we have included efficient 3D operators, heterogeneous batching capabilities, and a modular differentiable rendering API, to equip researchers in this field with a much needed toolkit to implement cutting-edge research with complex 3D inputs.
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_config_system.ipynb ADDED
@@ -0,0 +1,1247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "customInput": null,
8
+ "customOutput": null,
9
+ "originalKey": "f0af2d90-cb21-4ab4-b4cb-0fd00dbfb77b",
10
+ "showInput": true
11
+ },
12
+ "outputs": [],
13
+ "source": [
14
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
15
+ ]
16
+ },
17
+ {
18
+ "attachments": {},
19
+ "cell_type": "markdown",
20
+ "metadata": {
21
+ "customInput": null,
22
+ "originalKey": "4e15bfa2-5404-40d0-98b6-eb2732c8b72b",
23
+ "showInput": false
24
+ },
25
+ "source": [
26
+ "# Implicitron's config system"
27
+ ]
28
+ },
29
+ {
30
+ "attachments": {},
31
+ "cell_type": "markdown",
32
+ "metadata": {
33
+ "customInput": null,
34
+ "originalKey": "287be985-423d-42e0-a2af-1e8c585e723c",
35
+ "showInput": false
36
+ },
37
+ "source": [
38
+ "Implicitron's components are all based on a unified hierarchical configuration system. \n",
39
+ "This allows configurable variables and all defaults to be defined separately for each new component.\n",
40
+ "All configs relevant to an experiment are then automatically composed into a single configuration file that fully specifies the experiment.\n",
41
+ "An especially important feature is extension points where users can insert their own sub-classes of Implicitron's base components.\n",
42
+ "\n",
43
+ "The file which defines this system is [here](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/implicitron/tools/config.py) in the PyTorch3D repo.\n",
44
+ "The Implicitron volumes tutorial contains a simple example of using the config system.\n",
45
+ "This tutorial provides detailed hands-on experience in using and modifying Implicitron's configurable components.\n"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "markdown",
50
+ "metadata": {
51
+ "customInput": null,
52
+ "originalKey": "fde300a2-99cb-4d52-9d5b-4464a2083e0b",
53
+ "showInput": false
54
+ },
55
+ "source": [
56
+ "## 0. Install and import modules\n",
57
+ "\n",
58
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": null,
64
+ "metadata": {
65
+ "customInput": null,
66
+ "customOutput": null,
67
+ "originalKey": "ad6e94a7-e114-43d3-b038-a5210c7d34c9",
68
+ "showInput": true
69
+ },
70
+ "outputs": [],
71
+ "source": [
72
+ "import os\n",
73
+ "import sys\n",
74
+ "import torch\n",
75
+ "import subprocess\n",
76
+ "need_pytorch3d=False\n",
77
+ "try:\n",
78
+ " import pytorch3d\n",
79
+ "except ModuleNotFoundError:\n",
80
+ " need_pytorch3d=True\n",
81
+ "if need_pytorch3d:\n",
82
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
83
+ " version_str=\"\".join([\n",
84
+ " f\"py3{sys.version_info.minor}_cu\",\n",
85
+ " torch.version.cuda.replace(\".\",\"\"),\n",
86
+ " f\"_pyt{pyt_version_str}\"\n",
87
+ " ])\n",
88
+ " !pip install iopath\n",
89
+ " if sys.platform.startswith(\"linux\"):\n",
90
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
91
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
92
+ " pip_list = !pip freeze\n",
93
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
94
+ " if need_pytorch3d:\n",
95
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
96
+ "if need_pytorch3d:\n",
97
+ " print(\"Installing PyTorch3D from source\")\n",
98
+ " !pip install ninja\n",
99
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
100
+ ]
101
+ },
102
+ {
103
+ "attachments": {},
104
+ "cell_type": "markdown",
105
+ "metadata": {
106
+ "customInput": null,
107
+ "originalKey": "609896c0-9e2e-4716-b074-b565f0170e32",
108
+ "showInput": false
109
+ },
110
+ "source": [
111
+ "Ensure omegaconf is installed. If not, run this cell. (It should not be necessary to restart the runtime.)"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": null,
117
+ "metadata": {
118
+ "customInput": null,
119
+ "customOutput": null,
120
+ "originalKey": "d1c1851e-b9f2-4236-93c3-19aa4d63041c",
121
+ "showInput": true
122
+ },
123
+ "outputs": [],
124
+ "source": [
125
+ "!pip install omegaconf"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "execution_count": null,
131
+ "metadata": {
132
+ "code_folding": [],
133
+ "collapsed": false,
134
+ "customOutput": null,
135
+ "executionStartTime": 1659465468717,
136
+ "executionStopTime": 1659465468738,
137
+ "hidden_ranges": [],
138
+ "originalKey": "5ac7ef23-b74c-46b2-b8d3-799524d7ba4f",
139
+ "requestMsgId": "5ac7ef23-b74c-46b2-b8d3-799524d7ba4f"
140
+ },
141
+ "outputs": [],
142
+ "source": [
143
+ "from dataclasses import dataclass\n",
144
+ "from typing import Optional, Tuple\n",
145
+ "\n",
146
+ "import torch\n",
147
+ "from omegaconf import DictConfig, OmegaConf\n",
148
+ "from pytorch3d.implicitron.tools.config import (\n",
149
+ " Configurable,\n",
150
+ " ReplaceableBase,\n",
151
+ " expand_args_fields,\n",
152
+ " get_default_args,\n",
153
+ " registry,\n",
154
+ " run_auto_creation,\n",
155
+ ")"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "metadata": {
161
+ "customInput": null,
162
+ "originalKey": "a638bf90-eb6b-424d-b53d-eae11954a717",
163
+ "showInput": false
164
+ },
165
+ "source": [
166
+ "## 1. Introducing dataclasses \n",
167
+ "\n",
168
+ "[Type hints](https://docs.python.org/3/library/typing.html) give a taxonomy of types in Python. [Dataclasses](https://docs.python.org/3/library/dataclasses.html) let you create a class based on a list of members which have names, types and possibly default values. The `__init__` function is created automatically, and calls a `__post_init__` function if present as a final step. For example"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "metadata": {
175
+ "collapsed": false,
176
+ "customInput": null,
177
+ "customOutput": null,
178
+ "executionStartTime": 1659454972732,
179
+ "executionStopTime": 1659454972739,
180
+ "originalKey": "71eaad5e-e198-492e-8610-24b0da9dd4ae",
181
+ "requestMsgId": "71eaad5e-e198-492e-8610-24b0da9dd4ae",
182
+ "showInput": true
183
+ },
184
+ "outputs": [],
185
+ "source": [
186
+ "@dataclass\n",
187
+ "class MyDataclass:\n",
188
+ " a: int\n",
189
+ " b: int = 8\n",
190
+ " c: Optional[Tuple[int, ...]] = None\n",
191
+ "\n",
192
+ " def __post_init__(self):\n",
193
+ " print(f\"created with a = {self.a}\")\n",
194
+ " self.d = 2 * self.b"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "metadata": {
201
+ "collapsed": false,
202
+ "customInput": null,
203
+ "customOutput": null,
204
+ "executionStartTime": 1659454973051,
205
+ "executionStopTime": 1659454973077,
206
+ "originalKey": "83202a18-a3d3-44ec-a62d-b3360a302645",
207
+ "requestMsgId": "83202a18-a3d3-44ec-a62d-b3360a302645",
208
+ "showInput": true
209
+ },
210
+ "outputs": [],
211
+ "source": [
212
+ "my_dataclass_instance = MyDataclass(a=18)\n",
213
+ "assert my_dataclass_instance.d == 16"
214
+ ]
215
+ },
216
+ {
217
+ "attachments": {},
218
+ "cell_type": "markdown",
219
+ "metadata": {
220
+ "customInput": null,
221
+ "originalKey": "b67ccb9f-dc6c-4994-9b99-b5a1bcfebd70",
222
+ "showInput": false
223
+ },
224
+ "source": [
225
+ "👷 Note that the `dataclass` decorator here is function which modifies the definition of the class itself.\n",
226
+ "It runs immediately after the definition.\n",
227
+ "Our config system requires that implicitron library code contains classes whose modified versions need to be aware of user-defined implementations.\n",
228
+ "Therefore we need the modification of the class to be delayed. We don't use a decorator.\n"
229
+ ]
230
+ },
231
+ {
232
+ "attachments": {},
233
+ "cell_type": "markdown",
234
+ "metadata": {
235
+ "customInput": null,
236
+ "originalKey": "3e90f664-99df-4387-9c45-a1ad7939ef3a",
237
+ "showInput": false
238
+ },
239
+ "source": [
240
+ "## 2. Introducing omegaconf and OmegaConf.structured\n",
241
+ "\n",
242
+ "The [omegaconf](https://github.com/omry/omegaconf/) library provides a DictConfig class which is like a `dict` with str keys, but with extra features for ease-of-use as a configuration system."
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": null,
248
+ "metadata": {
249
+ "collapsed": false,
250
+ "customInput": null,
251
+ "customOutput": null,
252
+ "executionStartTime": 1659451341683,
253
+ "executionStopTime": 1659451341690,
254
+ "originalKey": "81c73c9b-27ee-4aab-b55e-fb0dd67fe174",
255
+ "requestMsgId": "81c73c9b-27ee-4aab-b55e-fb0dd67fe174",
256
+ "showInput": true
257
+ },
258
+ "outputs": [],
259
+ "source": [
260
+ "dc = DictConfig({\"a\": 2, \"b\": True, \"c\": None, \"d\": \"hello\"})\n",
261
+ "assert dc.a == dc[\"a\"] == 2"
262
+ ]
263
+ },
264
+ {
265
+ "attachments": {},
266
+ "cell_type": "markdown",
267
+ "metadata": {
268
+ "customInput": null,
269
+ "originalKey": "3b5b76a9-4b76-4784-96ff-2a1212e48e48",
270
+ "showInput": false
271
+ },
272
+ "source": [
273
+ "OmegaConf has a serialization to and from yaml. The [Hydra](https://hydra.cc/) library relies on this for its configuration files."
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "execution_count": null,
279
+ "metadata": {
280
+ "collapsed": false,
281
+ "customInput": null,
282
+ "customOutput": null,
283
+ "executionStartTime": 1659451411835,
284
+ "executionStopTime": 1659451411936,
285
+ "originalKey": "d7a25ec1-caea-46bc-a1da-4b1f040c4b61",
286
+ "requestMsgId": "d7a25ec1-caea-46bc-a1da-4b1f040c4b61",
287
+ "showInput": true
288
+ },
289
+ "outputs": [],
290
+ "source": [
291
+ "print(OmegaConf.to_yaml(dc))\n",
292
+ "assert OmegaConf.create(OmegaConf.to_yaml(dc)) == dc"
293
+ ]
294
+ },
295
+ {
296
+ "attachments": {},
297
+ "cell_type": "markdown",
298
+ "metadata": {
299
+ "customInput": null,
300
+ "originalKey": "777fecdd-8bf6-4fd8-827b-cb8af5477fa8",
301
+ "showInput": false
302
+ },
303
+ "source": [
304
+ "OmegaConf.structured provides a DictConfig from a dataclass or instance of a dataclass. Unlike a normal DictConfig, it is type-checked and only known keys can be added."
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "execution_count": null,
310
+ "metadata": {
311
+ "collapsed": false,
312
+ "customInput": null,
313
+ "customOutput": null,
314
+ "executionStartTime": 1659455098879,
315
+ "executionStopTime": 1659455098900,
316
+ "originalKey": "de36efb4-0b08-4fb8-bb3a-be1b2c0cd162",
317
+ "requestMsgId": "de36efb4-0b08-4fb8-bb3a-be1b2c0cd162",
318
+ "showInput": true
319
+ },
320
+ "outputs": [],
321
+ "source": [
322
+ "structured = OmegaConf.structured(MyDataclass)\n",
323
+ "assert isinstance(structured, DictConfig)\n",
324
+ "print(structured)\n",
325
+ "print()\n",
326
+ "print(OmegaConf.to_yaml(structured))"
327
+ ]
328
+ },
329
+ {
330
+ "attachments": {},
331
+ "cell_type": "markdown",
332
+ "metadata": {
333
+ "customInput": null,
334
+ "originalKey": "be4446da-e536-4139-9ba3-37669a5b5e61",
335
+ "showInput": false
336
+ },
337
+ "source": [
338
+ "`structured` knows it is missing a value for `a`."
339
+ ]
340
+ },
341
+ {
342
+ "attachments": {},
343
+ "cell_type": "markdown",
344
+ "metadata": {
345
+ "customInput": null,
346
+ "originalKey": "864811e8-1a75-4932-a85e-f681b0541ae9",
347
+ "showInput": false
348
+ },
349
+ "source": [
350
+ "Such an object has members compatible with the dataclass, so an initialisation can be performed as follows."
351
+ ]
352
+ },
353
+ {
354
+ "cell_type": "code",
355
+ "execution_count": null,
356
+ "metadata": {
357
+ "collapsed": false,
358
+ "customInput": null,
359
+ "customOutput": null,
360
+ "executionStartTime": 1659455580491,
361
+ "executionStopTime": 1659455580501,
362
+ "originalKey": "eb88aaa0-c22f-4ffb-813a-ca957b490acb",
363
+ "requestMsgId": "eb88aaa0-c22f-4ffb-813a-ca957b490acb",
364
+ "showInput": true
365
+ },
366
+ "outputs": [],
367
+ "source": [
368
+ "structured.a = 21\n",
369
+ "my_dataclass_instance2 = MyDataclass(**structured)\n",
370
+ "print(my_dataclass_instance2)"
371
+ ]
372
+ },
373
+ {
374
+ "attachments": {},
375
+ "cell_type": "markdown",
376
+ "metadata": {
377
+ "customInput": null,
378
+ "originalKey": "2d08c81c-9d18-4de9-8464-0da2d89f94f3",
379
+ "showInput": false
380
+ },
381
+ "source": [
382
+ "You can also call OmegaConf.structured on an instance."
383
+ ]
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "execution_count": null,
388
+ "metadata": {
389
+ "collapsed": false,
390
+ "customInput": null,
391
+ "customOutput": null,
392
+ "executionStartTime": 1659455594700,
393
+ "executionStopTime": 1659455594737,
394
+ "originalKey": "5e469bac-32a4-475d-9c09-8b64ba3f2155",
395
+ "requestMsgId": "5e469bac-32a4-475d-9c09-8b64ba3f2155",
396
+ "showInput": true
397
+ },
398
+ "outputs": [],
399
+ "source": [
400
+ "structured_from_instance = OmegaConf.structured(my_dataclass_instance)\n",
401
+ "my_dataclass_instance3 = MyDataclass(**structured_from_instance)\n",
402
+ "print(my_dataclass_instance3)"
403
+ ]
404
+ },
405
+ {
406
+ "attachments": {},
407
+ "cell_type": "markdown",
408
+ "metadata": {
409
+ "collapsed": false,
410
+ "customInput": null,
411
+ "customOutput": null,
412
+ "executionStartTime": 1659452594203,
413
+ "executionStopTime": 1659452594333,
414
+ "originalKey": "2ed559e3-8552-465a-938f-30c72a321184",
415
+ "requestMsgId": "2ed559e3-8552-465a-938f-30c72a321184",
416
+ "showInput": false
417
+ },
418
+ "source": [
419
+ "## 3. Our approach to OmegaConf.structured\n",
420
+ "\n",
421
+ "We provide functions which are equivalent to `OmegaConf.structured` but support more features. \n",
422
+ "To achieve the above using our functions, the following is used.\n",
423
+ "Note that we indicate configurable classes using a special base class `Configurable`, not a decorator."
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "metadata": {
430
+ "collapsed": false,
431
+ "customInput": null,
432
+ "customOutput": null,
433
+ "executionStartTime": 1659454053323,
434
+ "executionStopTime": 1659454061629,
435
+ "originalKey": "9888afbd-e617-4596-ab7a-fc1073f58656",
436
+ "requestMsgId": "9888afbd-e617-4596-ab7a-fc1073f58656",
437
+ "showInput": true
438
+ },
439
+ "outputs": [],
440
+ "source": [
441
+ "class MyConfigurable(Configurable):\n",
442
+ " a: int\n",
443
+ " b: int = 8\n",
444
+ " c: Optional[Tuple[int, ...]] = None\n",
445
+ "\n",
446
+ " def __post_init__(self):\n",
447
+ " print(f\"created with a = {self.a}\")\n",
448
+ " self.d = 2 * self.b"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "code",
453
+ "execution_count": null,
454
+ "metadata": {
455
+ "collapsed": false,
456
+ "customInput": null,
457
+ "customOutput": null,
458
+ "executionStartTime": 1659454784912,
459
+ "executionStopTime": 1659454784928,
460
+ "originalKey": "e43155b4-3da5-4df1-a2f5-da1d0369eec9",
461
+ "requestMsgId": "e43155b4-3da5-4df1-a2f5-da1d0369eec9",
462
+ "showInput": true
463
+ },
464
+ "outputs": [],
465
+ "source": [
466
+ "# The expand_args_fields function modifies the class like @dataclasses.dataclass.\n",
467
+ "# If it has not been called on a Configurable object before it has been instantiated, it will\n",
468
+ "# be called automatically.\n",
469
+ "expand_args_fields(MyConfigurable)\n",
470
+ "my_configurable_instance = MyConfigurable(a=18)\n",
471
+ "assert my_configurable_instance.d == 16"
472
+ ]
473
+ },
474
+ {
475
+ "cell_type": "code",
476
+ "execution_count": null,
477
+ "metadata": {
478
+ "collapsed": false,
479
+ "customInput": null,
480
+ "customOutput": null,
481
+ "executionStartTime": 1659460669541,
482
+ "executionStopTime": 1659460669566,
483
+ "originalKey": "96eaae18-dce4-4ee1-b451-1466fea51b9f",
484
+ "requestMsgId": "96eaae18-dce4-4ee1-b451-1466fea51b9f",
485
+ "showInput": true
486
+ },
487
+ "outputs": [],
488
+ "source": [
489
+ "# get_default_args also calls expand_args_fields automatically\n",
490
+ "our_structured = get_default_args(MyConfigurable)\n",
491
+ "assert isinstance(our_structured, DictConfig)\n",
492
+ "print(OmegaConf.to_yaml(our_structured))"
493
+ ]
494
+ },
495
+ {
496
+ "cell_type": "code",
497
+ "execution_count": null,
498
+ "metadata": {
499
+ "collapsed": false,
500
+ "customInput": null,
501
+ "customOutput": null,
502
+ "executionStartTime": 1659460454020,
503
+ "executionStopTime": 1659460454032,
504
+ "originalKey": "359f7925-68de-42cd-bd34-79a099b1c210",
505
+ "requestMsgId": "359f7925-68de-42cd-bd34-79a099b1c210",
506
+ "showInput": true
507
+ },
508
+ "outputs": [],
509
+ "source": [
510
+ "our_structured.a = 21\n",
511
+ "print(MyConfigurable(**our_structured))"
512
+ ]
513
+ },
514
+ {
515
+ "attachments": {},
516
+ "cell_type": "markdown",
517
+ "metadata": {
518
+ "collapsed": false,
519
+ "customInput": null,
520
+ "customOutput": null,
521
+ "executionStartTime": 1659460599142,
522
+ "executionStopTime": 1659460599149,
523
+ "originalKey": "eac7d385-9365-4098-acf9-4f0a0dbdcb85",
524
+ "requestMsgId": "eac7d385-9365-4098-acf9-4f0a0dbdcb85",
525
+ "showInput": false
526
+ },
527
+ "source": [
528
+ "## 4. First enhancement: nested types 🪺\n",
529
+ "\n",
530
+ "Our system allows Configurable classes to contain each other. \n",
531
+ "One thing to remember: add a call to `run_auto_creation` in `__post_init__`."
532
+ ]
533
+ },
534
+ {
535
+ "cell_type": "code",
536
+ "execution_count": null,
537
+ "metadata": {
538
+ "collapsed": false,
539
+ "customInput": null,
540
+ "customOutput": null,
541
+ "executionStartTime": 1659465752418,
542
+ "executionStopTime": 1659465752976,
543
+ "originalKey": "9bd70ee5-4ec1-4021-bce5-9638b5088c0a",
544
+ "requestMsgId": "9bd70ee5-4ec1-4021-bce5-9638b5088c0a",
545
+ "showInput": true
546
+ },
547
+ "outputs": [],
548
+ "source": [
549
+ "class Inner(Configurable):\n",
550
+ " a: int = 8\n",
551
+ " b: bool = True\n",
552
+ " c: Tuple[int, ...] = (2, 3, 4, 6)\n",
553
+ "\n",
554
+ "\n",
555
+ "class Outer(Configurable):\n",
556
+ " inner: Inner\n",
557
+ " x: str = \"hello\"\n",
558
+ " xx: bool = False\n",
559
+ "\n",
560
+ " def __post_init__(self):\n",
561
+ " run_auto_creation(self)"
562
+ ]
563
+ },
564
+ {
565
+ "cell_type": "code",
566
+ "execution_count": null,
567
+ "metadata": {
568
+ "collapsed": false,
569
+ "customInput": null,
570
+ "customOutput": null,
571
+ "executionStartTime": 1659465762326,
572
+ "executionStopTime": 1659465762339,
573
+ "originalKey": "9f2b9f98-b54b-46cc-9b02-9e902cb279e7",
574
+ "requestMsgId": "9f2b9f98-b54b-46cc-9b02-9e902cb279e7",
575
+ "showInput": true
576
+ },
577
+ "outputs": [],
578
+ "source": [
579
+ "outer_dc = get_default_args(Outer)\n",
580
+ "print(OmegaConf.to_yaml(outer_dc))"
581
+ ]
582
+ },
583
+ {
584
+ "cell_type": "code",
585
+ "execution_count": null,
586
+ "metadata": {
587
+ "collapsed": false,
588
+ "customInput": null,
589
+ "customOutput": null,
590
+ "executionStartTime": 1659465772894,
591
+ "executionStopTime": 1659465772911,
592
+ "originalKey": "0254204b-8c7a-4d40-bba6-5132185f63d7",
593
+ "requestMsgId": "0254204b-8c7a-4d40-bba6-5132185f63d7",
594
+ "showInput": true
595
+ },
596
+ "outputs": [],
597
+ "source": [
598
+ "outer = Outer(**outer_dc)\n",
599
+ "assert isinstance(outer, Outer)\n",
600
+ "assert isinstance(outer.inner, Inner)\n",
601
+ "print(vars(outer))\n",
602
+ "print(outer.inner)"
603
+ ]
604
+ },
605
+ {
606
+ "attachments": {},
607
+ "cell_type": "markdown",
608
+ "metadata": {
609
+ "customInput": null,
610
+ "originalKey": "44a78c13-ec92-4a87-808a-c4674b320c22",
611
+ "showInput": false
612
+ },
613
+ "source": [
614
+ "Note how inner_args is an extra member of outer. `run_auto_creation(self)` is equivalent to\n",
615
+ "```\n",
616
+ " self.inner = Inner(**self.inner_args)\n",
617
+ "```"
618
+ ]
619
+ },
620
+ {
621
+ "attachments": {},
622
+ "cell_type": "markdown",
623
+ "metadata": {
624
+ "collapsed": false,
625
+ "customInput": null,
626
+ "customOutput": null,
627
+ "executionStartTime": 1659461071129,
628
+ "executionStopTime": 1659461071137,
629
+ "originalKey": "af0ec78b-7888-4b0d-9346-63d970d43293",
630
+ "requestMsgId": "af0ec78b-7888-4b0d-9346-63d970d43293",
631
+ "showInput": false
632
+ },
633
+ "source": [
634
+ "## 5. Second enhancement: pluggable/replaceable components 🔌\n",
635
+ "\n",
636
+ "If a class uses `ReplaceableBase` as a base class instead of `Configurable`, we call it a replaceable.\n",
637
+ "It indicates that it is designed for child classes to use in its place.\n",
638
+ "We might use `NotImplementedError` to indicate functionality which subclasses are expected to implement.\n",
639
+ "The system maintains a global `registry` containing subclasses of each ReplaceableBase.\n",
640
+ "The subclasses register themselves with it with a decorator.\n",
641
+ "\n",
642
+ "A configurable class (i.e. a class which uses our system, i.e. a child of `Configurable` or `ReplaceableBase`) which contains a ReplaceableBase must also \n",
643
+ "contain a corresponding class_type field of type `str` which indicates which concrete child class to use."
644
+ ]
645
+ },
646
+ {
647
+ "cell_type": "code",
648
+ "execution_count": null,
649
+ "metadata": {
650
+ "collapsed": false,
651
+ "customInput": null,
652
+ "customOutput": null,
653
+ "executionStartTime": 1659463453457,
654
+ "executionStopTime": 1659463453467,
655
+ "originalKey": "f2898703-d147-4394-978e-fc7f1f559395",
656
+ "requestMsgId": "f2898703-d147-4394-978e-fc7f1f559395",
657
+ "showInput": true
658
+ },
659
+ "outputs": [],
660
+ "source": [
661
+ "class InnerBase(ReplaceableBase):\n",
662
+ " def say_something(self):\n",
663
+ " raise NotImplementedError\n",
664
+ "\n",
665
+ "\n",
666
+ "@registry.register\n",
667
+ "class Inner1(InnerBase):\n",
668
+ " a: int = 1\n",
669
+ " b: str = \"h\"\n",
670
+ "\n",
671
+ " def say_something(self):\n",
672
+ " print(\"hello from an Inner1\")\n",
673
+ "\n",
674
+ "\n",
675
+ "@registry.register\n",
676
+ "class Inner2(InnerBase):\n",
677
+ " a: int = 2\n",
678
+ "\n",
679
+ " def say_something(self):\n",
680
+ " print(\"hello from an Inner2\")"
681
+ ]
682
+ },
683
+ {
684
+ "cell_type": "code",
685
+ "execution_count": null,
686
+ "metadata": {
687
+ "collapsed": false,
688
+ "customInput": null,
689
+ "customOutput": null,
690
+ "executionStartTime": 1659463453514,
691
+ "executionStopTime": 1659463453592,
692
+ "originalKey": "6f171599-51ee-440f-82d7-a59f84d24624",
693
+ "requestMsgId": "6f171599-51ee-440f-82d7-a59f84d24624",
694
+ "showInput": true
695
+ },
696
+ "outputs": [],
697
+ "source": [
698
+ "class Out(Configurable):\n",
699
+ " inner: InnerBase\n",
700
+ " inner_class_type: str = \"Inner1\"\n",
701
+ " x: int = 19\n",
702
+ "\n",
703
+ " def __post_init__(self):\n",
704
+ " run_auto_creation(self)\n",
705
+ "\n",
706
+ " def talk(self):\n",
707
+ " self.inner.say_something()"
708
+ ]
709
+ },
710
+ {
711
+ "cell_type": "code",
712
+ "execution_count": null,
713
+ "metadata": {
714
+ "collapsed": false,
715
+ "customInput": null,
716
+ "customOutput": null,
717
+ "executionStartTime": 1659463191360,
718
+ "executionStopTime": 1659463191428,
719
+ "originalKey": "7abaecec-96e6-44df-8c8d-69c36a14b913",
720
+ "requestMsgId": "7abaecec-96e6-44df-8c8d-69c36a14b913",
721
+ "showInput": true
722
+ },
723
+ "outputs": [],
724
+ "source": [
725
+ "Out_dc = get_default_args(Out)\n",
726
+ "print(OmegaConf.to_yaml(Out_dc))"
727
+ ]
728
+ },
729
+ {
730
+ "cell_type": "code",
731
+ "execution_count": null,
732
+ "metadata": {
733
+ "collapsed": false,
734
+ "customInput": null,
735
+ "customOutput": null,
736
+ "executionStartTime": 1659463192717,
737
+ "executionStopTime": 1659463192754,
738
+ "originalKey": "c82dc2ca-ba8f-4a44-aed3-43f6b52ec28c",
739
+ "requestMsgId": "c82dc2ca-ba8f-4a44-aed3-43f6b52ec28c",
740
+ "showInput": true
741
+ },
742
+ "outputs": [],
743
+ "source": [
744
+ "Out_dc.inner_class_type = \"Inner2\"\n",
745
+ "out = Out(**Out_dc)\n",
746
+ "print(out.inner)"
747
+ ]
748
+ },
749
+ {
750
+ "cell_type": "code",
751
+ "execution_count": null,
752
+ "metadata": {
753
+ "collapsed": false,
754
+ "customInput": null,
755
+ "customOutput": null,
756
+ "executionStartTime": 1659463193751,
757
+ "executionStopTime": 1659463193791,
758
+ "originalKey": "aa0e1b04-963a-4724-81b7-5748b598b541",
759
+ "requestMsgId": "aa0e1b04-963a-4724-81b7-5748b598b541",
760
+ "showInput": true
761
+ },
762
+ "outputs": [],
763
+ "source": [
764
+ "out.talk()"
765
+ ]
766
+ },
767
+ {
768
+ "attachments": {},
769
+ "cell_type": "markdown",
770
+ "metadata": {
771
+ "customInput": null,
772
+ "originalKey": "4f78a56c-39cd-4563-a97e-041e5f360f6b",
773
+ "showInput": false
774
+ },
775
+ "source": [
776
+ "Note in this case there are many `args` members. It is usually fine to ignore them in the code. They are needed for the config."
777
+ ]
778
+ },
779
+ {
780
+ "cell_type": "code",
781
+ "execution_count": null,
782
+ "metadata": {
783
+ "collapsed": false,
784
+ "customInput": null,
785
+ "customOutput": null,
786
+ "executionStartTime": 1659462145294,
787
+ "executionStopTime": 1659462145307,
788
+ "originalKey": "ce7069d5-a813-4286-a7cd-6ff40362105a",
789
+ "requestMsgId": "ce7069d5-a813-4286-a7cd-6ff40362105a",
790
+ "showInput": true
791
+ },
792
+ "outputs": [],
793
+ "source": [
794
+ "print(vars(out))"
795
+ ]
796
+ },
797
+ {
798
+ "attachments": {},
799
+ "cell_type": "markdown",
800
+ "metadata": {
801
+ "collapsed": false,
802
+ "customInput": null,
803
+ "customOutput": null,
804
+ "executionStartTime": 1659462231114,
805
+ "executionStopTime": 1659462231130,
806
+ "originalKey": "c7f051ff-c264-4b89-80dc-36cf179aafaf",
807
+ "requestMsgId": "c7f051ff-c264-4b89-80dc-36cf179aafaf",
808
+ "showInput": false
809
+ },
810
+ "source": [
811
+ "## 6. Example with torch.nn.Module 🔥\n",
812
+ "Typically in implicitron, we use this system in combination with [`Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)s. \n",
813
+ "Note in this case it is necessary to call `Module.__init__` explicitly in `__post_init__`."
814
+ ]
815
+ },
816
+ {
817
+ "cell_type": "code",
818
+ "execution_count": null,
819
+ "metadata": {
820
+ "collapsed": false,
821
+ "customInput": null,
822
+ "customOutput": null,
823
+ "executionStartTime": 1659462645018,
824
+ "executionStopTime": 1659462645037,
825
+ "originalKey": "42d210d6-09e0-4daf-8ccb-411d30f268f4",
826
+ "requestMsgId": "42d210d6-09e0-4daf-8ccb-411d30f268f4",
827
+ "showInput": true
828
+ },
829
+ "outputs": [],
830
+ "source": [
831
+ "class MyLinear(torch.nn.Module, Configurable):\n",
832
+ " d_in: int = 2\n",
833
+ " d_out: int = 200\n",
834
+ "\n",
835
+ " def __post_init__(self):\n",
836
+ " super().__init__()\n",
837
+ " self.linear = torch.nn.Linear(in_features=self.d_in, out_features=self.d_out)\n",
838
+ "\n",
839
+ " def forward(self, x):\n",
840
+ " return self.linear.forward(x)"
841
+ ]
842
+ },
843
+ {
844
+ "cell_type": "code",
845
+ "execution_count": null,
846
+ "metadata": {
847
+ "collapsed": false,
848
+ "customInput": null,
849
+ "customOutput": null,
850
+ "executionStartTime": 1659462692309,
851
+ "executionStopTime": 1659462692346,
852
+ "originalKey": "546781fe-5b95-4e48-9cb5-34a634a31313",
853
+ "requestMsgId": "546781fe-5b95-4e48-9cb5-34a634a31313",
854
+ "showInput": true
855
+ },
856
+ "outputs": [],
857
+ "source": [
858
+ "my_linear = MyLinear()\n",
859
+ "input = torch.zeros(2)\n",
860
+ "output = my_linear(input)\n",
861
+ "print(\"output shape:\", output.shape)"
862
+ ]
863
+ },
864
+ {
865
+ "attachments": {},
866
+ "cell_type": "markdown",
867
+ "metadata": {
868
+ "collapsed": false,
869
+ "customInput": null,
870
+ "customOutput": null,
871
+ "executionStartTime": 1659462738302,
872
+ "executionStopTime": 1659462738419,
873
+ "originalKey": "b6cb71e1-1d54-4e89-a422-0a70772c5c03",
874
+ "requestMsgId": "b6cb71e1-1d54-4e89-a422-0a70772c5c03",
875
+ "showInput": false
876
+ },
877
+ "source": [
878
+ "`my_linear` has all the usual features of a Module.\n",
879
+ "E.g. it can be saved and loaded with `torch.save` and `torch.load`.\n",
880
+ "It has parameters:"
881
+ ]
882
+ },
883
+ {
884
+ "cell_type": "code",
885
+ "execution_count": null,
886
+ "metadata": {
887
+ "collapsed": false,
888
+ "customInput": null,
889
+ "customOutput": null,
890
+ "executionStartTime": 1659462821485,
891
+ "executionStopTime": 1659462821501,
892
+ "originalKey": "47e8c53e-2d2c-4b41-8aa3-65aa3ea8a7d3",
893
+ "requestMsgId": "47e8c53e-2d2c-4b41-8aa3-65aa3ea8a7d3",
894
+ "showInput": true
895
+ },
896
+ "outputs": [],
897
+ "source": [
898
+ "for name, value in my_linear.named_parameters():\n",
899
+ " print(name, value.shape)"
900
+ ]
901
+ },
902
+ {
903
+ "attachments": {},
904
+ "cell_type": "markdown",
905
+ "metadata": {
906
+ "collapsed": false,
907
+ "customInput": null,
908
+ "customOutput": null,
909
+ "executionStartTime": 1659463222379,
910
+ "executionStopTime": 1659463222409,
911
+ "originalKey": "a01f0ea7-55f2-4af9-8e81-45dddf40f13b",
912
+ "requestMsgId": "a01f0ea7-55f2-4af9-8e81-45dddf40f13b",
913
+ "showInput": false
914
+ },
915
+ "source": [
916
+ "## 7. Example of implementing your own pluggable component \n",
917
+ "Let's say I am using a library with `Out` like in section **5** but I want to implement my own child of InnerBase. \n",
918
+ "All I need to do is register its definition, but I need to do this before expand_args_fields is explicitly or implicitly called on Out."
919
+ ]
920
+ },
921
+ {
922
+ "cell_type": "code",
923
+ "execution_count": null,
924
+ "metadata": {
925
+ "collapsed": false,
926
+ "customInput": null,
927
+ "customOutput": null,
928
+ "executionStartTime": 1659463694644,
929
+ "executionStopTime": 1659463694653,
930
+ "originalKey": "d9635511-a52b-43d5-8dae-d5c1a3dd9157",
931
+ "requestMsgId": "d9635511-a52b-43d5-8dae-d5c1a3dd9157",
932
+ "showInput": true
933
+ },
934
+ "outputs": [],
935
+ "source": [
936
+ "@registry.register\n",
937
+ "class UserImplementedInner(InnerBase):\n",
938
+ " a: int = 200\n",
939
+ "\n",
940
+ " def say_something(self):\n",
941
+ " print(\"hello from the user\")"
942
+ ]
943
+ },
944
+ {
945
+ "attachments": {},
946
+ "cell_type": "markdown",
947
+ "metadata": {
948
+ "customInput": null,
949
+ "originalKey": "f1511aa2-56b8-4ed0-a453-17e2bbfeefe7",
950
+ "showInput": false
951
+ },
952
+ "source": [
953
+ "At this point, we need to redefine the class Out. \n",
954
+ "Otherwise if it has already been expanded without UserImplementedInner, then the following would not work,\n",
955
+ "because the implementations known to a class are fixed when it is expanded.\n",
956
+ "\n",
957
+ "If you are running experiments from a script, the thing to remember here is that you must import your own modules, which register your own implementations,\n",
958
+ "before you *use* the library classes."
959
+ ]
960
+ },
961
+ {
962
+ "cell_type": "code",
963
+ "execution_count": null,
964
+ "metadata": {
965
+ "collapsed": false,
966
+ "customInput": null,
967
+ "customOutput": null,
968
+ "executionStartTime": 1659463745967,
969
+ "executionStopTime": 1659463745986,
970
+ "originalKey": "c7bb5a6e-682b-4eb0-a214-e0f5990b9406",
971
+ "requestMsgId": "c7bb5a6e-682b-4eb0-a214-e0f5990b9406",
972
+ "showInput": true
973
+ },
974
+ "outputs": [],
975
+ "source": [
976
+ "class Out(Configurable):\n",
977
+ " inner: InnerBase\n",
978
+ " inner_class_type: str = \"Inner1\"\n",
979
+ " x: int = 19\n",
980
+ "\n",
981
+ " def __post_init__(self):\n",
982
+ " run_auto_creation(self)\n",
983
+ "\n",
984
+ " def talk(self):\n",
985
+ " self.inner.say_something()"
986
+ ]
987
+ },
988
+ {
989
+ "cell_type": "code",
990
+ "execution_count": null,
991
+ "metadata": {
992
+ "collapsed": false,
993
+ "customInput": null,
994
+ "customOutput": null,
995
+ "executionStartTime": 1659463747398,
996
+ "executionStopTime": 1659463747431,
997
+ "originalKey": "b6ecdc86-4b7b-47c6-9f45-a7e557c94979",
998
+ "requestMsgId": "b6ecdc86-4b7b-47c6-9f45-a7e557c94979",
999
+ "showInput": true
1000
+ },
1001
+ "outputs": [],
1002
+ "source": [
1003
+ "out2 = Out(inner_class_type=\"UserImplementedInner\")\n",
1004
+ "print(out2.inner)"
1005
+ ]
1006
+ },
1007
+ {
1008
+ "attachments": {},
1009
+ "cell_type": "markdown",
1010
+ "metadata": {
1011
+ "collapsed": false,
1012
+ "customInput": null,
1013
+ "customOutput": null,
1014
+ "executionStartTime": 1659464033633,
1015
+ "executionStopTime": 1659464033643,
1016
+ "originalKey": "c7fe0df3-da13-40b8-9b06-6b1f37f37bb9",
1017
+ "requestMsgId": "c7fe0df3-da13-40b8-9b06-6b1f37f37bb9",
1018
+ "showInput": false
1019
+ },
1020
+ "source": [
1021
+ "## 8: Example of making a subcomponent pluggable\n",
1022
+ "\n",
1023
+ "Let's look what needs to happen if we have a subcomponent which we make pluggable, to allow users to supply their own."
1024
+ ]
1025
+ },
1026
+ {
1027
+ "cell_type": "code",
1028
+ "execution_count": null,
1029
+ "metadata": {
1030
+ "collapsed": false,
1031
+ "customInput": null,
1032
+ "customOutput": null,
1033
+ "executionStartTime": 1659464709922,
1034
+ "executionStopTime": 1659464709933,
1035
+ "originalKey": "e37227b2-6897-4033-8560-9f2040abdeeb",
1036
+ "requestMsgId": "e37227b2-6897-4033-8560-9f2040abdeeb",
1037
+ "showInput": true
1038
+ },
1039
+ "outputs": [],
1040
+ "source": [
1041
+ "class SubComponent(Configurable):\n",
1042
+ " x: float = 0.25\n",
1043
+ "\n",
1044
+ " def apply(self, a: float) -> float:\n",
1045
+ " return a + self.x\n",
1046
+ "\n",
1047
+ "\n",
1048
+ "class LargeComponent(Configurable):\n",
1049
+ " repeats: int = 4\n",
1050
+ " subcomponent: SubComponent\n",
1051
+ "\n",
1052
+ " def __post_init__(self):\n",
1053
+ " run_auto_creation(self)\n",
1054
+ "\n",
1055
+ " def apply(self, a: float) -> float:\n",
1056
+ " for _ in range(self.repeats):\n",
1057
+ " a = self.subcomponent.apply(a)\n",
1058
+ " return a"
1059
+ ]
1060
+ },
1061
+ {
1062
+ "cell_type": "code",
1063
+ "execution_count": null,
1064
+ "metadata": {
1065
+ "collapsed": false,
1066
+ "customInput": null,
1067
+ "customOutput": null,
1068
+ "executionStartTime": 1659464710339,
1069
+ "executionStopTime": 1659464710459,
1070
+ "originalKey": "cab4c121-350e-443f-9a49-bd542a9735a2",
1071
+ "requestMsgId": "cab4c121-350e-443f-9a49-bd542a9735a2",
1072
+ "showInput": true
1073
+ },
1074
+ "outputs": [],
1075
+ "source": [
1076
+ "large_component = LargeComponent()\n",
1077
+ "assert large_component.apply(3) == 4\n",
1078
+ "print(OmegaConf.to_yaml(LargeComponent))"
1079
+ ]
1080
+ },
1081
+ {
1082
+ "attachments": {},
1083
+ "cell_type": "markdown",
1084
+ "metadata": {
1085
+ "customInput": null,
1086
+ "originalKey": "be60323a-badf-46e4-a259-72cae1391028",
1087
+ "showInput": false
1088
+ },
1089
+ "source": [
1090
+ "Made generic:"
1091
+ ]
1092
+ },
1093
+ {
1094
+ "cell_type": "code",
1095
+ "execution_count": null,
1096
+ "metadata": {
1097
+ "collapsed": false,
1098
+ "customInput": null,
1099
+ "customOutput": null,
1100
+ "executionStartTime": 1659464717226,
1101
+ "executionStopTime": 1659464717261,
1102
+ "originalKey": "fc0d8cdb-4627-4427-b92a-17ac1c1b37b8",
1103
+ "requestMsgId": "fc0d8cdb-4627-4427-b92a-17ac1c1b37b8",
1104
+ "showInput": true
1105
+ },
1106
+ "outputs": [],
1107
+ "source": [
1108
+ "class SubComponentBase(ReplaceableBase):\n",
1109
+ " def apply(self, a: float) -> float:\n",
1110
+ " raise NotImplementedError\n",
1111
+ "\n",
1112
+ "\n",
1113
+ "@registry.register\n",
1114
+ "class SubComponent(SubComponentBase):\n",
1115
+ " x: float = 0.25\n",
1116
+ "\n",
1117
+ " def apply(self, a: float) -> float:\n",
1118
+ " return a + self.x\n",
1119
+ "\n",
1120
+ "\n",
1121
+ "class LargeComponent(Configurable):\n",
1122
+ " repeats: int = 4\n",
1123
+ " subcomponent: SubComponentBase\n",
1124
+ " subcomponent_class_type: str = \"SubComponent\"\n",
1125
+ "\n",
1126
+ " def __post_init__(self):\n",
1127
+ " run_auto_creation(self)\n",
1128
+ "\n",
1129
+ " def apply(self, a: float) -> float:\n",
1130
+ " for _ in range(self.repeats):\n",
1131
+ " a = self.subcomponent.apply(a)\n",
1132
+ " return a"
1133
+ ]
1134
+ },
1135
+ {
1136
+ "cell_type": "code",
1137
+ "execution_count": null,
1138
+ "metadata": {
1139
+ "collapsed": false,
1140
+ "customInput": null,
1141
+ "customOutput": null,
1142
+ "executionStartTime": 1659464725473,
1143
+ "executionStopTime": 1659464725587,
1144
+ "originalKey": "bbc3d321-6b49-4356-be75-1a173b1fc3a5",
1145
+ "requestMsgId": "bbc3d321-6b49-4356-be75-1a173b1fc3a5",
1146
+ "showInput": true
1147
+ },
1148
+ "outputs": [],
1149
+ "source": [
1150
+ "large_component = LargeComponent()\n",
1151
+ "assert large_component.apply(3) == 4\n",
1152
+ "print(OmegaConf.to_yaml(LargeComponent))"
1153
+ ]
1154
+ },
1155
+ {
1156
+ "attachments": {},
1157
+ "cell_type": "markdown",
1158
+ "metadata": {
1159
+ "collapsed": false,
1160
+ "customInput": null,
1161
+ "customOutput": null,
1162
+ "executionStartTime": 1659464672680,
1163
+ "executionStopTime": 1659464673231,
1164
+ "originalKey": "5115453a-1d96-4022-97e7-46433e6dcf60",
1165
+ "requestMsgId": "5115453a-1d96-4022-97e7-46433e6dcf60",
1166
+ "showInput": false
1167
+ },
1168
+ "source": [
1169
+ "The following things had to change:\n",
1170
+ "* The base class SubComponentBase was defined.\n",
1171
+ "* SubComponent gained a `@registry.register` decoration and had its base class changed to the new one.\n",
1172
+ "* `subcomponent_class_type` was added as a member of the outer class.\n",
1173
+ "* In any saved configuration yaml files, the key `subcomponent_args` had to be changed to `subcomponent_SubComponent_args`."
1174
+ ]
1175
+ },
1176
+ {
1177
+ "attachments": {},
1178
+ "cell_type": "markdown",
1179
+ "metadata": {
1180
+ "collapsed": false,
1181
+ "customInput": null,
1182
+ "customOutput": null,
1183
+ "executionStartTime": 1659462041307,
1184
+ "executionStopTime": 1659462041637,
1185
+ "originalKey": "0739269e-5c0e-4551-b06f-f4aab386ba54",
1186
+ "requestMsgId": "0739269e-5c0e-4551-b06f-f4aab386ba54",
1187
+ "showInput": false
1188
+ },
1189
+ "source": [
1190
+ "## Appendix: gotchas ⚠️\n",
1191
+ "\n",
1192
+ "* Omitting to define `__post_init__` or not calling `run_auto_creation` in it.\n",
1193
+ "* Omitting a type annotation on a field. For example, writing \n",
1194
+ "```\n",
1195
+ " subcomponent_class_type = \"SubComponent\"\n",
1196
+ "```\n",
1197
+ "instead of \n",
1198
+ "```\n",
1199
+ " subcomponent_class_type: str = \"SubComponent\"\n",
1200
+ "```\n",
1201
+ "\n"
1202
+ ]
1203
+ }
1204
+ ],
1205
+ "metadata": {
1206
+ "bento_stylesheets": {
1207
+ "bento/extensions/flow/main.css": true,
1208
+ "bento/extensions/kernel_selector/main.css": true,
1209
+ "bento/extensions/kernel_ui/main.css": true,
1210
+ "bento/extensions/new_kernel/main.css": true,
1211
+ "bento/extensions/system_usage/main.css": true,
1212
+ "bento/extensions/theme/main.css": true
1213
+ },
1214
+ "captumWidgetMessage": {},
1215
+ "dataExplorerConfig": {},
1216
+ "kernelspec": {
1217
+ "display_name": "pytorch3d",
1218
+ "language": "python",
1219
+ "metadata": {
1220
+ "cinder_runtime": false,
1221
+ "fbpkg_supported": true,
1222
+ "is_prebuilt": true,
1223
+ "kernel_name": "bento_kernel_pytorch3d",
1224
+ "nightly_builds": true
1225
+ },
1226
+ "name": "bento_kernel_pytorch3d"
1227
+ },
1228
+ "language_info": {
1229
+ "codemirror_mode": {
1230
+ "name": "ipython",
1231
+ "version": 3
1232
+ },
1233
+ "file_extension": ".py",
1234
+ "mimetype": "text/x-python",
1235
+ "name": "python",
1236
+ "nbconvert_exporter": "python",
1237
+ "pygments_lexer": "ipython3"
1238
+ },
1239
+ "last_base_url": "https://9177.od.fbinfra.net:443/",
1240
+ "last_kernel_id": "90755407-3729-46f4-ab67-ff2cb1daa5cb",
1241
+ "last_msg_id": "f61034eb-826226915ad9548ffbe495ba_6317",
1242
+ "last_server_session_id": "d6b46f14-cee7-44c1-8c51-39a38a4ea4c2",
1243
+ "outputWidgetContext": {}
1244
+ },
1245
+ "nbformat": 4,
1246
+ "nbformat_minor": 2
1247
+ }
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_volumes.ipynb ADDED
@@ -0,0 +1,902 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "collapsed": false,
8
+ "customInput": null,
9
+ "customOutput": null,
10
+ "executionStartTime": 1659619824914,
11
+ "executionStopTime": 1659619825485,
12
+ "originalKey": "d38652e8-200a-413c-a36a-f4d349b78a9d",
13
+ "requestMsgId": "641de8aa-0e42-4446-9304-c160a2d226bf",
14
+ "showInput": true
15
+ },
16
+ "outputs": [],
17
+ "source": [
18
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
19
+ ]
20
+ },
21
+ {
22
+ "attachments": {},
23
+ "cell_type": "markdown",
24
+ "metadata": {
25
+ "customInput": null,
26
+ "originalKey": "a48a9dcf-e80f-474b-a0c4-2c9a765b15c5",
27
+ "showInput": false
28
+ },
29
+ "source": [
30
+ "# A simple model using Implicitron\n",
31
+ "\n",
32
+ "In this demo, we use the VolumeRenderer from PyTorch3D as a custom implicit function in Implicitron. We will see\n",
33
+ "* some of the main objects in Implicitron\n",
34
+ "* how to plug in a custom part of a model"
35
+ ]
36
+ },
37
+ {
38
+ "attachments": {},
39
+ "cell_type": "markdown",
40
+ "metadata": {
41
+ "customInput": null,
42
+ "originalKey": "51337c0e-ad27-4b75-ad6a-737dca5d7b95",
43
+ "showInput": false
44
+ },
45
+ "source": [
46
+ "## 0. Install and import modules\n",
47
+ "\n",
48
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:\n"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "metadata": {
55
+ "collapsed": false,
56
+ "customInput": null,
57
+ "customOutput": null,
58
+ "executionStartTime": 1659619898147,
59
+ "executionStopTime": 1659619898274,
60
+ "originalKey": "76f1ecd4-6b73-4214-81b0-118ef8d86872",
61
+ "requestMsgId": "deb6a860-6923-4227-abef-d31388b5142d",
62
+ "showInput": true
63
+ },
64
+ "outputs": [],
65
+ "source": [
66
+ "import os\n",
67
+ "import sys\n",
68
+ "import torch\n",
69
+ "import subprocess\n",
70
+ "need_pytorch3d=False\n",
71
+ "try:\n",
72
+ " import pytorch3d\n",
73
+ "except ModuleNotFoundError:\n",
74
+ " need_pytorch3d=True\n",
75
+ "if need_pytorch3d:\n",
76
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
77
+ " version_str=\"\".join([\n",
78
+ " f\"py3{sys.version_info.minor}_cu\",\n",
79
+ " torch.version.cuda.replace(\".\",\"\"),\n",
80
+ " f\"_pyt{pyt_version_str}\"\n",
81
+ " ])\n",
82
+ " !pip install iopath\n",
83
+ " if sys.platform.startswith(\"linux\"):\n",
84
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
85
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
86
+ " pip_list = !pip freeze\n",
87
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
88
+ " if need_pytorch3d:\n",
89
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
90
+ "if need_pytorch3d:\n",
91
+ " print(\"Installing PyTorch3D from source\")\n",
92
+ " !pip install ninja\n",
93
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
94
+ ]
95
+ },
96
+ {
97
+ "attachments": {},
98
+ "cell_type": "markdown",
99
+ "metadata": {
100
+ "customInput": null,
101
+ "originalKey": "2c1020e6-eb4a-4644-9719-9147500d8e4f",
102
+ "showInput": false
103
+ },
104
+ "source": [
105
+ "Ensure omegaconf and visdom are installed. If not, run this cell. (It should not be necessary to restart the runtime.)"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": null,
111
+ "metadata": {
112
+ "customInput": null,
113
+ "customOutput": null,
114
+ "originalKey": "9e751931-a38d-44c9-9ff1-ac2f7d3a3f99",
115
+ "showInput": true
116
+ },
117
+ "outputs": [],
118
+ "source": [
119
+ "!pip install omegaconf visdom"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": null,
125
+ "metadata": {
126
+ "code_folding": [],
127
+ "collapsed": false,
128
+ "customOutput": null,
129
+ "executionStartTime": 1659612480556,
130
+ "executionStopTime": 1659612480644,
131
+ "hidden_ranges": [],
132
+ "originalKey": "86807e4a-1675-4520-a033-c7af85b233ec",
133
+ "requestMsgId": "880a7e20-4a90-4b37-a5eb-bccc0b23cac6"
134
+ },
135
+ "outputs": [],
136
+ "source": [
137
+ "import logging\n",
138
+ "from typing import Tuple\n",
139
+ "\n",
140
+ "import matplotlib.animation as animation\n",
141
+ "import matplotlib.pyplot as plt\n",
142
+ "import numpy as np\n",
143
+ "import torch\n",
144
+ "import tqdm\n",
145
+ "from IPython.display import HTML\n",
146
+ "from omegaconf import OmegaConf\n",
147
+ "from PIL import Image\n",
148
+ "from pytorch3d.implicitron.dataset.dataset_base import FrameData\n",
149
+ "from pytorch3d.implicitron.dataset.rendered_mesh_dataset_map_provider import RenderedMeshDatasetMapProvider\n",
150
+ "from pytorch3d.implicitron.models.generic_model import GenericModel\n",
151
+ "from pytorch3d.implicitron.models.implicit_function.base import ImplicitFunctionBase, ImplicitronRayBundle\n",
152
+ "from pytorch3d.implicitron.models.renderer.base import EvaluationMode\n",
153
+ "from pytorch3d.implicitron.tools.config import get_default_args, registry, remove_unused_components\n",
154
+ "from pytorch3d.renderer.implicit.renderer import VolumeSampler\n",
155
+ "from pytorch3d.structures import Volumes\n",
156
+ "from pytorch3d.vis.plotly_vis import plot_batch_individually, plot_scene"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": null,
162
+ "metadata": {
163
+ "code_folding": [],
164
+ "collapsed": false,
165
+ "customInput": null,
166
+ "customOutput": null,
167
+ "executionStartTime": 1659610929375,
168
+ "executionStopTime": 1659610929383,
169
+ "hidden_ranges": [],
170
+ "originalKey": "b2d9f5bd-a9d4-4f78-b21e-92f2658e0fe9",
171
+ "requestMsgId": "7e43e623-4030-438b-af4e-b96170c9a052",
172
+ "showInput": true
173
+ },
174
+ "outputs": [],
175
+ "source": [
176
+ "output_resolution = 80"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": null,
182
+ "metadata": {
183
+ "code_folding": [],
184
+ "collapsed": false,
185
+ "customInput": null,
186
+ "customOutput": null,
187
+ "executionStartTime": 1659610930042,
188
+ "executionStopTime": 1659610930050,
189
+ "hidden_ranges": [],
190
+ "originalKey": "0b0c2087-4c86-4c57-b0ee-6f48a70a9c78",
191
+ "requestMsgId": "46883aad-f00b-4fd4-ac17-eec0b2ac272a",
192
+ "showInput": true
193
+ },
194
+ "outputs": [],
195
+ "source": [
196
+ "torch.set_printoptions(sci_mode=False)"
197
+ ]
198
+ },
199
+ {
200
+ "attachments": {},
201
+ "cell_type": "markdown",
202
+ "metadata": {
203
+ "customInput": null,
204
+ "originalKey": "37809d0d-b02e-42df-85b6-cdd038373653",
205
+ "showInput": false
206
+ },
207
+ "source": [
208
+ "## 1. Load renders of a mesh (the cow mesh) as a dataset\n",
209
+ "\n",
210
+ "A dataset's train, val and test parts in Implicitron are represented as a `dataset_map`, and provided by an implementation of `DatasetMapProvider`. \n",
211
+ "`RenderedMeshDatasetMapProvider` is one which generates a single-scene dataset with only a train component by taking a mesh and rendering it.\n",
212
+ "We use it with the cow mesh."
213
+ ]
214
+ },
215
+ {
216
+ "attachments": {},
217
+ "cell_type": "markdown",
218
+ "metadata": {
219
+ "collapsed": false,
220
+ "customInput": null,
221
+ "customOutput": null,
222
+ "executionStartTime": 1659620739780,
223
+ "executionStopTime": 1659620739914,
224
+ "originalKey": "cc68cb9c-b8bf-4e9e-bef1-2cfafdf6caa2",
225
+ "requestMsgId": "398cfcae-5d43-4b6f-9c75-db3d297364d4",
226
+ "showInput": false
227
+ },
228
+ "source": [
229
+ "If running this notebook using **Google Colab**, run the following cell to fetch the mesh obj and texture files and save it at the path data/cow_mesh.\n",
230
+ "If running locally, the data is already available at the correct path."
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "execution_count": null,
236
+ "metadata": {
237
+ "customInput": null,
238
+ "customOutput": null,
239
+ "originalKey": "2c55e002-a885-4169-8fdc-af9078b05968",
240
+ "showInput": true
241
+ },
242
+ "outputs": [],
243
+ "source": [
244
+ "!mkdir -p data/cow_mesh\n",
245
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.obj\n",
246
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.mtl\n",
247
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow_texture.png"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": null,
253
+ "metadata": {
254
+ "code_folding": [],
255
+ "collapsed": false,
256
+ "customOutput": null,
257
+ "executionStartTime": 1659621652237,
258
+ "executionStopTime": 1659621652903,
259
+ "hidden_ranges": [],
260
+ "originalKey": "eb77aaec-048c-40bd-bd69-0e66b6ab60b1",
261
+ "requestMsgId": "09b9975c-ff86-41c9-b4a9-975d23afc562",
262
+ "showInput": true
263
+ },
264
+ "outputs": [],
265
+ "source": [
266
+ "cow_provider = RenderedMeshDatasetMapProvider(\n",
267
+ " data_file=\"data/cow_mesh/cow.obj\",\n",
268
+ " use_point_light=False,\n",
269
+ " resolution=output_resolution,\n",
270
+ ")"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "metadata": {
277
+ "code_folding": [],
278
+ "collapsed": false,
279
+ "customInput": null,
280
+ "customOutput": null,
281
+ "executionStartTime": 1659610966145,
282
+ "executionStopTime": 1659610966255,
283
+ "hidden_ranges": [],
284
+ "originalKey": "8210e15b-da48-4306-a49a-41c4e7e7d42f",
285
+ "requestMsgId": "c243edd2-a106-4fba-8471-dfa4f99a2088",
286
+ "showInput": true
287
+ },
288
+ "outputs": [],
289
+ "source": [
290
+ "dataset_map = cow_provider.get_dataset_map()\n",
291
+ "tr_cameras = [training_frame.camera for training_frame in dataset_map.train]"
292
+ ]
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "execution_count": null,
297
+ "metadata": {
298
+ "code_folding": [],
299
+ "collapsed": false,
300
+ "customInput": null,
301
+ "customOutput": null,
302
+ "executionStartTime": 1659610967703,
303
+ "executionStopTime": 1659610967848,
304
+ "hidden_ranges": [],
305
+ "originalKey": "458d72ad-d9a7-4f13-b5b7-90d2aec61c16",
306
+ "requestMsgId": "7f9431f3-8717-4d89-a7fe-1420dd0e00c4",
307
+ "showInput": true
308
+ },
309
+ "outputs": [],
310
+ "source": [
311
+ "# The cameras are all in the XZ plane, in a circle about 2.7 from the origin\n",
312
+ "centers = torch.cat([i.get_camera_center() for i in tr_cameras])\n",
313
+ "print(centers.min(0).values)\n",
314
+ "print(centers.max(0).values)"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "execution_count": null,
320
+ "metadata": {
321
+ "code_folding": [],
322
+ "collapsed": false,
323
+ "customInput": null,
324
+ "customOutput": null,
325
+ "executionStartTime": 1659552920194,
326
+ "executionStopTime": 1659552923122,
327
+ "hidden_ranges": [],
328
+ "originalKey": "931e712b-b141-437a-97fb-dc2a07ce3458",
329
+ "requestMsgId": "931e712b-b141-437a-97fb-dc2a07ce3458",
330
+ "showInput": true
331
+ },
332
+ "outputs": [],
333
+ "source": [
334
+ "# visualization of the cameras\n",
335
+ "plot = plot_scene({\"k\": {i: camera for i, camera in enumerate(tr_cameras)}}, camera_scale=0.25)\n",
336
+ "plot.layout.scene.aspectmode = \"data\"\n",
337
+ "plot"
338
+ ]
339
+ },
340
+ {
341
+ "attachments": {},
342
+ "cell_type": "markdown",
343
+ "metadata": {
344
+ "customInput": null,
345
+ "originalKey": "afa9c02d-f76b-4f68-83e9-9733c615406b",
346
+ "showInput": false
347
+ },
348
+ "source": [
349
+ "## 2. Custom implicit function 🧊\n",
350
+ "\n",
351
+ "At the core of neural rendering methods are functions of spatial coordinates called implicit functions, which are used in some kind of rendering process.\n",
352
+ "(Often those functions can additionally take other data as well, such as view direction.)\n",
353
+ "A common rendering process is ray marching over densities and colors provided by an implicit function.\n",
354
+ "In our case, taking samples from a 3D volume grid is a very simple function of spatial coordinates. \n",
355
+ "\n",
356
+ "Here we define our own implicit function, which uses PyTorch3D's existing functionality for sampling from a volume grid.\n",
357
+ "We do this by subclassing `ImplicitFunctionBase`.\n",
358
+ "We need to register our subclass with a special decorator.\n",
359
+ "We use Python's dataclass annotations for configuring the module."
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "metadata": {
366
+ "code_folding": [],
367
+ "collapsed": false,
368
+ "customInput": null,
369
+ "customOutput": null,
370
+ "executionStartTime": 1659613575850,
371
+ "executionStopTime": 1659613575940,
372
+ "hidden_ranges": [],
373
+ "originalKey": "61b55043-dc52-4de7-992e-e2195edd2123",
374
+ "requestMsgId": "dfaace3c-098c-4ffe-9240-6a7ae0ff271e",
375
+ "showInput": true
376
+ },
377
+ "outputs": [],
378
+ "source": [
379
+ "@registry.register\n",
380
+ "class MyVolumes(ImplicitFunctionBase, torch.nn.Module):\n",
381
+ " grid_resolution: int = 50 # common HWD of volumes, the number of voxels in each direction\n",
382
+ " extent: float = 1.0 # In world coordinates, the volume occupies is [-extent, extent] along each axis\n",
383
+ "\n",
384
+ " def __post_init__(self):\n",
385
+ " # We have to call this explicitly if there are other base classes like Module\n",
386
+ " super().__init__()\n",
387
+ "\n",
388
+ " # We define parameters like other torch.nn.Module objects.\n",
389
+ " # In this case, both our parameter tensors are trainable; they govern the contents of the volume grid.\n",
390
+ " density = torch.full((self.grid_resolution, self.grid_resolution, self.grid_resolution), -2.0)\n",
391
+ " self.density = torch.nn.Parameter(density)\n",
392
+ " color = torch.full((3, self.grid_resolution, self.grid_resolution, self.grid_resolution), 0.0)\n",
393
+ " self.color = torch.nn.Parameter(color)\n",
394
+ " self.density_activation = torch.nn.Softplus()\n",
395
+ "\n",
396
+ " def forward(\n",
397
+ " self,\n",
398
+ " ray_bundle: ImplicitronRayBundle,\n",
399
+ " fun_viewpool=None,\n",
400
+ " global_code=None,\n",
401
+ " ):\n",
402
+ " densities = self.density_activation(self.density[None, None])\n",
403
+ " voxel_size = 2.0 * float(self.extent) / self.grid_resolution\n",
404
+ " features = self.color.sigmoid()[None]\n",
405
+ "\n",
406
+ " # Like other PyTorch3D structures, the actual Volumes object should only exist as long\n",
407
+ " # as one iteration of training. It is local to this function.\n",
408
+ "\n",
409
+ " volume = Volumes(densities=densities, features=features, voxel_size=voxel_size)\n",
410
+ " sampler = VolumeSampler(volumes=volume)\n",
411
+ " densities, features = sampler(ray_bundle)\n",
412
+ "\n",
413
+ " # When an implicit function is used for raymarching, i.e. for MultiPassEmissionAbsorptionRenderer,\n",
414
+ " # it must return (densities, features, an auxiliary tuple)\n",
415
+ " return densities, features, {}\n"
416
+ ]
417
+ },
418
+ {
419
+ "attachments": {},
420
+ "cell_type": "markdown",
421
+ "metadata": {
422
+ "customInput": null,
423
+ "originalKey": "abaf2cd6-1b68-400e-a142-8fb9f49953f3",
424
+ "showInput": false
425
+ },
426
+ "source": [
427
+ "## 3. Construct the model object.\n",
428
+ "\n",
429
+ "The main model object in PyTorch3D is `GenericModel`, which has pluggable components for the major steps, including the renderer and the implicit function(s).\n",
430
+ "There are two ways to construct it which are equivalent here."
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "code",
435
+ "execution_count": null,
436
+ "metadata": {
437
+ "collapsed": false,
438
+ "customInput": null,
439
+ "customOutput": null,
440
+ "executionStartTime": 1659621267561,
441
+ "executionStopTime": 1659621267938,
442
+ "originalKey": "f26c3dce-fbae-4592-bd0e-e4a8abc57c2c",
443
+ "requestMsgId": "9213687e-1caf-46a8-a4e5-a9c531530092",
444
+ "showInput": true
445
+ },
446
+ "outputs": [],
447
+ "source": [
448
+ "CONSTRUCT_MODEL_FROM_CONFIG = True\n",
449
+ "if CONSTRUCT_MODEL_FROM_CONFIG:\n",
450
+ " # Via a DictConfig - this is how our training loop with hydra works\n",
451
+ " cfg = get_default_args(GenericModel)\n",
452
+ " cfg.implicit_function_class_type = \"MyVolumes\"\n",
453
+ " cfg.render_image_height=output_resolution\n",
454
+ " cfg.render_image_width=output_resolution\n",
455
+ " cfg.loss_weights={\"loss_rgb_huber\": 1.0}\n",
456
+ " cfg.tqdm_trigger_threshold=19000\n",
457
+ " cfg.raysampler_AdaptiveRaySampler_args.scene_extent= 4.0\n",
458
+ " gm = GenericModel(**cfg)\n",
459
+ "else:\n",
460
+ " # constructing GenericModel directly\n",
461
+ " gm = GenericModel(\n",
462
+ " implicit_function_class_type=\"MyVolumes\",\n",
463
+ " render_image_height=output_resolution,\n",
464
+ " render_image_width=output_resolution,\n",
465
+ " loss_weights={\"loss_rgb_huber\": 1.0},\n",
466
+ " tqdm_trigger_threshold=19000,\n",
467
+ " raysampler_AdaptiveRaySampler_args = {\"scene_extent\": 4.0}\n",
468
+ " )\n",
469
+ "\n",
470
+ " # In this case we can get the equivalent DictConfig cfg object to the way gm is configured as follows\n",
471
+ " cfg = OmegaConf.structured(gm)\n"
472
+ ]
473
+ },
474
+ {
475
+ "attachments": {},
476
+ "cell_type": "markdown",
477
+ "metadata": {
478
+ "code_folding": [],
479
+ "collapsed": false,
480
+ "customInput": null,
481
+ "customOutput": null,
482
+ "executionStartTime": 1659611214689,
483
+ "executionStopTime": 1659611214748,
484
+ "hidden_ranges": [],
485
+ "originalKey": "4e659f7d-ce66-4999-83de-005eb09d7705",
486
+ "requestMsgId": "7b815b2b-cf19-44d0-ae89-76fde6df35ec",
487
+ "showInput": false
488
+ },
489
+ "source": [
490
+ " The default renderer is an emission-absorbtion raymarcher. We keep that default."
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": null,
496
+ "metadata": {
497
+ "code_folding": [],
498
+ "collapsed": false,
499
+ "customInput": null,
500
+ "customOutput": null,
501
+ "executionStartTime": 1659621268007,
502
+ "executionStopTime": 1659621268190,
503
+ "hidden_ranges": [],
504
+ "originalKey": "d37ae488-c57c-44d3-9def-825dc1a6495b",
505
+ "requestMsgId": "71143ec1-730f-4876-8a14-e46eea9d6dd1",
506
+ "showInput": true
507
+ },
508
+ "outputs": [],
509
+ "source": [
510
+ "# We can display the configuration in use as follows.\n",
511
+ "remove_unused_components(cfg)\n",
512
+ "yaml = OmegaConf.to_yaml(cfg, sort_keys=False)\n",
513
+ "%page -r yaml"
514
+ ]
515
+ },
516
+ {
517
+ "cell_type": "code",
518
+ "execution_count": null,
519
+ "metadata": {
520
+ "code_folding": [],
521
+ "collapsed": false,
522
+ "customInput": null,
523
+ "customOutput": null,
524
+ "executionStartTime": 1659621268727,
525
+ "executionStopTime": 1659621268776,
526
+ "hidden_ranges": [],
527
+ "originalKey": "52e53179-3c6e-4c1f-a38a-3a6d803687bb",
528
+ "requestMsgId": "05de9bc3-3f74-4a6f-851c-9ec919b59506",
529
+ "showInput": true
530
+ },
531
+ "outputs": [],
532
+ "source": [
533
+ "device = torch.device(\"cuda:0\")\n",
534
+ "gm.to(device)\n",
535
+ "assert next(gm.parameters()).is_cuda"
536
+ ]
537
+ },
538
+ {
539
+ "cell_type": "markdown",
540
+ "metadata": {
541
+ "customInput": null,
542
+ "originalKey": "528a7d53-c645-49c2-9021-09adbb18cd23",
543
+ "showInput": false
544
+ },
545
+ "source": [
546
+ "## 4. train the model "
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "code",
551
+ "execution_count": null,
552
+ "metadata": {
553
+ "code_folding": [],
554
+ "collapsed": false,
555
+ "customInput": null,
556
+ "customOutput": null,
557
+ "executionStartTime": 1659621270236,
558
+ "executionStopTime": 1659621270446,
559
+ "hidden_ranges": [],
560
+ "originalKey": "953280bd-3161-42ba-8dcb-0c8ef2d5cc25",
561
+ "requestMsgId": "9bba424b-7bfd-4e5a-9d79-ae316e20bab0",
562
+ "showInput": true
563
+ },
564
+ "outputs": [],
565
+ "source": [
566
+ "train_data_collated = [FrameData.collate([frame.to(device)]) for frame in dataset_map.train]"
567
+ ]
568
+ },
569
+ {
570
+ "cell_type": "code",
571
+ "execution_count": null,
572
+ "metadata": {
573
+ "code_folding": [],
574
+ "collapsed": false,
575
+ "customInput": null,
576
+ "customOutput": null,
577
+ "executionStartTime": 1659621270815,
578
+ "executionStopTime": 1659621270948,
579
+ "hidden_ranges": [],
580
+ "originalKey": "2fcf07f0-0c28-49c7-8c76-1c9a9d810167",
581
+ "requestMsgId": "821deb43-6084-4ece-83c3-dee214562c47",
582
+ "showInput": true
583
+ },
584
+ "outputs": [],
585
+ "source": [
586
+ "gm.train()\n",
587
+ "optimizer = torch.optim.Adam(gm.parameters(), lr=0.1)"
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": null,
593
+ "metadata": {
594
+ "code_folding": [],
595
+ "collapsed": false,
596
+ "customOutput": null,
597
+ "executionStartTime": 1659621271875,
598
+ "executionStopTime": 1659621298146,
599
+ "hidden_ranges": [],
600
+ "originalKey": "105099f7-ed0c-4e7f-a976-61a93fd0a8fe",
601
+ "requestMsgId": "0c87c108-83e3-4129-ad02-85e0140f1368",
602
+ "showInput": true
603
+ },
604
+ "outputs": [],
605
+ "source": [
606
+ "iterator = tqdm.tqdm(range(2000))\n",
607
+ "for n_batch in iterator:\n",
608
+ " optimizer.zero_grad()\n",
609
+ "\n",
610
+ " frame = train_data_collated[n_batch % len(dataset_map.train)]\n",
611
+ " out = gm(**frame, evaluation_mode=EvaluationMode.TRAINING)\n",
612
+ " out[\"objective\"].backward()\n",
613
+ " if n_batch % 100 == 0:\n",
614
+ " iterator.set_postfix_str(f\"loss: {float(out['objective']):.5f}\")\n",
615
+ " optimizer.step()"
616
+ ]
617
+ },
618
+ {
619
+ "attachments": {},
620
+ "cell_type": "markdown",
621
+ "metadata": {
622
+ "collapsed": false,
623
+ "customInput": null,
624
+ "customOutput": null,
625
+ "executionStartTime": 1659535024768,
626
+ "executionStopTime": 1659535024906,
627
+ "originalKey": "e3cd494a-536b-48bc-8290-c048118c82eb",
628
+ "requestMsgId": "e3cd494a-536b-48bc-8290-c048118c82eb",
629
+ "showInput": false
630
+ },
631
+ "source": [
632
+ "## 5. Evaluate the module\n",
633
+ "\n",
634
+ "We generate complete images from all the viewpoints to see how they look."
635
+ ]
636
+ },
637
+ {
638
+ "cell_type": "code",
639
+ "execution_count": null,
640
+ "metadata": {
641
+ "code_folding": [],
642
+ "collapsed": false,
643
+ "customInput": null,
644
+ "customOutput": null,
645
+ "executionStartTime": 1659621299859,
646
+ "executionStopTime": 1659621311133,
647
+ "hidden_ranges": [],
648
+ "originalKey": "fbe1b2ea-cc24-4b20-a2d7-0249185e34a5",
649
+ "requestMsgId": "771ef1f8-5eee-4932-9e81-33604bf0512a",
650
+ "showInput": true
651
+ },
652
+ "outputs": [],
653
+ "source": [
654
+ "def to_numpy_image(image):\n",
655
+ " # Takes an image of shape (C, H, W) in [0,1], where C=3 or 1\n",
656
+ " # to a numpy uint image of shape (H, W, 3)\n",
657
+ " return (image * 255).to(torch.uint8).permute(1, 2, 0).detach().cpu().expand(-1, -1, 3).numpy()\n",
658
+ "def resize_image(image):\n",
659
+ " # Takes images of shape (B, C, H, W) to (B, C, output_resolution, output_resolution)\n",
660
+ " return torch.nn.functional.interpolate(image, size=(output_resolution, output_resolution))\n",
661
+ "\n",
662
+ "gm.eval()\n",
663
+ "images = []\n",
664
+ "expected = []\n",
665
+ "masks = []\n",
666
+ "masks_expected = []\n",
667
+ "for frame in tqdm.tqdm(train_data_collated):\n",
668
+ " with torch.no_grad():\n",
669
+ " out = gm(**frame, evaluation_mode=EvaluationMode.EVALUATION)\n",
670
+ "\n",
671
+ " image_rgb = to_numpy_image(out[\"images_render\"][0])\n",
672
+ " mask = to_numpy_image(out[\"masks_render\"][0])\n",
673
+ " expd = to_numpy_image(resize_image(frame.image_rgb)[0])\n",
674
+ " mask_expected = to_numpy_image(resize_image(frame.fg_probability)[0])\n",
675
+ "\n",
676
+ " images.append(image_rgb)\n",
677
+ " masks.append(mask)\n",
678
+ " expected.append(expd)\n",
679
+ " masks_expected.append(mask_expected)"
680
+ ]
681
+ },
682
+ {
683
+ "attachments": {},
684
+ "cell_type": "markdown",
685
+ "metadata": {
686
+ "collapsed": false,
687
+ "customInput": null,
688
+ "customOutput": null,
689
+ "executionStartTime": 1659614622542,
690
+ "executionStopTime": 1659614622757,
691
+ "originalKey": "24953039-9780-40fd-bd81-5d63e9f40069",
692
+ "requestMsgId": "7af895a3-dfe4-4c28-ac3b-4ff0fbb40c7f",
693
+ "showInput": false
694
+ },
695
+ "source": [
696
+ "We draw a grid showing predicted image and expected image, followed by predicted mask and expected mask, from each viewpoint. \n",
697
+ "This is a grid of four rows of images, wrapped in to several large rows, i.e..\n",
698
+ "<small><center>\n",
699
+ "```\n",
700
+ "┌────────┬────────┐ ┌────────┐\n",
701
+ "│pred │pred │ │pred │\n",
702
+ "│image │image │ │image │\n",
703
+ "│1 │2 │ │n │\n",
704
+ "├────────┼────────┤ ├────────┤\n",
705
+ "│expected│expected│ │expected│\n",
706
+ "│image │image │ ... │image │\n",
707
+ "│1 │2 │ │n │\n",
708
+ "├────────┼────────┤ ├────────┤\n",
709
+ "│pred │pred │ │pred │\n",
710
+ "│mask │mask │ │mask │\n",
711
+ "│1 │2 │ │n │\n",
712
+ "├────────┼────────┤ ├────────┤\n",
713
+ "│expected│expected│ │expected│\n",
714
+ "│mask │mask │ │mask │\n",
715
+ "│1 │2 │ │n │\n",
716
+ "├────────┼────────┤ ├────────┤\n",
717
+ "│pred │pred │ │pred │\n",
718
+ "│image │image │ │image │\n",
719
+ "│n+1 │n+1 │ │2n │\n",
720
+ "├────────┼────────┤ ├────────┤\n",
721
+ "│expected│expected│ │expected│\n",
722
+ "│image │image │ ... │image │\n",
723
+ "│n+1 │n+2 │ │2n │\n",
724
+ "├────────┼────────┤ ├────────┤\n",
725
+ "│pred │pred │ │pred │\n",
726
+ "│mask │mask │ │mask │\n",
727
+ "│n+1 │n+2 │ │2n │\n",
728
+ "├────────┼────────┤ ├────────┤\n",
729
+ "│expected│expected│ │expected│\n",
730
+ "│mask │mask │ │mask │\n",
731
+ "│n+1 │n+2 │ │2n │\n",
732
+ "└────────┴────────┘ └────────┘\n",
733
+ " ...\n",
734
+ "```\n",
735
+ "</center></small>"
736
+ ]
737
+ },
738
+ {
739
+ "cell_type": "code",
740
+ "execution_count": null,
741
+ "metadata": {
742
+ "code_folding": [],
743
+ "collapsed": false,
744
+ "customInput": null,
745
+ "customOutput": null,
746
+ "executionStartTime": 1659621313894,
747
+ "executionStopTime": 1659621314042,
748
+ "hidden_ranges": [],
749
+ "originalKey": "c488a34a-e46d-4649-93fb-4b1bb5a0e439",
750
+ "requestMsgId": "4221e632-fca1-4fe5-b2e3-f92c37aa40e4",
751
+ "showInput": true
752
+ },
753
+ "outputs": [],
754
+ "source": [
755
+ "images_to_display = [images.copy(), expected.copy(), masks.copy(), masks_expected.copy()]\n",
756
+ "n_rows = 4\n",
757
+ "n_images = len(images)\n",
758
+ "blank_image = images[0] * 0\n",
759
+ "n_per_row = 1+(n_images-1)//n_rows\n",
760
+ "for _ in range(n_per_row*n_rows - n_images):\n",
761
+ " for group in images_to_display:\n",
762
+ " group.append(blank_image)\n",
763
+ "\n",
764
+ "images_to_display_listed = [[[i] for i in j] for j in images_to_display]\n",
765
+ "split = []\n",
766
+ "for row in range(n_rows):\n",
767
+ " for group in images_to_display_listed:\n",
768
+ " split.append(group[row*n_per_row:(row+1)*n_per_row]) \n",
769
+ "\n",
770
+ "Image.fromarray(np.block(split))\n"
771
+ ]
772
+ },
773
+ {
774
+ "cell_type": "code",
775
+ "execution_count": null,
776
+ "metadata": {
777
+ "code_folding": [],
778
+ "collapsed": false,
779
+ "customInput": null,
780
+ "customOutput": null,
781
+ "executionStartTime": 1659621323795,
782
+ "executionStopTime": 1659621323820,
783
+ "hidden_ranges": [],
784
+ "originalKey": "49eab9e1-4fe2-4fbe-b4f3-7b6953340170",
785
+ "requestMsgId": "85b402ad-f903-431f-a13e-c2d697e869bb",
786
+ "showInput": true
787
+ },
788
+ "outputs": [],
789
+ "source": [
790
+ "# Print the maximum channel intensity in the first image.\n",
791
+ "print(images[1].max()/255)"
792
+ ]
793
+ },
794
+ {
795
+ "cell_type": "code",
796
+ "execution_count": null,
797
+ "metadata": {
798
+ "code_folding": [],
799
+ "collapsed": false,
800
+ "customInput": null,
801
+ "customOutput": null,
802
+ "executionStartTime": 1659621408642,
803
+ "executionStopTime": 1659621409559,
804
+ "hidden_ranges": [],
805
+ "originalKey": "137d2c43-d39d-4266-ac5e-2b714da5e0ee",
806
+ "requestMsgId": "8e27ec57-c2d6-4ae0-be69-b63b6af929ff",
807
+ "showInput": true
808
+ },
809
+ "outputs": [],
810
+ "source": [
811
+ "plt.ioff()\n",
812
+ "fig, ax = plt.subplots(figsize=(3,3))\n",
813
+ "\n",
814
+ "ax.grid(None)\n",
815
+ "ims = [[ax.imshow(im, animated=True)] for im in images]\n",
816
+ "ani = animation.ArtistAnimation(fig, ims, interval=80, blit=True)\n",
817
+ "ani_html = ani.to_jshtml()\n"
818
+ ]
819
+ },
820
+ {
821
+ "cell_type": "code",
822
+ "execution_count": null,
823
+ "metadata": {
824
+ "collapsed": false,
825
+ "customInput": null,
826
+ "customOutput": null,
827
+ "executionStartTime": 1659621409620,
828
+ "executionStopTime": 1659621409725,
829
+ "originalKey": "783e70d6-7cf1-4d76-a126-ba11ffc2f5be",
830
+ "requestMsgId": "b6843506-c5fa-4508-80fc-8ecae51a934a",
831
+ "showInput": true
832
+ },
833
+ "outputs": [],
834
+ "source": [
835
+ "HTML(ani_html)"
836
+ ]
837
+ },
838
+ {
839
+ "cell_type": "code",
840
+ "execution_count": null,
841
+ "metadata": {
842
+ "collapsed": false,
843
+ "customInput": null,
844
+ "customOutput": null,
845
+ "executionStartTime": 1659614670081,
846
+ "executionStopTime": 1659614670168,
847
+ "originalKey": "0286c350-2362-4f47-8181-2fc2ba51cfcf",
848
+ "requestMsgId": "976f4db9-d4c7-466c-bcfd-218234400226",
849
+ "showInput": true
850
+ },
851
+ "outputs": [],
852
+ "source": [
853
+ "# If you want to see the output of the model with the volume forced to opaque white, run this and re-evaluate\n",
854
+ "# with torch.no_grad():\n",
855
+ "# gm._implicit_functions[0]._fn.density.fill_(9.0)\n",
856
+ "# gm._implicit_functions[0]._fn.color.fill_(9.0)\n"
857
+ ]
858
+ }
859
+ ],
860
+ "metadata": {
861
+ "bento_stylesheets": {
862
+ "bento/extensions/flow/main.css": true,
863
+ "bento/extensions/kernel_selector/main.css": true,
864
+ "bento/extensions/kernel_ui/main.css": true,
865
+ "bento/extensions/new_kernel/main.css": true,
866
+ "bento/extensions/system_usage/main.css": true,
867
+ "bento/extensions/theme/main.css": true
868
+ },
869
+ "captumWidgetMessage": {},
870
+ "dataExplorerConfig": {},
871
+ "kernelspec": {
872
+ "display_name": "pytorch3d",
873
+ "language": "python",
874
+ "metadata": {
875
+ "cinder_runtime": false,
876
+ "fbpkg_supported": true,
877
+ "is_prebuilt": true,
878
+ "kernel_name": "bento_kernel_pytorch3d",
879
+ "nightly_builds": true
880
+ },
881
+ "name": "bento_kernel_pytorch3d"
882
+ },
883
+ "language_info": {
884
+ "codemirror_mode": {
885
+ "name": "ipython",
886
+ "version": 3
887
+ },
888
+ "file_extension": ".py",
889
+ "mimetype": "text/x-python",
890
+ "name": "python",
891
+ "nbconvert_exporter": "python",
892
+ "pygments_lexer": "ipython3"
893
+ },
894
+ "last_base_url": "https://9177.od.fbinfra.net:443/",
895
+ "last_kernel_id": "bb33cd83-7924-489a-8bd8-2d9d62eb0126",
896
+ "last_msg_id": "99f7088e-d22b355b859660479ef0574e_5743",
897
+ "last_server_session_id": "2944b203-9ea8-4c0e-9634-645dfea5f26b",
898
+ "outputWidgetContext": {}
899
+ },
900
+ "nbformat": 4,
901
+ "nbformat_minor": 2
902
+ }
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_colored_points.ipynb ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Render a colored point cloud\n",
17
+ "\n",
18
+ "This tutorial shows how to:\n",
19
+ "- set up a renderer \n",
20
+ "- render the point cloud \n",
21
+ "- vary the rendering settings such as compositing and camera position"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "markdown",
26
+ "metadata": {},
27
+ "source": [
28
+ "## Import modules"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "import os\n",
45
+ "import sys\n",
46
+ "import torch\n",
47
+ "import subprocess\n",
48
+ "need_pytorch3d=False\n",
49
+ "try:\n",
50
+ " import pytorch3d\n",
51
+ "except ModuleNotFoundError:\n",
52
+ " need_pytorch3d=True\n",
53
+ "if need_pytorch3d:\n",
54
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
55
+ " version_str=\"\".join([\n",
56
+ " f\"py3{sys.version_info.minor}_cu\",\n",
57
+ " torch.version.cuda.replace(\".\",\"\"),\n",
58
+ " f\"_pyt{pyt_version_str}\"\n",
59
+ " ])\n",
60
+ " !pip install iopath\n",
61
+ " if sys.platform.startswith(\"linux\"):\n",
62
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
63
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
64
+ " pip_list = !pip freeze\n",
65
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
66
+ " if need_pytorch3d:\n",
67
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
68
+ "if need_pytorch3d:\n",
69
+ " print(\"Installing PyTorch3D from source\")\n",
70
+ " !pip install ninja\n",
71
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "execution_count": null,
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "import os\n",
81
+ "import torch\n",
82
+ "import torch.nn.functional as F\n",
83
+ "import matplotlib.pyplot as plt\n",
84
+ "\n",
85
+ "# Util function for loading point clouds|\n",
86
+ "import numpy as np\n",
87
+ "\n",
88
+ "# Data structures and functions for rendering\n",
89
+ "from pytorch3d.structures import Pointclouds\n",
90
+ "from pytorch3d.vis.plotly_vis import AxisArgs, plot_batch_individually, plot_scene\n",
91
+ "from pytorch3d.renderer import (\n",
92
+ " look_at_view_transform,\n",
93
+ " FoVOrthographicCameras, \n",
94
+ " PointsRasterizationSettings,\n",
95
+ " PointsRenderer,\n",
96
+ " PulsarPointsRenderer,\n",
97
+ " PointsRasterizer,\n",
98
+ " AlphaCompositor,\n",
99
+ " NormWeightedCompositor\n",
100
+ ")"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "markdown",
105
+ "metadata": {},
106
+ "source": [
107
+ "### Load a point cloud and corresponding colors\n",
108
+ "\n",
109
+ "Load and create a **Point Cloud** object. \n",
110
+ "\n",
111
+ "**Pointclouds** is a unique datastructure provided in PyTorch3D for working with batches of point clouds of different sizes. "
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "markdown",
116
+ "metadata": {},
117
+ "source": [
118
+ "If running this notebook using **Google Colab**, run the following cell to fetch the pointcloud data and save it at the path `data/PittsburghBridge`:\n",
119
+ "If running locally, the data is already available at the correct path. "
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": null,
125
+ "metadata": {},
126
+ "outputs": [],
127
+ "source": [
128
+ "!mkdir -p data/PittsburghBridge\n",
129
+ "!wget -P data/PittsburghBridge https://dl.fbaipublicfiles.com/pytorch3d/data/PittsburghBridge/pointcloud.npz"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": null,
135
+ "metadata": {},
136
+ "outputs": [],
137
+ "source": [
138
+ "# Setup\n",
139
+ "if torch.cuda.is_available():\n",
140
+ " device = torch.device(\"cuda:0\")\n",
141
+ " torch.cuda.set_device(device)\n",
142
+ "else:\n",
143
+ " device = torch.device(\"cpu\")\n",
144
+ "\n",
145
+ "# Set paths\n",
146
+ "DATA_DIR = \"./data\"\n",
147
+ "obj_filename = os.path.join(DATA_DIR, \"PittsburghBridge/pointcloud.npz\")\n",
148
+ "\n",
149
+ "# Load point cloud\n",
150
+ "pointcloud = np.load(obj_filename)\n",
151
+ "verts = torch.Tensor(pointcloud['verts']).to(device)\n",
152
+ " \n",
153
+ "rgb = torch.Tensor(pointcloud['rgb']).to(device)\n",
154
+ "\n",
155
+ "point_cloud = Pointclouds(points=[verts], features=[rgb])"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "metadata": {},
161
+ "source": [
162
+ "## Create a renderer\n",
163
+ "\n",
164
+ "A renderer in PyTorch3D is composed of a **rasterizer** and a **shader** which each have a number of subcomponents such as a **camera** (orthographic/perspective). Here we initialize some of these components and use default values for the rest.\n",
165
+ "\n",
166
+ "In this example we will first create a **renderer** which uses an **orthographic camera**, and applies **alpha compositing**. Then we learn how to vary different components using the modular API. \n",
167
+ "\n",
168
+ "[1] <a href=\"https://arxiv.org/abs/1912.08804\">SynSin: End to end View Synthesis from a Single Image.</a> Olivia Wiles, Georgia Gkioxari, Richard Szeliski, Justin Johnson. CVPR 2020."
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "metadata": {},
175
+ "outputs": [],
176
+ "source": [
177
+ "# Initialize a camera.\n",
178
+ "R, T = look_at_view_transform(20, 10, 0)\n",
179
+ "cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)\n",
180
+ "\n",
181
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
182
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
183
+ "# and blur_radius=0.0. Refer to raster_points.py for explanations of these parameters. \n",
184
+ "raster_settings = PointsRasterizationSettings(\n",
185
+ " image_size=512, \n",
186
+ " radius = 0.003,\n",
187
+ " points_per_pixel = 10\n",
188
+ ")\n",
189
+ "\n",
190
+ "\n",
191
+ "# Create a points renderer by compositing points using an alpha compositor (nearer points\n",
192
+ "# are weighted more heavily). See [1] for an explanation.\n",
193
+ "rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)\n",
194
+ "renderer = PointsRenderer(\n",
195
+ " rasterizer=rasterizer,\n",
196
+ " compositor=AlphaCompositor()\n",
197
+ ")"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "execution_count": null,
203
+ "metadata": {},
204
+ "outputs": [],
205
+ "source": [
206
+ "images = renderer(point_cloud)\n",
207
+ "plt.figure(figsize=(10, 10))\n",
208
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
209
+ "plt.axis(\"off\");"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "markdown",
214
+ "metadata": {},
215
+ "source": [
216
+ "We will now modify the **renderer** to use **alpha compositing** with a set background color. "
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": null,
222
+ "metadata": {},
223
+ "outputs": [],
224
+ "source": [
225
+ "renderer = PointsRenderer(\n",
226
+ " rasterizer=rasterizer,\n",
227
+ " # Pass in background_color to the alpha compositor, setting the background color \n",
228
+ " # to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case blue\n",
229
+ " compositor=AlphaCompositor(background_color=(0, 0, 1))\n",
230
+ ")\n",
231
+ "images = renderer(point_cloud)\n",
232
+ "\n",
233
+ "plt.figure(figsize=(10, 10))\n",
234
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
235
+ "plt.axis(\"off\");"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "markdown",
240
+ "metadata": {},
241
+ "source": [
242
+ "In this example we will first create a **renderer** which uses an **orthographic camera**, and applies **weighted compositing**. "
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": null,
248
+ "metadata": {},
249
+ "outputs": [],
250
+ "source": [
251
+ "# Initialize a camera.\n",
252
+ "R, T = look_at_view_transform(20, 10, 0)\n",
253
+ "cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)\n",
254
+ "\n",
255
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
256
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
257
+ "# and blur_radius=0.0. Refer to rasterize_points.py for explanations of these parameters. \n",
258
+ "raster_settings = PointsRasterizationSettings(\n",
259
+ " image_size=512, \n",
260
+ " radius = 0.003,\n",
261
+ " points_per_pixel = 10\n",
262
+ ")\n",
263
+ "\n",
264
+ "\n",
265
+ "# Create a points renderer by compositing points using an weighted compositor (3D points are\n",
266
+ "# weighted according to their distance to a pixel and accumulated using a weighted sum)\n",
267
+ "renderer = PointsRenderer(\n",
268
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
269
+ " compositor=NormWeightedCompositor()\n",
270
+ ")\n"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "metadata": {},
277
+ "outputs": [],
278
+ "source": [
279
+ "images = renderer(point_cloud)\n",
280
+ "plt.figure(figsize=(10, 10))\n",
281
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
282
+ "plt.axis(\"off\");"
283
+ ]
284
+ },
285
+ {
286
+ "cell_type": "markdown",
287
+ "metadata": {},
288
+ "source": [
289
+ "We will now modify the **renderer** to use **weighted compositing** with a set background color. "
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "execution_count": null,
295
+ "metadata": {},
296
+ "outputs": [],
297
+ "source": [
298
+ "renderer = PointsRenderer(\n",
299
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
300
+ " # Pass in background_color to the norm weighted compositor, setting the background color \n",
301
+ " # to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case red\n",
302
+ " compositor=NormWeightedCompositor(background_color=(1,0,0))\n",
303
+ ")\n",
304
+ "images = renderer(point_cloud)\n",
305
+ "plt.figure(figsize=(10, 10))\n",
306
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
307
+ "plt.axis(\"off\");"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "markdown",
312
+ "metadata": {},
313
+ "source": [
314
+ "## Using the pulsar backend\n",
315
+ "\n",
316
+ "Switching to the pulsar backend is easy! The pulsar backend has a compositor built-in, so the `compositor` argument is not required when creating it (a warning will be displayed if you provide it nevertheless). It pre-allocates memory on the rendering device, that's why it needs the `n_channels` at construction time.\n",
317
+ "\n",
318
+ "All parameters for the renderer forward function are batch-wise except the background color (in this example, `gamma`) and you have to provide as many values as you have examples in your batch. The background color is optional and by default set to all zeros. You can find a detailed explanation of how gamma influences the rendering function here in the paper [Fast Differentiable Raycasting for Neural Rendering using\n",
319
+ "Sphere-based Representations](https://arxiv.org/pdf/2004.07484.pdf).\n",
320
+ "\n",
321
+ "You can also use the `native` backend for the pulsar backend which already provides access to point opacity. The native backend can be imported from `pytorch3d.renderer.points.pulsar`; you can find examples for this in the folder `docs/examples`."
322
+ ]
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "execution_count": null,
327
+ "metadata": {},
328
+ "outputs": [],
329
+ "source": [
330
+ "renderer = PulsarPointsRenderer(\n",
331
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
332
+ " n_channels=4\n",
333
+ ").to(device)\n",
334
+ "\n",
335
+ "images = renderer(point_cloud, gamma=(1e-4,),\n",
336
+ " bg_col=torch.tensor([0.0, 1.0, 0.0, 1.0], dtype=torch.float32, device=device))\n",
337
+ "plt.figure(figsize=(10, 10))\n",
338
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
339
+ "plt.axis(\"off\");"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "markdown",
344
+ "metadata": {},
345
+ "source": [
346
+ "### View pointclouds in Plotly figures\n",
347
+ "\n",
348
+ "Here we use the PyTorch3D function `plot_scene` to render the pointcloud in a Plotly figure. `plot_scene` returns a plotly figure with trace and subplots defined by the input."
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": null,
354
+ "metadata": {},
355
+ "outputs": [],
356
+ "source": [
357
+ "plot_scene({\n",
358
+ " \"Pointcloud\": {\n",
359
+ " \"person\": point_cloud\n",
360
+ " }\n",
361
+ "})"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "markdown",
366
+ "metadata": {},
367
+ "source": [
368
+ "We will now render a batch of pointclouds. The first pointcloud is the same as above, and the second is all-black and offset by 2 in all dimensions so we can see them on the same plot. "
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "execution_count": null,
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "point_cloud_batch = Pointclouds(points=[verts, verts + 2], features=[rgb, torch.zeros_like(rgb)])\n",
378
+ "# render both in the same plot in different traces\n",
379
+ "fig = plot_scene({\n",
380
+ " \"Pointcloud\": {\n",
381
+ " \"person\": point_cloud_batch[0],\n",
382
+ " \"person2\": point_cloud_batch[1]\n",
383
+ " }\n",
384
+ "})\n",
385
+ "fig.show()"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "execution_count": null,
391
+ "metadata": {},
392
+ "outputs": [],
393
+ "source": [
394
+ "# render both in the same plot in one trace\n",
395
+ "fig = plot_scene({\n",
396
+ " \"Pointcloud\": {\n",
397
+ " \"2 people\": point_cloud_batch\n",
398
+ " }\n",
399
+ "})\n",
400
+ "fig.show()"
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "markdown",
405
+ "metadata": {},
406
+ "source": [
407
+ "For batches, we can also use `plot_batch_individually` to avoid constructing the scene dictionary ourselves."
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": null,
413
+ "metadata": {},
414
+ "outputs": [],
415
+ "source": [
416
+ "# render both in 1 row in different subplots\n",
417
+ "fig2 = plot_batch_individually(point_cloud_batch, ncols=2)\n",
418
+ "fig2.show()"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "code",
423
+ "execution_count": null,
424
+ "metadata": {},
425
+ "outputs": [],
426
+ "source": [
427
+ "# modify the plotly figure height and width\n",
428
+ "fig2.update_layout(height=500, width=500)\n",
429
+ "fig2.show()"
430
+ ]
431
+ },
432
+ {
433
+ "cell_type": "markdown",
434
+ "metadata": {},
435
+ "source": [
436
+ "We can also modify the axis arguments and axis backgrounds for either function, and title our plots in `plot_batch_individually`."
437
+ ]
438
+ },
439
+ {
440
+ "cell_type": "code",
441
+ "execution_count": null,
442
+ "metadata": {},
443
+ "outputs": [],
444
+ "source": [
445
+ "fig3 = plot_batch_individually(\n",
446
+ " point_cloud_batch, \n",
447
+ " xaxis={\"backgroundcolor\":\"rgb(200, 200, 230)\"},\n",
448
+ " yaxis={\"backgroundcolor\":\"rgb(230, 200, 200)\"},\n",
449
+ " zaxis={\"backgroundcolor\":\"rgb(200, 230, 200)\"}, \n",
450
+ " subplot_titles=[\"Pointcloud1\", \"Pointcloud2\"], # this should have a title for each subplot, titles can be \"\"\n",
451
+ " axis_args=AxisArgs(showgrid=True))\n",
452
+ "fig3.show()"
453
+ ]
454
+ }
455
+ ],
456
+ "metadata": {
457
+ "bento_stylesheets": {
458
+ "bento/extensions/flow/main.css": true,
459
+ "bento/extensions/kernel_selector/main.css": true,
460
+ "bento/extensions/kernel_ui/main.css": true,
461
+ "bento/extensions/new_kernel/main.css": true,
462
+ "bento/extensions/system_usage/main.css": true,
463
+ "bento/extensions/theme/main.css": true
464
+ },
465
+ "kernelspec": {
466
+ "display_name": "Python 3",
467
+ "language": "python",
468
+ "name": "python3"
469
+ },
470
+ "language_info": {
471
+ "codemirror_mode": {
472
+ "name": "ipython",
473
+ "version": 3
474
+ },
475
+ "file_extension": ".py",
476
+ "mimetype": "text/x-python",
477
+ "name": "python",
478
+ "nbconvert_exporter": "python",
479
+ "pygments_lexer": "ipython3",
480
+ "version": "3.6.8"
481
+ }
482
+ },
483
+ "nbformat": 4,
484
+ "nbformat_minor": 2
485
+ }
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_densepose.ipynb ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# Render DensePose \n",
17
+ "\n",
18
+ "DensePose refers to dense human pose representation: https://github.com/facebookresearch/DensePose. \n",
19
+ "In this tutorial, we provide an example of using DensePose data in PyTorch3D.\n",
20
+ "\n",
21
+ "This tutorial shows how to:\n",
22
+ "- load a mesh and textures from densepose `.mat` and `.pkl` files\n",
23
+ "- set up a renderer \n",
24
+ "- render the mesh \n",
25
+ "- vary the rendering settings such as lighting and camera position"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "markdown",
30
+ "metadata": {
31
+ "colab_type": "text",
32
+ "id": "Bnj3THhzfBLf"
33
+ },
34
+ "source": [
35
+ "## Import modules"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "metadata": {},
41
+ "source": [
42
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "import os\n",
52
+ "import sys\n",
53
+ "import torch\n",
54
+ "import subprocess\n",
55
+ "need_pytorch3d=False\n",
56
+ "try:\n",
57
+ " import pytorch3d\n",
58
+ "except ModuleNotFoundError:\n",
59
+ " need_pytorch3d=True\n",
60
+ "if need_pytorch3d:\n",
61
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
62
+ " version_str=\"\".join([\n",
63
+ " f\"py3{sys.version_info.minor}_cu\",\n",
64
+ " torch.version.cuda.replace(\".\",\"\"),\n",
65
+ " f\"_pyt{pyt_version_str}\"\n",
66
+ " ])\n",
67
+ " !pip install iopath\n",
68
+ " if sys.platform.startswith(\"linux\"):\n",
69
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
70
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
71
+ " pip_list = !pip freeze\n",
72
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
73
+ " if need_pytorch3d:\n",
74
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
75
+ "if need_pytorch3d:\n",
76
+ " print(\"Installing PyTorch3D from source\")\n",
77
+ " !pip install ninja\n",
78
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "metadata": {},
85
+ "outputs": [],
86
+ "source": [
87
+ "# We also install chumpy as it is needed to load the SMPL model pickle file.\n",
88
+ "!pip install chumpy"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "import os\n",
98
+ "import torch\n",
99
+ "import matplotlib.pyplot as plt\n",
100
+ "import numpy as np\n",
101
+ "\n",
102
+ "# libraries for reading data from files\n",
103
+ "from scipy.io import loadmat\n",
104
+ "from PIL import Image\n",
105
+ "import pickle\n",
106
+ "\n",
107
+ "# Data structures and functions for rendering\n",
108
+ "from pytorch3d.structures import Meshes\n",
109
+ "from pytorch3d.renderer import (\n",
110
+ " look_at_view_transform,\n",
111
+ " FoVPerspectiveCameras, \n",
112
+ " PointLights, \n",
113
+ " DirectionalLights, \n",
114
+ " Materials, \n",
115
+ " RasterizationSettings, \n",
116
+ " MeshRenderer, \n",
117
+ " MeshRasterizer, \n",
118
+ " SoftPhongShader,\n",
119
+ " TexturesUV\n",
120
+ ")\n",
121
+ "\n",
122
+ "# add path for demo utils functions \n",
123
+ "import sys\n",
124
+ "import os\n",
125
+ "sys.path.append(os.path.abspath(''))"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "metadata": {},
131
+ "source": [
132
+ "## Load the SMPL model\n",
133
+ "\n",
134
+ "#### Download the SMPL model\n",
135
+ "- Go to https://smpl.is.tue.mpg.de/download.php and sign up.\n",
136
+ "- Download SMPL for Python Users and unzip.\n",
137
+ "- Copy the file male template file **'models/basicModel_m_lbs_10_207_0_v1.0.0.pkl'** to the data/DensePose/ folder.\n",
138
+ " - rename the file to **'smpl_model.pkl'** or rename the string where it's commented below\n",
139
+ " \n",
140
+ "If running this notebook using Google Colab, run the following cell to fetch the texture and UV values and save it at the correct path."
141
+ ]
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "execution_count": null,
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "# Texture image\n",
150
+ "!wget -P data/DensePose https://raw.githubusercontent.com/facebookresearch/DensePose/master/DensePoseData/demo_data/texture_from_SURREAL.png\n",
151
+ "\n",
152
+ "# UV_processed.mat\n",
153
+ "!wget https://dl.fbaipublicfiles.com/densepose/densepose_uv_data.tar.gz\n",
154
+ "!tar xvf densepose_uv_data.tar.gz -C data/DensePose\n",
155
+ "!rm densepose_uv_data.tar.gz"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "metadata": {},
161
+ "source": [
162
+ "Load our texture UV data and our SMPL data, with some processing to correct data values and format."
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "execution_count": null,
168
+ "metadata": {},
169
+ "outputs": [],
170
+ "source": [
171
+ "# Setup\n",
172
+ "if torch.cuda.is_available():\n",
173
+ " device = torch.device(\"cuda:0\")\n",
174
+ " torch.cuda.set_device(device)\n",
175
+ "else:\n",
176
+ " device = torch.device(\"cpu\")\n",
177
+ " \n",
178
+ "# Set paths\n",
179
+ "DATA_DIR = \"./data\"\n",
180
+ "data_filename = os.path.join(DATA_DIR, \"DensePose/UV_Processed.mat\")\n",
181
+ "tex_filename = os.path.join(DATA_DIR,\"DensePose/texture_from_SURREAL.png\")\n",
182
+ "# rename your .pkl file or change this string\n",
183
+ "verts_filename = os.path.join(DATA_DIR, \"DensePose/smpl_model.pkl\")\n",
184
+ "\n",
185
+ "\n",
186
+ "# Load SMPL and texture data\n",
187
+ "with open(verts_filename, 'rb') as f:\n",
188
+ " data = pickle.load(f, encoding='latin1') \n",
189
+ " v_template = torch.Tensor(data['v_template']).to(device) # (6890, 3)\n",
190
+ "ALP_UV = loadmat(data_filename)\n",
191
+ "with Image.open(tex_filename) as image:\n",
192
+ " np_image = np.asarray(image.convert(\"RGB\")).astype(np.float32)\n",
193
+ "tex = torch.from_numpy(np_image / 255.)[None].to(device)\n",
194
+ "\n",
195
+ "verts = torch.from_numpy((ALP_UV[\"All_vertices\"]).astype(int)).squeeze().to(device) # (7829,)\n",
196
+ "U = torch.Tensor(ALP_UV['All_U_norm']).to(device) # (7829, 1)\n",
197
+ "V = torch.Tensor(ALP_UV['All_V_norm']).to(device) # (7829, 1)\n",
198
+ "faces = torch.from_numpy((ALP_UV['All_Faces'] - 1).astype(int)).to(device) # (13774, 3)\n",
199
+ "face_indices = torch.Tensor(ALP_UV['All_FaceIndices']).squeeze() # (13774,)"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "execution_count": null,
205
+ "metadata": {},
206
+ "outputs": [],
207
+ "source": [
208
+ "# Display the texture image\n",
209
+ "plt.figure(figsize=(10, 10))\n",
210
+ "plt.imshow(tex.squeeze(0).cpu())\n",
211
+ "plt.axis(\"off\");"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "markdown",
216
+ "metadata": {},
217
+ "source": [
218
+ "In DensePose, the body mesh is split into 24 parts. In the texture image, we can see the 24 parts are separated out into individual (200, 200) images per body part. The convention in DensePose is that each face in the mesh is associated with a body part (given by the face_indices tensor above). The vertex UV values (in the range [0, 1]) for each face are specific to the (200, 200) size texture map for the part of the body that the mesh face corresponds to. We cannot use them directly with the entire texture map. We have to offset the vertex UV values depending on what body part the associated face corresponds to."
219
+ ]
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "execution_count": null,
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "# Map each face to a (u, v) offset\n",
228
+ "offset_per_part = {}\n",
229
+ "already_offset = set()\n",
230
+ "cols, rows = 4, 6\n",
231
+ "for i, u in enumerate(np.linspace(0, 1, cols, endpoint=False)):\n",
232
+ " for j, v in enumerate(np.linspace(0, 1, rows, endpoint=False)):\n",
233
+ " part = rows * i + j + 1 # parts are 1-indexed in face_indices\n",
234
+ " offset_per_part[part] = (u, v)\n",
235
+ "\n",
236
+ "U_norm = U.clone()\n",
237
+ "V_norm = V.clone()\n",
238
+ "\n",
239
+ "# iterate over faces and offset the corresponding vertex u and v values\n",
240
+ "for i in range(len(faces)):\n",
241
+ " face_vert_idxs = faces[i]\n",
242
+ " part = face_indices[i]\n",
243
+ " offset_u, offset_v = offset_per_part[int(part.item())]\n",
244
+ " \n",
245
+ " for vert_idx in face_vert_idxs: \n",
246
+ " # vertices are reused, but we don't want to offset multiple times\n",
247
+ " if vert_idx.item() not in already_offset:\n",
248
+ " # offset u value\n",
249
+ " U_norm[vert_idx] = U[vert_idx] / cols + offset_u\n",
250
+ " # offset v value\n",
251
+ " # this also flips each part locally, as each part is upside down\n",
252
+ " V_norm[vert_idx] = (1 - V[vert_idx]) / rows + offset_v\n",
253
+ " # add vertex to our set tracking offsetted vertices\n",
254
+ " already_offset.add(vert_idx.item())\n",
255
+ "\n",
256
+ "# invert V values\n",
257
+ "V_norm = 1 - V_norm"
258
+ ]
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "execution_count": null,
263
+ "metadata": {},
264
+ "outputs": [],
265
+ "source": [
266
+ "# create our verts_uv values\n",
267
+ "verts_uv = torch.cat([U_norm[None],V_norm[None]], dim=2) # (1, 7829, 2)\n",
268
+ "\n",
269
+ "# There are 6890 xyz vertex coordinates but 7829 vertex uv coordinates. \n",
270
+ "# This is because the same vertex can be shared by multiple faces where each face may correspond to a different body part. \n",
271
+ "# Therefore when initializing the Meshes class,\n",
272
+ "# we need to map each of the vertices referenced by the DensePose faces (in verts, which is the \"All_vertices\" field)\n",
273
+ "# to the correct xyz coordinate in the SMPL template mesh.\n",
274
+ "v_template_extended = v_template[verts-1][None] # (1, 7829, 3)"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "markdown",
279
+ "metadata": {},
280
+ "source": [
281
+ "### Create our textured mesh \n",
282
+ "\n",
283
+ "**Meshes** is a unique datastructure provided in PyTorch3D for working with batches of meshes of different sizes.\n",
284
+ "\n",
285
+ "**TexturesUV** is an auxiliary datastructure for storing vertex uv and texture maps for meshes."
286
+ ]
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "execution_count": null,
291
+ "metadata": {},
292
+ "outputs": [],
293
+ "source": [
294
+ "texture = TexturesUV(maps=tex, faces_uvs=faces[None], verts_uvs=verts_uv)\n",
295
+ "mesh = Meshes(v_template_extended, faces[None], texture)"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "markdown",
300
+ "metadata": {},
301
+ "source": [
302
+ "## Create a renderer"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "execution_count": null,
308
+ "metadata": {},
309
+ "outputs": [],
310
+ "source": [
311
+ "# Initialize a camera.\n",
312
+ "# World coordinates +Y up, +X left and +Z in.\n",
313
+ "R, T = look_at_view_transform(2.7, 0, 0) \n",
314
+ "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
315
+ "\n",
316
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
317
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
318
+ "# and blur_radius=0.0. \n",
319
+ "raster_settings = RasterizationSettings(\n",
320
+ " image_size=512, \n",
321
+ " blur_radius=0.0, \n",
322
+ " faces_per_pixel=1, \n",
323
+ ")\n",
324
+ "\n",
325
+ "# Place a point light in front of the person. \n",
326
+ "lights = PointLights(device=device, location=[[0.0, 0.0, 2.0]])\n",
327
+ "\n",
328
+ "# Create a Phong renderer by composing a rasterizer and a shader. The textured Phong shader will \n",
329
+ "# interpolate the texture uv coordinates for each vertex, sample from a texture image and \n",
330
+ "# apply the Phong lighting model\n",
331
+ "renderer = MeshRenderer(\n",
332
+ " rasterizer=MeshRasterizer(\n",
333
+ " cameras=cameras, \n",
334
+ " raster_settings=raster_settings\n",
335
+ " ),\n",
336
+ " shader=SoftPhongShader(\n",
337
+ " device=device, \n",
338
+ " cameras=cameras,\n",
339
+ " lights=lights\n",
340
+ " )\n",
341
+ ")"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "markdown",
346
+ "metadata": {},
347
+ "source": [
348
+ "Render the textured mesh we created from the SMPL model and texture map."
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": null,
354
+ "metadata": {},
355
+ "outputs": [],
356
+ "source": [
357
+ "images = renderer(mesh)\n",
358
+ "plt.figure(figsize=(10, 10))\n",
359
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
360
+ "plt.axis(\"off\");"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "metadata": {},
366
+ "source": [
367
+ "### Different view and lighting of the body\n",
368
+ "\n",
369
+ "We can also change many other settings in the rendering pipeline. Here we:\n",
370
+ "\n",
371
+ "- change the **viewing angle** of the camera\n",
372
+ "- change the **position** of the point light"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "code",
377
+ "execution_count": null,
378
+ "metadata": {},
379
+ "outputs": [],
380
+ "source": [
381
+ "# Rotate the person by increasing the elevation and azimuth angles to view the back of the person from above. \n",
382
+ "R, T = look_at_view_transform(2.7, 10, 180)\n",
383
+ "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
384
+ "\n",
385
+ "# Move the light location so the light is shining on the person's back. \n",
386
+ "lights.location = torch.tensor([[2.0, 2.0, -2.0]], device=device)\n",
387
+ "\n",
388
+ "# Re render the mesh, passing in keyword arguments for the modified components.\n",
389
+ "images = renderer(mesh, lights=lights, cameras=cameras)"
390
+ ]
391
+ },
392
+ {
393
+ "cell_type": "code",
394
+ "execution_count": null,
395
+ "metadata": {},
396
+ "outputs": [],
397
+ "source": [
398
+ "plt.figure(figsize=(10, 10))\n",
399
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
400
+ "plt.axis(\"off\");"
401
+ ]
402
+ },
403
+ {
404
+ "cell_type": "markdown",
405
+ "metadata": {},
406
+ "source": [
407
+ "## Conclusion\n",
408
+ "In this tutorial, we've learned how to construct a **textured mesh** from **DensePose model and uv data**, as well as initialize a **Renderer** and change the viewing angle and lighting of our rendered mesh."
409
+ ]
410
+ }
411
+ ],
412
+ "metadata": {
413
+ "bento_stylesheets": {
414
+ "bento/extensions/flow/main.css": true,
415
+ "bento/extensions/kernel_selector/main.css": true,
416
+ "bento/extensions/kernel_ui/main.css": true,
417
+ "bento/extensions/new_kernel/main.css": true,
418
+ "bento/extensions/system_usage/main.css": true,
419
+ "bento/extensions/theme/main.css": true
420
+ },
421
+ "kernelspec": {
422
+ "display_name": "pytorch3d_etc (local)",
423
+ "language": "python",
424
+ "name": "pytorch3d_etc_local"
425
+ },
426
+ "language_info": {
427
+ "codemirror_mode": {
428
+ "name": "ipython",
429
+ "version": 3
430
+ },
431
+ "file_extension": ".py",
432
+ "mimetype": "text/x-python",
433
+ "name": "python",
434
+ "nbconvert_exporter": "python",
435
+ "pygments_lexer": "ipython3",
436
+ "version": "3.7.5+"
437
+ }
438
+ },
439
+ "nbformat": 4,
440
+ "nbformat_minor": 2
441
+ }
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+ from .datatypes import Device, get_device, make_device
10
+
11
+
12
+ __all__ = [k for k in globals().keys() if not k.startswith("_")]
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__pycache__/datatypes.cpython-310.pyc ADDED
Binary file (1.52 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/compat.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+ from typing import Sequence, Tuple, Union
10
+
11
+ import torch
12
+
13
+
14
+ """
15
+ Some functions which depend on PyTorch or Python versions.
16
+ """
17
+
18
+
19
+ def meshgrid_ij(
20
+ *A: Union[torch.Tensor, Sequence[torch.Tensor]]
21
+ ) -> Tuple[torch.Tensor, ...]: # pragma: no cover
22
+ """
23
+ Like torch.meshgrid was before PyTorch 1.10.0, i.e. with indexing set to ij
24
+ """
25
+ if (
26
+ # pyre-fixme[16]: Callable `meshgrid` has no attribute `__kwdefaults__`.
27
+ torch.meshgrid.__kwdefaults__ is not None
28
+ and "indexing" in torch.meshgrid.__kwdefaults__
29
+ ):
30
+ # PyTorch >= 1.10.0
31
+ # pyre-fixme[6]: For 1st param expected `Union[List[Tensor], Tensor]` but
32
+ # got `Union[Sequence[Tensor], Tensor]`.
33
+ return torch.meshgrid(*A, indexing="ij")
34
+ # pyre-fixme[6]: For 1st param expected `Union[List[Tensor], Tensor]` but got
35
+ # `Union[Sequence[Tensor], Tensor]`.
36
+ return torch.meshgrid(*A)
37
+
38
+
39
+ def prod(iterable, *, start=1):
40
+ """
41
+ Like math.prod in Python 3.8 and later.
42
+ """
43
+ for i in iterable:
44
+ start *= i
45
+ return start
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/datatypes.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+ from typing import Optional, Union
10
+
11
+ import torch
12
+
13
+
14
+ Device = Union[str, torch.device]
15
+
16
+
17
+ def make_device(device: Device) -> torch.device:
18
+ """
19
+ Makes an actual torch.device object from the device specified as
20
+ either a string or torch.device object. If the device is `cuda` without
21
+ a specific index, the index of the current device is assigned.
22
+
23
+ Args:
24
+ device: Device (as str or torch.device)
25
+
26
+ Returns:
27
+ A matching torch.device object
28
+ """
29
+ device = torch.device(device) if isinstance(device, str) else device
30
+ if device.type == "cuda" and device.index is None:
31
+ # If cuda but with no index, then the current cuda device is indicated.
32
+ # In that case, we fix to that device
33
+ device = torch.device(f"cuda:{torch.cuda.current_device()}")
34
+ return device
35
+
36
+
37
+ def get_device(x, device: Optional[Device] = None) -> torch.device:
38
+ """
39
+ Gets the device of the specified variable x if it is a tensor, or
40
+ falls back to a default CPU device otherwise. Allows overriding by
41
+ providing an explicit device.
42
+
43
+ Args:
44
+ x: a torch.Tensor to get the device from or another type
45
+ device: Device (as str or torch.device) to fall back to
46
+
47
+ Returns:
48
+ A matching torch.device object
49
+ """
50
+
51
+ # User overrides device
52
+ if device is not None:
53
+ return make_device(device)
54
+
55
+ # Set device based on input tensor
56
+ if torch.is_tensor(x):
57
+ return x.device
58
+
59
+ # Default device is cpu
60
+ return torch.device("cpu")
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/linear_with_repeat.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+ import math
10
+ from typing import Tuple
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch.nn import init, Parameter
15
+
16
+
17
+ class LinearWithRepeat(torch.nn.Module):
18
+ """
19
+ if x has shape (..., k, n1)
20
+ and y has shape (..., n2)
21
+ then
22
+ LinearWithRepeat(n1 + n2, out_features).forward((x,y))
23
+ is equivalent to
24
+ Linear(n1 + n2, out_features).forward(
25
+ torch.cat([x, y.unsqueeze(-2).expand(..., k, n2)], dim=-1)
26
+ )
27
+
28
+ Or visually:
29
+ Given the following, for each ray,
30
+
31
+ feature ->
32
+
33
+ ray xxxxxxxx
34
+ position xxxxxxxx
35
+ | xxxxxxxx
36
+ v xxxxxxxx
37
+
38
+
39
+ and
40
+ yyyyyyyy
41
+
42
+ where the y's do not depend on the position
43
+ but only on the ray,
44
+ we want to evaluate a Linear layer on both
45
+ types of data at every position.
46
+
47
+ It's as if we constructed
48
+
49
+ xxxxxxxxyyyyyyyy
50
+ xxxxxxxxyyyyyyyy
51
+ xxxxxxxxyyyyyyyy
52
+ xxxxxxxxyyyyyyyy
53
+
54
+ and sent that through the Linear.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ in_features: int,
60
+ out_features: int,
61
+ bias: bool = True,
62
+ device=None,
63
+ dtype=None,
64
+ ) -> None:
65
+ """
66
+ Copied from torch.nn.Linear.
67
+ """
68
+ factory_kwargs = {"device": device, "dtype": dtype}
69
+ super().__init__()
70
+ self.in_features = in_features
71
+ self.out_features = out_features
72
+ self.weight = Parameter(
73
+ torch.empty((out_features, in_features), **factory_kwargs)
74
+ )
75
+ if bias:
76
+ self.bias = Parameter(torch.empty(out_features, **factory_kwargs))
77
+ else:
78
+ self.register_parameter("bias", None)
79
+ self.reset_parameters()
80
+
81
+ def reset_parameters(self) -> None:
82
+ """
83
+ Copied from torch.nn.Linear.
84
+ """
85
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
86
+ if self.bias is not None:
87
+ fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
88
+ bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
89
+ init.uniform_(self.bias, -bound, bound)
90
+
91
+ def forward(self, input: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
92
+ n1 = input[0].shape[-1]
93
+ output1 = F.linear(input[0], self.weight[:, :n1], self.bias)
94
+ output2 = F.linear(input[1], self.weight[:, n1:], None)
95
+ return output1 + output2.unsqueeze(-2)
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+ from .symeig3x3 import symeig3x3
10
+ from .utils import _safe_det_3x3
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (303 Bytes). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pyc ADDED
Binary file (9.64 kB). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pyc ADDED
Binary file (941 Bytes). View file
 
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # pyre-unsafe
8
+
9
+
10
+ import torch
11
+
12
+
13
+ def _safe_det_3x3(t: torch.Tensor):
14
+ """
15
+ Fast determinant calculation for a batch of 3x3 matrices.
16
+
17
+ Note, result of this function might not be the same as `torch.det()`.
18
+ The differences might be in the last significant digit.
19
+
20
+ Args:
21
+ t: Tensor of shape (N, 3, 3).
22
+
23
+ Returns:
24
+ Tensor of shape (N) with determinants.
25
+ """
26
+
27
+ det = (
28
+ t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1])
29
+ - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2])
30
+ + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1])
31
+ )
32
+
33
+ return det
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.cu ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #include <ATen/ATen.h>
10
+ #include <ATen/core/TensorAccessor.h>
11
+ #include <ATen/cuda/CUDAContext.h>
12
+ #include <c10/cuda/CUDAGuard.h>
13
+
14
+ #include <cuda.h>
15
+ #include <cuda_runtime.h>
16
+
17
+ #include <stdio.h>
18
+ #include <vector>
19
+
20
+ __constant__ const float kEpsilon = 1e-9;
21
+
22
+ // TODO(gkioxari) support all data types once AtomicAdd supports doubles.
23
+ // Currently, support is for floats only.
24
+ __global__ void alphaCompositeCudaForwardKernel(
25
+ // clang-format off
26
+ at::PackedTensorAccessor64<float, 4, at::RestrictPtrTraits> result,
27
+ const at::PackedTensorAccessor64<float, 2, at::RestrictPtrTraits> features,
28
+ const at::PackedTensorAccessor64<float, 4, at::RestrictPtrTraits> alphas,
29
+ const at::PackedTensorAccessor64<int64_t, 4, at::RestrictPtrTraits> points_idx) {
30
+ // clang-format on
31
+ const int64_t batch_size = result.size(0);
32
+ const int64_t C = features.size(0);
33
+ const int64_t H = points_idx.size(2);
34
+ const int64_t W = points_idx.size(3);
35
+
36
+ // Get the batch and index
37
+ const int batch = blockIdx.x;
38
+
39
+ const int num_pixels = C * H * W;
40
+ const int num_threads = gridDim.y * blockDim.x;
41
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
42
+
43
+ // Iterate over each feature in each pixel
44
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
45
+ int ch = pid / (H * W);
46
+ int j = (pid % (H * W)) / W;
47
+ int i = (pid % (H * W)) % W;
48
+
49
+ // alphacomposite the different values
50
+ float cum_alpha = 1.;
51
+ // Iterate through the closest K points for this pixel
52
+ for (int k = 0; k < points_idx.size(1); ++k) {
53
+ int n_idx = points_idx[batch][k][j][i];
54
+
55
+ // Sentinel value is -1 indicating no point overlaps the pixel
56
+ if (n_idx < 0) {
57
+ continue;
58
+ }
59
+
60
+ float alpha = alphas[batch][k][j][i];
61
+ // TODO(gkioxari) It might be more efficient to have threads write in a
62
+ // local variable, and move atomicAdd outside of the loop such that
63
+ // atomicAdd is executed once per thread.
64
+ atomicAdd(
65
+ &result[batch][ch][j][i], features[ch][n_idx] * cum_alpha * alpha);
66
+ cum_alpha = cum_alpha * (1 - alpha);
67
+ }
68
+ }
69
+ }
70
+
71
+ // TODO(gkioxari) support all data types once AtomicAdd supports doubles.
72
+ // Currently, support is for floats only.
73
+ __global__ void alphaCompositeCudaBackwardKernel(
74
+ // clang-format off
75
+ at::PackedTensorAccessor64<float, 2, at::RestrictPtrTraits> grad_features,
76
+ at::PackedTensorAccessor64<float, 4, at::RestrictPtrTraits> grad_alphas,
77
+ const at::PackedTensorAccessor64<float, 4, at::RestrictPtrTraits> grad_outputs,
78
+ const at::PackedTensorAccessor64<float, 2, at::RestrictPtrTraits> features,
79
+ const at::PackedTensorAccessor64<float, 4, at::RestrictPtrTraits> alphas,
80
+ const at::PackedTensorAccessor64<int64_t, 4, at::RestrictPtrTraits> points_idx) {
81
+ // clang-format on
82
+ const int64_t batch_size = points_idx.size(0);
83
+ const int64_t C = features.size(0);
84
+ const int64_t H = points_idx.size(2);
85
+ const int64_t W = points_idx.size(3);
86
+
87
+ // Get the batch and index
88
+ const int batch = blockIdx.x;
89
+
90
+ const int num_pixels = C * H * W;
91
+ const int num_threads = gridDim.y * blockDim.x;
92
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
93
+
94
+ // Parallelize over each feature in each pixel in images of size H * W,
95
+ // for each image in the batch of size batch_size
96
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
97
+ int ch = pid / (H * W);
98
+ int j = (pid % (H * W)) / W;
99
+ int i = (pid % (H * W)) % W;
100
+
101
+ // alphacomposite the different values
102
+ float cum_alpha = 1.;
103
+ // Iterate through the closest K points for this pixel
104
+ for (int k = 0; k < points_idx.size(1); ++k) {
105
+ int n_idx = points_idx[batch][k][j][i];
106
+
107
+ // Sentinel value is -1 indicating no point overlaps the pixel
108
+ if (n_idx < 0) {
109
+ continue;
110
+ }
111
+ float alpha = alphas[batch][k][j][i];
112
+
113
+ // TODO(gkioxari) It might be more efficient to have threads write in a
114
+ // local variable, and move atomicAdd outside of the loop such that
115
+ // atomicAdd is executed once per thread.
116
+ atomicAdd(
117
+ &grad_alphas[batch][k][j][i],
118
+ cum_alpha * features[ch][n_idx] * grad_outputs[batch][ch][j][i]);
119
+ atomicAdd(
120
+ &grad_features[ch][n_idx],
121
+ cum_alpha * alpha * grad_outputs[batch][ch][j][i]);
122
+
123
+ // Iterate over all (K-1) nearest points to update gradient
124
+ for (int t = 0; t < k; ++t) {
125
+ int t_idx = points_idx[batch][t][j][i];
126
+ // Sentinel value is -1, indicating no point overlaps this pixel
127
+ if (t_idx < 0) {
128
+ continue;
129
+ }
130
+ float alpha_tvalue = alphas[batch][t][j][i];
131
+ // TODO(gkioxari) It might be more efficient to have threads write in a
132
+ // local variable, and move atomicAdd outside of the loop such that
133
+ // atomicAdd is executed once per thread.
134
+ atomicAdd(
135
+ &grad_alphas[batch][t][j][i],
136
+ -grad_outputs[batch][ch][j][i] * features[ch][n_idx] * cum_alpha *
137
+ alpha / (1 - alpha_tvalue + kEpsilon));
138
+ }
139
+
140
+ cum_alpha = cum_alpha * (1 - alphas[batch][k][j][i]);
141
+ }
142
+ }
143
+ }
144
+
145
+ at::Tensor alphaCompositeCudaForward(
146
+ const at::Tensor& features,
147
+ const at::Tensor& alphas,
148
+ const at::Tensor& points_idx) {
149
+ // Check inputs are on the same device
150
+ at::TensorArg features_t{features, "features", 1},
151
+ alphas_t{alphas, "alphas", 2}, points_idx_t{points_idx, "points_idx", 3};
152
+ at::CheckedFrom c = "alphaCompositeCudaForward";
153
+ at::checkAllSameGPU(c, {features_t, alphas_t, points_idx_t});
154
+ at::checkAllSameType(c, {features_t, alphas_t});
155
+
156
+ // Set the device for the kernel launch based on the device of the input
157
+ at::cuda::CUDAGuard device_guard(features.device());
158
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
159
+
160
+ const int64_t batch_size = points_idx.size(0);
161
+ const int64_t C = features.size(0);
162
+ const int64_t H = points_idx.size(2);
163
+ const int64_t W = points_idx.size(3);
164
+
165
+ auto result = at::zeros({batch_size, C, H, W}, features.options());
166
+
167
+ if (result.numel() == 0) {
168
+ AT_CUDA_CHECK(cudaGetLastError());
169
+ return result;
170
+ }
171
+
172
+ const dim3 threadsPerBlock(64);
173
+ const dim3 numBlocks(batch_size, 1024 / batch_size + 1);
174
+
175
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
176
+ // doubles. Currently, support is for floats only.
177
+ alphaCompositeCudaForwardKernel<<<numBlocks, threadsPerBlock, 0, stream>>>(
178
+ // clang-format off
179
+ // As we are using packed accessors here the tensors
180
+ // do not need to be made contiguous.
181
+ result.packed_accessor64<float, 4, at::RestrictPtrTraits>(),
182
+ features.packed_accessor64<float, 2, at::RestrictPtrTraits>(),
183
+ alphas.packed_accessor64<float, 4, at::RestrictPtrTraits>(),
184
+ points_idx.packed_accessor64<int64_t, 4, at::RestrictPtrTraits>());
185
+ // clang-format on
186
+ AT_CUDA_CHECK(cudaGetLastError());
187
+ return result;
188
+ }
189
+
190
+ std::tuple<at::Tensor, at::Tensor> alphaCompositeCudaBackward(
191
+ const at::Tensor& grad_outputs,
192
+ const at::Tensor& features,
193
+ const at::Tensor& alphas,
194
+ const at::Tensor& points_idx) {
195
+ // Check inputs are on the same device
196
+ at::TensorArg grad_outputs_t{grad_outputs, "grad_outputs", 1},
197
+ features_t{features, "features", 2}, alphas_t{alphas, "alphas", 3},
198
+ points_idx_t{points_idx, "points_idx", 4};
199
+ at::CheckedFrom c = "alphaCompositeCudaBackward";
200
+ at::checkAllSameGPU(c, {grad_outputs_t, features_t, alphas_t, points_idx_t});
201
+ at::checkAllSameType(c, {grad_outputs_t, features_t, alphas_t});
202
+
203
+ // Set the device for the kernel launch based on the device of the input
204
+ at::cuda::CUDAGuard device_guard(features.device());
205
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
206
+
207
+ auto grad_features = at::zeros_like(features);
208
+ auto grad_alphas = at::zeros_like(alphas);
209
+
210
+ if (grad_features.numel() == 0 || grad_alphas.numel() == 0) {
211
+ AT_CUDA_CHECK(cudaGetLastError());
212
+ return std::make_tuple(grad_features, grad_alphas);
213
+ }
214
+
215
+ const int64_t bs = alphas.size(0);
216
+
217
+ const dim3 threadsPerBlock(64);
218
+ const dim3 numBlocks(bs, 1024 / bs + 1);
219
+
220
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
221
+ // doubles. Currently, support is for floats only.
222
+ alphaCompositeCudaBackwardKernel<<<numBlocks, threadsPerBlock, 0, stream>>>(
223
+ // clang-format off
224
+ // As we are using packed accessors here the tensors
225
+ // do not need to be made contiguous.
226
+ grad_features.packed_accessor64<float, 2, at::RestrictPtrTraits>(),
227
+ grad_alphas.packed_accessor64<float, 4, at::RestrictPtrTraits>(),
228
+ grad_outputs.packed_accessor64<float, 4, at::RestrictPtrTraits>(),
229
+ features.packed_accessor64<float, 2, at::RestrictPtrTraits>(),
230
+ alphas.packed_accessor64<float, 4, at::RestrictPtrTraits>(),
231
+ points_idx.packed_accessor64<int64_t, 4, at::RestrictPtrTraits>());
232
+ // clang-format on
233
+ AT_CUDA_CHECK(cudaGetLastError());
234
+ return std::make_tuple(grad_features, grad_alphas);
235
+ }
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.h ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #include <torch/extension.h>
10
+ #include "utils/pytorch3d_cutils.h"
11
+
12
+ #include <vector>
13
+
14
+ // Perform alpha compositing of points in a z-buffer.
15
+ //
16
+ // Inputs:
17
+ // features: FloatTensor of shape (C, P) which gives the features
18
+ // of each point where C is the size of the feature and
19
+ // P the number of points.
20
+ // alphas: FloatTensor of shape (N, points_per_pixel, H, W) where
21
+ // points_per_pixel is the number of points in the z-buffer
22
+ // sorted in z-order, and (H, W) is the image size.
23
+ // points_idx: IntTensor of shape (N, points_per_pixel, H, W) giving the
24
+ // indices of the nearest points at each pixel, sorted in z-order.
25
+ // Returns:
26
+ // weighted_fs: FloatTensor of shape (N, C, H, W) giving the accumulated
27
+ // feature for each point. Concretely, it gives:
28
+ // weighted_fs[b,c,i,j] = sum_k cum_alpha_k *
29
+ // features[c,points_idx[b,k,i,j]]
30
+ // where cum_alpha_k =
31
+ // alphas[b,k,i,j] * prod_l=0..k-1 (1 - alphas[b,l,i,j])
32
+
33
+ // CUDA declarations
34
+ #ifdef WITH_CUDA
35
+ torch::Tensor alphaCompositeCudaForward(
36
+ const torch::Tensor& features,
37
+ const torch::Tensor& alphas,
38
+ const torch::Tensor& points_idx);
39
+
40
+ std::tuple<torch::Tensor, torch::Tensor> alphaCompositeCudaBackward(
41
+ const torch::Tensor& grad_outputs,
42
+ const torch::Tensor& features,
43
+ const torch::Tensor& alphas,
44
+ const torch::Tensor& points_idx);
45
+ #endif
46
+
47
+ // C++ declarations
48
+ torch::Tensor alphaCompositeCpuForward(
49
+ const torch::Tensor& features,
50
+ const torch::Tensor& alphas,
51
+ const torch::Tensor& points_idx);
52
+
53
+ std::tuple<torch::Tensor, torch::Tensor> alphaCompositeCpuBackward(
54
+ const torch::Tensor& grad_outputs,
55
+ const torch::Tensor& features,
56
+ const torch::Tensor& alphas,
57
+ const torch::Tensor& points_idx);
58
+
59
+ torch::Tensor alphaCompositeForward(
60
+ torch::Tensor& features,
61
+ torch::Tensor& alphas,
62
+ torch::Tensor& points_idx) {
63
+ features = features.contiguous();
64
+ alphas = alphas.contiguous();
65
+ points_idx = points_idx.contiguous();
66
+
67
+ if (features.is_cuda()) {
68
+ #ifdef WITH_CUDA
69
+ CHECK_CUDA(features);
70
+ CHECK_CUDA(alphas);
71
+ CHECK_CUDA(points_idx);
72
+ return alphaCompositeCudaForward(features, alphas, points_idx);
73
+ #else
74
+ AT_ERROR("Not compiled with GPU support");
75
+ #endif
76
+ } else {
77
+ return alphaCompositeCpuForward(features, alphas, points_idx);
78
+ }
79
+ }
80
+
81
+ std::tuple<torch::Tensor, torch::Tensor> alphaCompositeBackward(
82
+ torch::Tensor& grad_outputs,
83
+ torch::Tensor& features,
84
+ torch::Tensor& alphas,
85
+ torch::Tensor& points_idx) {
86
+ grad_outputs = grad_outputs.contiguous();
87
+ features = features.contiguous();
88
+ alphas = alphas.contiguous();
89
+ points_idx = points_idx.contiguous();
90
+
91
+ if (grad_outputs.is_cuda()) {
92
+ #ifdef WITH_CUDA
93
+ CHECK_CUDA(grad_outputs);
94
+ CHECK_CUDA(features);
95
+ CHECK_CUDA(alphas);
96
+ CHECK_CUDA(points_idx);
97
+
98
+ return alphaCompositeCudaBackward(
99
+ grad_outputs, features, alphas, points_idx);
100
+ #else
101
+ AT_ERROR("Not compiled with GPU support");
102
+ #endif
103
+ } else {
104
+ return alphaCompositeCpuBackward(
105
+ grad_outputs, features, alphas, points_idx);
106
+ }
107
+ }