diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..be547e340ec4f7fe1b9348d022d36673fe575bd8
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This example demonstrates the most trivial, direct interface of the pulsar
+sphere renderer. It renders and saves an image with 10 random spheres.
+Output: basic.png.
+"""
+import logging
+import math
+from os import path
+
+import imageio
+import torch
+from pytorch3d.renderer.points.pulsar import Renderer
+
+
+LOGGER = logging.getLogger(__name__)
+
+
+def cli():
+ """
+ Basic example for the pulsar sphere renderer.
+
+ Writes to `basic.png`.
+ """
+ LOGGER.info("Rendering on GPU...")
+ torch.manual_seed(1)
+ n_points = 10
+ width = 1_000
+ height = 1_000
+ device = torch.device("cuda")
+ # The PyTorch3D system is right handed; in pulsar you can choose the handedness.
+ # For easy reproducibility we use a right handed coordinate system here.
+ renderer = Renderer(width, height, n_points, right_handed_system=True).to(device)
+ # Generate sample data.
+ vert_pos = torch.rand(n_points, 3, dtype=torch.float32, device=device) * 10.0
+ vert_pos[:, 2] += 25.0
+ vert_pos[:, :2] -= 5.0
+ vert_col = torch.rand(n_points, 3, dtype=torch.float32, device=device)
+ vert_rad = torch.rand(n_points, dtype=torch.float32, device=device)
+ cam_params = torch.tensor(
+ [
+ 0.0,
+ 0.0,
+ 0.0, # Position 0, 0, 0 (x, y, z).
+ 0.0,
+ math.pi, # Because of the right handed system, the camera must look 'back'.
+ 0.0, # Rotation 0, 0, 0 (in axis-angle format).
+ 5.0, # Focal length in world size.
+ 2.0, # Sensor size in world size.
+ ],
+ dtype=torch.float32,
+ device=device,
+ )
+ # Render.
+ image = renderer(
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_params,
+ 1.0e-1, # Renderer blending parameter gamma, in [1., 1e-5].
+ 45.0, # Maximum depth.
+ )
+ LOGGER.info("Writing image to `%s`.", path.abspath("basic.png"))
+ imageio.imsave("basic.png", (image.cpu().detach() * 255.0).to(torch.uint8).numpy())
+ LOGGER.info("Done.")
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ cli()
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic_unified.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic_unified.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae93f49d928adb46eda2857f3cf919a4f364882e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_basic_unified.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This example demonstrates the most trivial use of the pulsar PyTorch3D
+interface for sphere renderering. It renders and saves an image with
+10 random spheres.
+Output: basic-pt3d.png.
+"""
+import logging
+from os import path
+
+import imageio
+import torch
+from pytorch3d.renderer import (
+ PerspectiveCameras,
+ PointsRasterizationSettings,
+ PointsRasterizer,
+ PulsarPointsRenderer,
+)
+from pytorch3d.structures import Pointclouds
+
+
+LOGGER = logging.getLogger(__name__)
+
+
+def cli():
+ """
+ Basic example for the pulsar sphere renderer using the PyTorch3D interface.
+
+ Writes to `basic-pt3d.png`.
+ """
+ LOGGER.info("Rendering on GPU...")
+ torch.manual_seed(1)
+ n_points = 10
+ width = 1_000
+ height = 1_000
+ device = torch.device("cuda")
+ # Generate sample data.
+ vert_pos = torch.rand(n_points, 3, dtype=torch.float32, device=device) * 10.0
+ vert_pos[:, 2] += 25.0
+ vert_pos[:, :2] -= 5.0
+ vert_col = torch.rand(n_points, 3, dtype=torch.float32, device=device)
+ pcl = Pointclouds(points=vert_pos[None, ...], features=vert_col[None, ...])
+ # Alternatively, you can also use the look_at_view_transform to get R and T:
+ # R, T = look_at_view_transform(
+ # dist=30.0, elev=0.0, azim=180.0, at=((0.0, 0.0, 30.0),), up=((0, 1, 0),),
+ # )
+ cameras = PerspectiveCameras(
+ # The focal length must be double the size for PyTorch3D because of the NDC
+ # coordinates spanning a range of two - and they must be normalized by the
+ # sensor width (see the pulsar example). This means we need here
+ # 5.0 * 2.0 / 2.0 to get the equivalent results as in pulsar.
+ focal_length=(5.0 * 2.0 / 2.0,),
+ R=torch.eye(3, dtype=torch.float32, device=device)[None, ...],
+ T=torch.zeros((1, 3), dtype=torch.float32, device=device),
+ image_size=((height, width),),
+ device=device,
+ )
+ vert_rad = torch.rand(n_points, dtype=torch.float32, device=device)
+ raster_settings = PointsRasterizationSettings(
+ image_size=(height, width),
+ radius=vert_rad,
+ )
+ rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)
+ renderer = PulsarPointsRenderer(rasterizer=rasterizer).to(device)
+ # Render.
+ image = renderer(
+ pcl,
+ gamma=(1.0e-1,), # Renderer blending parameter gamma, in [1., 1e-5].
+ znear=(1.0,),
+ zfar=(45.0,),
+ radius_world=True,
+ bg_col=torch.ones((3,), dtype=torch.float32, device=device),
+ )[0]
+ LOGGER.info("Writing image to `%s`.", path.abspath("basic-pt3d.png"))
+ imageio.imsave(
+ "basic-pt3d.png", (image.cpu().detach() * 255.0).to(torch.uint8).numpy()
+ )
+ LOGGER.info("Done.")
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ cli()
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_cam_unified.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_cam_unified.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ef3a8df408a8750acc4fc415174f1456d25836b
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/examples/pulsar_cam_unified.py
@@ -0,0 +1,230 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This example demonstrates camera parameter optimization with the pulsar
+PyTorch3D interface. For this, a reference image has been pre-generated
+(you can find it at `../../tests/pulsar/reference/examples_TestRenderer_test_cam.png`).
+The same scene parameterization is loaded and the camera parameters
+distorted. Gradient-based optimization is used to converge towards the
+original camera parameters.
+Output: cam-pt3d.gif
+"""
+import logging
+from os import path
+
+import cv2
+import imageio
+import numpy as np
+import torch
+from pytorch3d.renderer.cameras import PerspectiveCameras
+from pytorch3d.renderer.points import (
+ PointsRasterizationSettings,
+ PointsRasterizer,
+ PulsarPointsRenderer,
+)
+from pytorch3d.structures.pointclouds import Pointclouds
+from pytorch3d.transforms import axis_angle_to_matrix
+from torch import nn, optim
+
+
+LOGGER = logging.getLogger(__name__)
+N_POINTS = 20
+WIDTH = 1_000
+HEIGHT = 1_000
+DEVICE = torch.device("cuda")
+
+
+class SceneModel(nn.Module):
+ """
+ A simple scene model to demonstrate use of pulsar in PyTorch modules.
+
+ The scene model is parameterized with sphere locations (vert_pos),
+ channel content (vert_col), radiuses (vert_rad), camera position (cam_pos),
+ camera rotation (cam_rot) and sensor focal length and width (cam_sensor).
+
+ The forward method of the model renders this scene description. Any
+ of these parameters could instead be passed as inputs to the forward
+ method and come from a different model.
+ """
+
+ def __init__(self):
+ super(SceneModel, self).__init__()
+ self.gamma = 0.1
+ # Points.
+ torch.manual_seed(1)
+ vert_pos = torch.rand(N_POINTS, 3, dtype=torch.float32) * 10.0
+ vert_pos[:, 2] += 25.0
+ vert_pos[:, :2] -= 5.0
+ self.register_parameter("vert_pos", nn.Parameter(vert_pos, requires_grad=False))
+ self.register_parameter(
+ "vert_col",
+ nn.Parameter(
+ torch.rand(N_POINTS, 3, dtype=torch.float32),
+ requires_grad=False,
+ ),
+ )
+ self.register_parameter(
+ "vert_rad",
+ nn.Parameter(
+ torch.rand(N_POINTS, dtype=torch.float32),
+ requires_grad=False,
+ ),
+ )
+ self.register_parameter(
+ "cam_pos",
+ nn.Parameter(
+ torch.tensor([0.1, 0.1, 0.0], dtype=torch.float32),
+ requires_grad=True,
+ ),
+ )
+ self.register_parameter(
+ "cam_rot",
+ # We're using the 6D rot. representation for better gradients.
+ nn.Parameter(
+ axis_angle_to_matrix(
+ torch.tensor(
+ [
+ [0.02, 0.02, 0.01],
+ ],
+ dtype=torch.float32,
+ )
+ )[0],
+ requires_grad=True,
+ ),
+ )
+ self.register_parameter(
+ "focal_length",
+ nn.Parameter(
+ torch.tensor(
+ [
+ 4.8 * 2.0 / 2.0,
+ ],
+ dtype=torch.float32,
+ ),
+ requires_grad=True,
+ ),
+ )
+ self.cameras = PerspectiveCameras(
+ # The focal length must be double the size for PyTorch3D because of the NDC
+ # coordinates spanning a range of two - and they must be normalized by the
+ # sensor width (see the pulsar example). This means we need here
+ # 5.0 * 2.0 / 2.0 to get the equivalent results as in pulsar.
+ #
+ # R, T and f are provided here, but will be provided again
+ # at every call to the forward method. The reason are problems
+ # with PyTorch which makes device placement for gradients problematic
+ # for tensors which are themselves on a 'gradient path' but not
+ # leafs in the calculation tree. This will be addressed by an architectural
+ # change in PyTorch3D in the future. Until then, this workaround is
+ # recommended.
+ focal_length=self.focal_length,
+ R=self.cam_rot[None, ...],
+ T=self.cam_pos[None, ...],
+ image_size=((HEIGHT, WIDTH),),
+ device=DEVICE,
+ )
+ raster_settings = PointsRasterizationSettings(
+ image_size=(HEIGHT, WIDTH),
+ radius=self.vert_rad,
+ )
+ rasterizer = PointsRasterizer(
+ cameras=self.cameras, raster_settings=raster_settings
+ )
+ self.renderer = PulsarPointsRenderer(rasterizer=rasterizer)
+
+ def forward(self):
+ # The Pointclouds object creates copies of it's arguments - that's why
+ # we have to create a new object in every forward step.
+ pcl = Pointclouds(
+ points=self.vert_pos[None, ...], features=self.vert_col[None, ...]
+ )
+ return self.renderer(
+ pcl,
+ gamma=(self.gamma,),
+ zfar=(45.0,),
+ znear=(1.0,),
+ radius_world=True,
+ bg_col=torch.ones((3,), dtype=torch.float32, device=DEVICE),
+ # As mentioned above: workaround for device placement of gradients for
+ # camera parameters.
+ focal_length=self.focal_length,
+ R=self.cam_rot[None, ...],
+ T=self.cam_pos[None, ...],
+ )[0]
+
+
+def cli():
+ """
+ Camera optimization example using pulsar.
+
+ Writes to `cam.gif`.
+ """
+ LOGGER.info("Loading reference...")
+ # Load reference.
+ ref = (
+ torch.from_numpy(
+ imageio.imread(
+ "../../tests/pulsar/reference/examples_TestRenderer_test_cam.png"
+ )[:, ::-1, :].copy()
+ ).to(torch.float32)
+ / 255.0
+ ).to(DEVICE)
+ # Set up model.
+ model = SceneModel().to(DEVICE)
+ # Optimizer.
+ optimizer = optim.SGD(
+ [
+ {"params": [model.cam_pos], "lr": 1e-4},
+ {"params": [model.cam_rot], "lr": 5e-6},
+ # Using a higher lr for the focal length here, because
+ # the sensor width can not be optimized directly.
+ {"params": [model.focal_length], "lr": 1e-3},
+ ]
+ )
+
+ LOGGER.info("Writing video to `%s`.", path.abspath("cam-pt3d.gif"))
+ writer = imageio.get_writer("cam-pt3d.gif", format="gif", fps=25)
+
+ # Optimize.
+ for i in range(300):
+ optimizer.zero_grad()
+ result = model()
+ # Visualize.
+ result_im = (result.cpu().detach().numpy() * 255).astype(np.uint8)
+ cv2.imshow("opt", result_im[:, :, ::-1])
+ writer.append_data(result_im)
+ overlay_img = np.ascontiguousarray(
+ ((result * 0.5 + ref * 0.5).cpu().detach().numpy() * 255).astype(np.uint8)[
+ :, :, ::-1
+ ]
+ )
+ overlay_img = cv2.putText(
+ overlay_img,
+ "Step %d" % (i),
+ (10, 40),
+ cv2.FONT_HERSHEY_SIMPLEX,
+ 1,
+ (0, 0, 0),
+ 2,
+ cv2.LINE_AA,
+ False,
+ )
+ cv2.imshow("overlay", overlay_img)
+ cv2.waitKey(1)
+ # Update.
+ loss = ((result - ref) ** 2).sum()
+ LOGGER.info("loss %d: %f", i, loss.item())
+ loss.backward()
+ optimizer.step()
+ writer.close()
+ LOGGER.info("Done.")
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ cli()
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/datasets.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/datasets.rst
new file mode 100644
index 0000000000000000000000000000000000000000..296a560d7aa9ec3a13c8da763977c96650610e62
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/datasets.rst
@@ -0,0 +1,9 @@
+pytorch3d.datasets
+===========================
+
+Dataset loaders for datasets including ShapeNetCore.
+
+.. automodule:: pytorch3d.datasets
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/loss.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/loss.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3ae9fdcbdbaed5f9935893953b1bc930fe69d1aa
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/loss.rst
@@ -0,0 +1,9 @@
+pytorch3d.loss
+====================
+
+Loss functions for meshes and point clouds.
+
+.. automodule:: pytorch3d.loss
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/ops.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/ops.rst
new file mode 100644
index 0000000000000000000000000000000000000000..148b6b3ddd951e88d9cc1c7d8ae6a4459787101c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/ops.rst
@@ -0,0 +1,6 @@
+pytorch3d.ops
+===========================
+
+.. automodule:: pytorch3d.ops
+ :members:
+ :undoc-members:
\ No newline at end of file
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_utils.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2cd3c5ac5f502b4e5576a09dbb820dc6638ed044
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_utils.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.camera_utils
+===============================
+
+camera_utils
+
+.. automodule:: pytorch3d.renderer.camera_utils
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/fisheyecameras.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/fisheyecameras.rst
new file mode 100644
index 0000000000000000000000000000000000000000..039b1646773a7f113a65efcc7ed22399d5c4297b
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/fisheyecameras.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.fisheyecameras
+=================================
+
+fisheyecameras
+
+.. automodule:: pytorch3d.renderer.fisheyecameras
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..e62048b623b1cd760680b2c4f94e7f3ddba30ce9
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/index.rst
@@ -0,0 +1,11 @@
+pytorch3d.renderer.implicit
+===========================
+
+.. toctree::
+
+ harmonic_embedding
+ raymarching
+ raysampling
+ renderer
+ sample_pdf
+ utils
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/raysampling.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/raysampling.rst
new file mode 100644
index 0000000000000000000000000000000000000000..23f9e409d2332740ab958ae16f81881400341c91
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/raysampling.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.implicit.raysampling
+=======================================
+
+raysampling
+
+.. automodule:: pytorch3d.renderer.implicit.raysampling
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/renderer.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/renderer.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2e27e86f26173b5252bea8bec21d640a5b4c2585
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/renderer.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.implicit.renderer
+====================================
+
+renderer
+
+.. automodule:: pytorch3d.renderer.implicit.renderer
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/sample_pdf.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/sample_pdf.rst
new file mode 100644
index 0000000000000000000000000000000000000000..5c35f789f9286b4d9e434763f77953fc282fc495
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/sample_pdf.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.implicit.sample_pdf
+======================================
+
+sample_pdf
+
+.. automodule:: pytorch3d.renderer.implicit.sample_pdf
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/utils.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1d7f976f41613a24ad7ee5e1a92d30ecf7b66011
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/implicit/utils.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.implicit.utils
+=================================
+
+utils
+
+.. automodule:: pytorch3d.renderer.implicit.utils
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..5bc1f306401d3377a99c3a6c06c53828f6753da2
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/index.rst
@@ -0,0 +1,7 @@
+pytorch3d.renderer.opengl
+=========================
+
+.. toctree::
+
+ opengl_utils
+ rasterizer_opengl
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/opengl_utils.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/opengl_utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..64a8660912f1215b0ad545b65278f02a266bd7b5
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/opengl_utils.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.opengl.opengl_utils
+======================================
+
+opengl_utils
+
+.. automodule:: pytorch3d.renderer.opengl.opengl_utils
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/rasterizer_opengl.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/rasterizer_opengl.rst
new file mode 100644
index 0000000000000000000000000000000000000000..28cf96462f6cc23fb869d8f30ed09a4f9e684018
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/opengl/rasterizer_opengl.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.opengl.rasterizer_opengl
+===========================================
+
+rasterizer_opengl
+
+.. automodule:: pytorch3d.renderer.opengl.rasterizer_opengl
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..064c518ff317227eca4fd54f16752dc143246422
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/index.rst
@@ -0,0 +1,7 @@
+pytorch3d.renderer.points.pulsar
+================================
+
+.. toctree::
+
+ renderer
+ unified
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/renderer.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/renderer.rst
new file mode 100644
index 0000000000000000000000000000000000000000..219566128185aac8ca8bd51786703671878223ce
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/renderer.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.points.pulsar.renderer
+=========================================
+
+renderer
+
+.. automodule:: pytorch3d.renderer.points.pulsar.renderer
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/unified.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/unified.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f5cc49387f95bfe289d21dd702c50ead5b2404f0
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/pulsar/unified.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.points.pulsar.unified
+========================================
+
+unified
+
+.. automodule:: pytorch3d.renderer.points.pulsar.unified
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/splatter_blend.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/splatter_blend.rst
new file mode 100644
index 0000000000000000000000000000000000000000..d092dc2b712efcf0b5f1ef8712618b40c971e68e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/splatter_blend.rst
@@ -0,0 +1,9 @@
+pytorch3d.renderer.splatter_blend
+=================================
+
+splatter_blend
+
+.. automodule:: pytorch3d.renderer.splatter_blend
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/structures.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/structures.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1f73a5595ef5dc32d67a6902a2daeae9ebfc7dce
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/structures.rst
@@ -0,0 +1,8 @@
+pytorch3d.structures
+====================
+
+.. automodule:: pytorch3d.structures
+ :members:
+ :undoc-members:
+
+
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/transforms.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/transforms.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3962f7f19690054d9eb0488e310973cd252ca9ef
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/transforms.rst
@@ -0,0 +1,7 @@
+pytorch3d.transforms
+===========================
+
+.. automodule:: pytorch3d.transforms
+ :members:
+ :undoc-members:
+ :show-inheritance:
\ No newline at end of file
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/utils.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3aaf1df154cc9b5b0eb3d3d0daae0661b7f26433
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/utils.rst
@@ -0,0 +1,7 @@
+pytorch3d.utils
+====================
+
+.. automodule:: pytorch3d.utils
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/index.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..79e1bda1723efd81431c53ccbc7aa904e9847166
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/index.rst
@@ -0,0 +1,7 @@
+pytorch3d.vis
+=============
+
+.. toctree::
+
+ plotly_vis
+ texture_vis
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/plotly_vis.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/plotly_vis.rst
new file mode 100644
index 0000000000000000000000000000000000000000..2380a7b1879d9b0619743e1dc4d9e6ccff0d2ded
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/plotly_vis.rst
@@ -0,0 +1,9 @@
+pytorch3d.vis.plotly_vis
+========================
+
+plotly_vis
+
+.. automodule:: pytorch3d.vis.plotly_vis
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/texture_vis.rst b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/texture_vis.rst
new file mode 100644
index 0000000000000000000000000000000000000000..5e59744ed150be134884467ff05b18297b5781bb
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/vis/texture_vis.rst
@@ -0,0 +1,9 @@
+pytorch3d.vis.texture_vis
+=========================
+
+texture_vis
+
+.. automodule:: pytorch3d.vis.texture_vis
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/batching.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/batching.md
new file mode 100644
index 0000000000000000000000000000000000000000..9aa9943e4408d952a466f653b4342c46161f01b7
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/batching.md
@@ -0,0 +1,32 @@
+---
+hide_title: true
+sidebar_label: Batching
+---
+
+# Batching
+
+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.
+
+
+
+## Batch modes for meshes
+
+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
+
+* 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]`.
+* 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.
+* 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.
+
+
+
+## Use cases for batch modes
+
+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.
+
+
+
+
+[meshes]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/structures/meshes.py
+[graphconv]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/graph_conv.py
+[vert_align]: https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/vert_align.py
+[meshrcnn]: https://github.com/facebookresearch/meshrcnn
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/cameras.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/cameras.md
new file mode 100644
index 0000000000000000000000000000000000000000..84e52dba03d16b54251d3fe0e68ed6daa2e62e71
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/cameras.md
@@ -0,0 +1,101 @@
+---
+hide_title: true
+sidebar_label: Cameras
+---
+
+# Cameras
+
+## Camera Coordinate Systems
+
+When working with 3D data, there are 4 coordinate systems users need to know
+* **World coordinate system**
+This is the system the object/scene lives - the world.
+* **Camera view coordinate system**
+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`).
+* **NDC coordinate system**
+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).
+The transformation from view to NDC happens after applying the camera projection matrix (`P`).
+* **Screen coordinate system**
+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
+and (W,H) is the bottom right corner of the bottom right pixel.
+
+An illustration of the 4 coordinate systems is shown below
+
+
+## Defining Cameras in PyTorch3D
+
+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.
+
+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).
+
+We provide instantiations of common camera types in PyTorch3D and how users can flexibly define the projection space below.
+
+## Interfacing with the PyTorch3D Renderer
+
+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.
+
+Examples of cameras and how they interface with the PyTorch3D renderer can be found in our tutorials.
+
+### Camera Types
+
+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:
+* `get_camera_center` that returns the optical center of the camera in world coordinates
+* `get_world_to_view_transform` which returns a 3D transform from world coordinates to the camera view coordinates `(R, T)`
+* `get_full_projection_transform` which composes the projection transform (`K`) with the world-to-view transform `(R, T)`
+* `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].
+* `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`.
+* `transform_points_ndc` which takes a set of points in world coordinates and projects them to PyTorch3D's NDC space
+* `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]
+
+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.
+
+#### FoVPerspectiveCameras, FoVOrthographicCameras
+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`.
+These cameras are by default in NDC space.
+
+#### PerspectiveCameras, OrthographicCameras
+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),))`
+
+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
+
+```
+# for perspective camera
+x = fx * X / Z + px
+y = fy * Y / Z + py
+z = 1 / Z
+
+# for orthographic camera
+x = fx * X + px
+y = fy * Y + py
+z = Z
+```
+
+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.
+
+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.
+
+Below are example of equivalent `PerspectiveCameras` instantiations in NDC and screen space, respectively.
+
+```python
+# NDC space camera
+fcl_ndc = (1.2,)
+prp_ndc = ((0.2, 0.5),)
+cameras_ndc = PerspectiveCameras(focal_length=fcl_ndc, principal_point=prp_ndc)
+
+# Screen space camera
+image_size = ((128, 256),) # (h, w)
+fcl_screen = (76.8,) # fcl_ndc * min(image_size) / 2
+prp_screen = ((115.2, 32), ) # w / 2 - px_ndc * min(image_size) / 2, h / 2 - py_ndc * min(image_size) / 2
+cameras_screen = PerspectiveCameras(focal_length=fcl_screen, principal_point=prp_screen, in_ndc=False, image_size=image_size)
+```
+
+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)`.
+The transformation of x and y coordinates between screen and NDC is exactly the same as for px and py.
+
+```
+fx_ndc = fx_screen * 2.0 / s
+fy_ndc = fy_screen * 2.0 / s
+
+px_ndc = - (px_screen - image_width / 2.0) * 2.0 / s
+py_ndc = - (py_screen - image_height / 2.0) * 2.0 / s
+```
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/datasets.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/datasets.md
new file mode 100644
index 0000000000000000000000000000000000000000..ee3588f2ae444567c9aa8787300add255e42e49d
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/datasets.md
@@ -0,0 +1,20 @@
+---
+hide_title: true
+sidebar_label: Data loaders
+---
+
+# Data loaders for common 3D Datasets
+
+### ShapetNetCore
+
+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).
+
+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.
+
+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.
+
+### R2N2
+
+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/).
+
+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.
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/io.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/io.md
new file mode 100644
index 0000000000000000000000000000000000000000..a75842716cb12e87069889255f5fcdce60b6b55a
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/io.md
@@ -0,0 +1,34 @@
+---
+hide_title: true
+sidebar_label: File IO
+---
+
+# File IO
+There is a flexible interface for loading and saving point clouds and meshes from different formats.
+
+The main usage is via the `pytorch3d.io.IO` object, and its methods
+`load_mesh`, `save_mesh`, `load_pointcloud` and `save_pointcloud`.
+
+For example, to load a mesh you might do
+```
+from pytorch3d.io import IO
+
+device=torch.device("cuda:0")
+mesh = IO().load_mesh("mymesh.obj", device=device)
+```
+
+and to save a pointcloud you might do
+```
+pcl = Pointclouds(...)
+IO().save_pointcloud(pcl, "output_pointcloud.ply")
+```
+
+For meshes, this supports OBJ, PLY and OFF files.
+
+For pointclouds, this supports PLY files.
+
+In addition, there is experimental support for loading meshes from
+[glTF 2 assets](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0)
+stored either in a GLB container file or a glTF JSON file with embedded binary data.
+This must be enabled explicitly, as described in
+`pytorch3d/io/experimental_gltf_io.py`.
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/iou3d.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/iou3d.md
new file mode 100644
index 0000000000000000000000000000000000000000..548d67811cdcc91c30ef12858a6ccda4952c3b87
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/iou3d.md
@@ -0,0 +1,93 @@
+---
+hide_title: true
+sidebar_label: IoU3D
+---
+
+# Intersection Over Union of Oriented 3D Boxes: A New Algorithm
+
+Author: Georgia Gkioxari
+
+Implementation: Georgia Gkioxari and Nikhila Ravi
+
+## Description
+
+Intersection over union (IoU) of boxes is widely used as an evaluation metric in object detection ([1][pascalvoc], [2][coco]).
+In 2D, IoU is commonly applied to axis-aligned boxes, namely boxes with edges parallel to the image axis.
+In 3D, boxes are usually not axis aligned and can be oriented in any way in the world.
+We introduce a new algorithm which computes the *exact* IoU of two *oriented 3D boxes*.
+
+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*.
+In 3D, these planar units are 3D triangular faces.
+In 2D, they are 2D edges.
+Each planar unit belongs strictly to either `box1` or `box2`.
+Our algorithm finds these units by iterating through the sides of each box.
+
+1. For each 3D triangular face `e` in `box1` we check wether `e` is *inside* `box2`.
+2. If `e` is not *inside*, then we discard it.
+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.
+4. We repeat for `box2`.
+
+Below, we show a visualization of our algorithm for the case of 2D oriented boxes.
+
+
+
+
+
+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.
+This is the sole fundamental difference between the algorithms for 2D and 3D.
+
+## Comparison With Other Algorithms
+
+Current algorithms for 3D box IoU rely on crude approximations or make box assumptions, for example they restrict the orientation of the 3D boxes.
+[Objectron][objectron] provides a nice discussion on the limitations of prior works.
+[Objectron][objectron] introduces a great algorithm for exact IoU computation of oriented 3D boxes.
+Objectron's algorithm computes the intersection points of two boxes using the [Sutherland-Hodgman algorithm][clipalgo].
+The intersection shape is formed by the convex hull from the intersection points, using the [Qhull library][qhull].
+
+Our algorithm has several advantages over Objectron's:
+
+* 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.
+* 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.
+* Our implementation supports batching, unlike Objectron which assumes single element inputs for `box1` and `box2`.
+* Our implementation is easily parallelizable and in fact we provide a custom C++/CUDA implementation which is **450 times faster than Objectron**.
+
+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`.
+
+
+
+
+
+## Usage and Code
+
+```python
+from pytorch3d.ops import box3d_overlap
+# Assume inputs: boxes1 (M, 8, 3) and boxes2 (N, 8, 3)
+intersection_vol, iou_3d = box3d_overlap(boxes1, boxes2)
+```
+
+For more details, read [iou_box3d.py](https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/ops/iou_box3d.py).
+
+Note that our implementation is not differentiable as of now. We plan to add gradient support soon.
+
+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.
+
+
+## Cite
+
+If you use our 3D IoU algorithm, please cite PyTorch3D
+
+```bibtex
+@article{ravi2020pytorch3d,
+ author = {Nikhila Ravi and Jeremy Reizenstein and David Novotny and Taylor Gordon
+ and Wan-Yen Lo and Justin Johnson and Georgia Gkioxari},
+ title = {Accelerating 3D Deep Learning with PyTorch3D},
+ journal = {arXiv:2007.08501},
+ year = {2020},
+}
+```
+
+[pascalvoc]: http://host.robots.ox.ac.uk/pascal/VOC/
+[coco]: https://cocodataset.org/
+[objectron]: https://arxiv.org/abs/2012.09988
+[qhull]: http://www.qhull.org/
+[clipalgo]: https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/meshes_io.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/meshes_io.md
new file mode 100644
index 0000000000000000000000000000000000000000..330c2abff7ed1a8a5c9489d5db9e7bb2f2433e6c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/meshes_io.md
@@ -0,0 +1,75 @@
+---
+sidebar_label: Loading from file
+hide_title: true
+---
+
+# Meshes and IO
+
+The Meshes object represents a batch of triangulated meshes, and is central to
+much of the functionality of PyTorch3D. There is no insistence that each mesh in
+the batch has the same number of vertices or faces. When available, it can store
+other data which pertains to the mesh, for example face normals, face areas
+and textures.
+
+Two common file formats for storing single meshes are ".obj" and ".ply" files,
+and PyTorch3D has functions for reading these.
+
+## OBJ
+
+Obj files have a standard way to store extra information about a mesh. Given an
+obj file, it can be read with
+
+```
+ verts, faces, aux = load_obj(filename)
+```
+
+which sets `verts` to be a (V,3)-tensor of vertices and `faces.verts_idx` to be
+an (F,3)- tensor of the vertex-indices of each of the corners of the faces.
+Faces which are not triangles will be split into triangles. `aux` is an object
+which may contain normals, uv coordinates, material colors and textures if they
+are present, and `faces` may additionally contain indices into these normals,
+textures and materials in its NamedTuple structure. A Meshes object containing a
+single mesh can be created from just the vertices and faces using
+```
+ meshes = Meshes(verts=[verts], faces=[faces.verts_idx])
+```
+
+If there is texture information in the `.obj` it can be used to initialize a
+`Textures` class which is passed into the `Meshes` constructor. Currently we
+support loading of texture maps for meshes which have one texture map for the
+entire mesh e.g.
+
+```
+verts_uvs = aux.verts_uvs[None, ...] # (1, V, 2)
+faces_uvs = faces.textures_idx[None, ...] # (1, F, 3)
+tex_maps = aux.texture_images
+
+# tex_maps is a dictionary of {material name: texture image}.
+# Take the first image:
+texture_image = list(tex_maps.values())[0]
+texture_image = texture_image[None, ...] # (1, H, W, 3)
+
+# Create a textures object
+tex = Textures(verts_uvs=verts_uvs, faces_uvs=faces_uvs, maps=texture_image)
+
+# Initialise the mesh with textures
+meshes = Meshes(verts=[verts], faces=[faces.verts_idx], textures=tex)
+```
+
+The `load_objs_as_meshes` function provides this procedure.
+
+## PLY
+
+Ply files are flexible in the way they store additional information. PyTorch3D
+provides a function just to read the vertices and faces from a ply file.
+The call
+```
+ verts, faces = load_ply(filename)
+```
+sets `verts` to be a (V,3)-tensor of vertices and `faces` to be an (F,3)-
+tensor of the vertex-indices of each of the corners of the faces. Faces which
+are not triangles will be split into triangles. A Meshes object containing a
+single mesh can be created from this data using
+```
+ meshes = Meshes(verts=[verts], faces=[faces])
+```
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/renderer.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/renderer.md
new file mode 100644
index 0000000000000000000000000000000000000000..463dd2f0702c040fdb34a051cc789b14422528a0
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/renderer.md
@@ -0,0 +1,76 @@
+---
+hide_title: true
+sidebar_label: Overview
+---
+
+# Rendering Overview
+
+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.
+
+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.
+
+We extensively researched existing codebases for differentiable rendering and found that:
+- the rendering pipeline is complex with more than 7 separate components which need to interoperate and be differentiable
+- 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
+- existing methods either do not support batching or assume that meshes in a batch have the same number of vertices and faces
+- existing projects only provide CUDA implementations so they cannot be used without GPUs
+
+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.
+
+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.
+
+## Get started
+
+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).
+
+## Tech Report
+
+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).
+
+---
+
+**NOTE: CUDA Memory usage**
+
+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:
+
+ - `pix_to_face`, LongTensor `(N, H, W, K)`
+ - `zbuf`, FloatTensor `(N, H, W, K)`
+ - `dist`, FloatTensor `(N, H, W, K)`
+ - `bary_coords`, FloatTensor `(N, H, W, K, 3)`
+
+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`.
+
+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:
+
+```
+# Assume 4 bytes per float, and 8 bytes for long
+
+memory_forward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4 + (N * H * W * K) * 8
+memory_backward_pass = ((N * H * W * K) * 2 + (N * H * W * K * 3)) * 4
+
+total_memory = memory_forward_pass + memory_backward_pass
+ = (N * H * W * K) * (5 * 4 * 2 + 8)
+ = (N * H * W * K) * 48
+```
+
+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.
+
+---
+
+### References
+
+[1] Kato et al, 'Neural 3D Mesh Renderer', CVPR 2018
+
+[2] Liu et al, 'Soft Rasterizer: A Differentiable Renderer for Image-based 3D Reasoning', ICCV 2019
+
+[3] Loper et al, 'OpenDR: An Approximate Differentiable Renderer', ECCV 2014
+
+[4] De La Gorce et al, 'Model-based 3D Hand Pose Estimation from Monocular Video', PAMI 2011
+
+[5] Li et al, 'Differentiable Monte Carlo Ray Tracing through Edge Sampling', SIGGRAPH Asia 2018
+
+[6] Yifan et al, 'Differentiable Surface Splatting for Point-based Geometry Processing', SIGGRAPH Asia 2019
+
+[7] Loubet et al, 'Reparameterizing Discontinuous Integrands for Differentiable Rendering', SIGGRAPH Asia 2019
+
+[8] Chen et al, 'Learning to Predict 3D Objects with an Interpolation-based Differentiable Renderer', NeurIPS 2019
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/why_pytorch3d.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/why_pytorch3d.md
new file mode 100644
index 0000000000000000000000000000000000000000..6d11e65987e58966ae08fd0edd5367081c391298
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/notes/why_pytorch3d.md
@@ -0,0 +1,12 @@
+---
+hide_title: true
+sidebar_label: Why PyTorch3D
+---
+
+
+# Why PyTorch3D
+
+
+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.
+
+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.
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_config_system.ipynb b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_config_system.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..b433c42d3bd7daa5c26ba4ade275139f4b8f2652
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_config_system.ipynb
@@ -0,0 +1,1247 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "customInput": null,
+ "customOutput": null,
+ "originalKey": "f0af2d90-cb21-4ab4-b4cb-0fd00dbfb77b",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "4e15bfa2-5404-40d0-98b6-eb2732c8b72b",
+ "showInput": false
+ },
+ "source": [
+ "# Implicitron's config system"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "287be985-423d-42e0-a2af-1e8c585e723c",
+ "showInput": false
+ },
+ "source": [
+ "Implicitron's components are all based on a unified hierarchical configuration system. \n",
+ "This allows configurable variables and all defaults to be defined separately for each new component.\n",
+ "All configs relevant to an experiment are then automatically composed into a single configuration file that fully specifies the experiment.\n",
+ "An especially important feature is extension points where users can insert their own sub-classes of Implicitron's base components.\n",
+ "\n",
+ "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",
+ "The Implicitron volumes tutorial contains a simple example of using the config system.\n",
+ "This tutorial provides detailed hands-on experience in using and modifying Implicitron's configurable components.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "fde300a2-99cb-4d52-9d5b-4464a2083e0b",
+ "showInput": false
+ },
+ "source": [
+ "## 0. Install and import modules\n",
+ "\n",
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "customInput": null,
+ "customOutput": null,
+ "originalKey": "ad6e94a7-e114-43d3-b038-a5210c7d34c9",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import sys\n",
+ "import torch\n",
+ "import subprocess\n",
+ "need_pytorch3d=False\n",
+ "try:\n",
+ " import pytorch3d\n",
+ "except ModuleNotFoundError:\n",
+ " need_pytorch3d=True\n",
+ "if need_pytorch3d:\n",
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
+ " version_str=\"\".join([\n",
+ " f\"py3{sys.version_info.minor}_cu\",\n",
+ " torch.version.cuda.replace(\".\",\"\"),\n",
+ " f\"_pyt{pyt_version_str}\"\n",
+ " ])\n",
+ " !pip install iopath\n",
+ " if sys.platform.startswith(\"linux\"):\n",
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
+ " pip_list = !pip freeze\n",
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
+ " if need_pytorch3d:\n",
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
+ "if need_pytorch3d:\n",
+ " print(\"Installing PyTorch3D from source\")\n",
+ " !pip install ninja\n",
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "609896c0-9e2e-4716-b074-b565f0170e32",
+ "showInput": false
+ },
+ "source": [
+ "Ensure omegaconf is installed. If not, run this cell. (It should not be necessary to restart the runtime.)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "customInput": null,
+ "customOutput": null,
+ "originalKey": "d1c1851e-b9f2-4236-93c3-19aa4d63041c",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "!pip install omegaconf"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customOutput": null,
+ "executionStartTime": 1659465468717,
+ "executionStopTime": 1659465468738,
+ "hidden_ranges": [],
+ "originalKey": "5ac7ef23-b74c-46b2-b8d3-799524d7ba4f",
+ "requestMsgId": "5ac7ef23-b74c-46b2-b8d3-799524d7ba4f"
+ },
+ "outputs": [],
+ "source": [
+ "from dataclasses import dataclass\n",
+ "from typing import Optional, Tuple\n",
+ "\n",
+ "import torch\n",
+ "from omegaconf import DictConfig, OmegaConf\n",
+ "from pytorch3d.implicitron.tools.config import (\n",
+ " Configurable,\n",
+ " ReplaceableBase,\n",
+ " expand_args_fields,\n",
+ " get_default_args,\n",
+ " registry,\n",
+ " run_auto_creation,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "a638bf90-eb6b-424d-b53d-eae11954a717",
+ "showInput": false
+ },
+ "source": [
+ "## 1. Introducing dataclasses \n",
+ "\n",
+ "[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"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659454972732,
+ "executionStopTime": 1659454972739,
+ "originalKey": "71eaad5e-e198-492e-8610-24b0da9dd4ae",
+ "requestMsgId": "71eaad5e-e198-492e-8610-24b0da9dd4ae",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "@dataclass\n",
+ "class MyDataclass:\n",
+ " a: int\n",
+ " b: int = 8\n",
+ " c: Optional[Tuple[int, ...]] = None\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " print(f\"created with a = {self.a}\")\n",
+ " self.d = 2 * self.b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659454973051,
+ "executionStopTime": 1659454973077,
+ "originalKey": "83202a18-a3d3-44ec-a62d-b3360a302645",
+ "requestMsgId": "83202a18-a3d3-44ec-a62d-b3360a302645",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "my_dataclass_instance = MyDataclass(a=18)\n",
+ "assert my_dataclass_instance.d == 16"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "b67ccb9f-dc6c-4994-9b99-b5a1bcfebd70",
+ "showInput": false
+ },
+ "source": [
+ "👷 Note that the `dataclass` decorator here is function which modifies the definition of the class itself.\n",
+ "It runs immediately after the definition.\n",
+ "Our config system requires that implicitron library code contains classes whose modified versions need to be aware of user-defined implementations.\n",
+ "Therefore we need the modification of the class to be delayed. We don't use a decorator.\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "3e90f664-99df-4387-9c45-a1ad7939ef3a",
+ "showInput": false
+ },
+ "source": [
+ "## 2. Introducing omegaconf and OmegaConf.structured\n",
+ "\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659451341683,
+ "executionStopTime": 1659451341690,
+ "originalKey": "81c73c9b-27ee-4aab-b55e-fb0dd67fe174",
+ "requestMsgId": "81c73c9b-27ee-4aab-b55e-fb0dd67fe174",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "dc = DictConfig({\"a\": 2, \"b\": True, \"c\": None, \"d\": \"hello\"})\n",
+ "assert dc.a == dc[\"a\"] == 2"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "3b5b76a9-4b76-4784-96ff-2a1212e48e48",
+ "showInput": false
+ },
+ "source": [
+ "OmegaConf has a serialization to and from yaml. The [Hydra](https://hydra.cc/) library relies on this for its configuration files."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659451411835,
+ "executionStopTime": 1659451411936,
+ "originalKey": "d7a25ec1-caea-46bc-a1da-4b1f040c4b61",
+ "requestMsgId": "d7a25ec1-caea-46bc-a1da-4b1f040c4b61",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "print(OmegaConf.to_yaml(dc))\n",
+ "assert OmegaConf.create(OmegaConf.to_yaml(dc)) == dc"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "777fecdd-8bf6-4fd8-827b-cb8af5477fa8",
+ "showInput": false
+ },
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659455098879,
+ "executionStopTime": 1659455098900,
+ "originalKey": "de36efb4-0b08-4fb8-bb3a-be1b2c0cd162",
+ "requestMsgId": "de36efb4-0b08-4fb8-bb3a-be1b2c0cd162",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "structured = OmegaConf.structured(MyDataclass)\n",
+ "assert isinstance(structured, DictConfig)\n",
+ "print(structured)\n",
+ "print()\n",
+ "print(OmegaConf.to_yaml(structured))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "be4446da-e536-4139-9ba3-37669a5b5e61",
+ "showInput": false
+ },
+ "source": [
+ "`structured` knows it is missing a value for `a`."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "864811e8-1a75-4932-a85e-f681b0541ae9",
+ "showInput": false
+ },
+ "source": [
+ "Such an object has members compatible with the dataclass, so an initialisation can be performed as follows."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659455580491,
+ "executionStopTime": 1659455580501,
+ "originalKey": "eb88aaa0-c22f-4ffb-813a-ca957b490acb",
+ "requestMsgId": "eb88aaa0-c22f-4ffb-813a-ca957b490acb",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "structured.a = 21\n",
+ "my_dataclass_instance2 = MyDataclass(**structured)\n",
+ "print(my_dataclass_instance2)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "2d08c81c-9d18-4de9-8464-0da2d89f94f3",
+ "showInput": false
+ },
+ "source": [
+ "You can also call OmegaConf.structured on an instance."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659455594700,
+ "executionStopTime": 1659455594737,
+ "originalKey": "5e469bac-32a4-475d-9c09-8b64ba3f2155",
+ "requestMsgId": "5e469bac-32a4-475d-9c09-8b64ba3f2155",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "structured_from_instance = OmegaConf.structured(my_dataclass_instance)\n",
+ "my_dataclass_instance3 = MyDataclass(**structured_from_instance)\n",
+ "print(my_dataclass_instance3)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659452594203,
+ "executionStopTime": 1659452594333,
+ "originalKey": "2ed559e3-8552-465a-938f-30c72a321184",
+ "requestMsgId": "2ed559e3-8552-465a-938f-30c72a321184",
+ "showInput": false
+ },
+ "source": [
+ "## 3. Our approach to OmegaConf.structured\n",
+ "\n",
+ "We provide functions which are equivalent to `OmegaConf.structured` but support more features. \n",
+ "To achieve the above using our functions, the following is used.\n",
+ "Note that we indicate configurable classes using a special base class `Configurable`, not a decorator."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659454053323,
+ "executionStopTime": 1659454061629,
+ "originalKey": "9888afbd-e617-4596-ab7a-fc1073f58656",
+ "requestMsgId": "9888afbd-e617-4596-ab7a-fc1073f58656",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class MyConfigurable(Configurable):\n",
+ " a: int\n",
+ " b: int = 8\n",
+ " c: Optional[Tuple[int, ...]] = None\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " print(f\"created with a = {self.a}\")\n",
+ " self.d = 2 * self.b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659454784912,
+ "executionStopTime": 1659454784928,
+ "originalKey": "e43155b4-3da5-4df1-a2f5-da1d0369eec9",
+ "requestMsgId": "e43155b4-3da5-4df1-a2f5-da1d0369eec9",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# The expand_args_fields function modifies the class like @dataclasses.dataclass.\n",
+ "# If it has not been called on a Configurable object before it has been instantiated, it will\n",
+ "# be called automatically.\n",
+ "expand_args_fields(MyConfigurable)\n",
+ "my_configurable_instance = MyConfigurable(a=18)\n",
+ "assert my_configurable_instance.d == 16"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659460669541,
+ "executionStopTime": 1659460669566,
+ "originalKey": "96eaae18-dce4-4ee1-b451-1466fea51b9f",
+ "requestMsgId": "96eaae18-dce4-4ee1-b451-1466fea51b9f",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# get_default_args also calls expand_args_fields automatically\n",
+ "our_structured = get_default_args(MyConfigurable)\n",
+ "assert isinstance(our_structured, DictConfig)\n",
+ "print(OmegaConf.to_yaml(our_structured))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659460454020,
+ "executionStopTime": 1659460454032,
+ "originalKey": "359f7925-68de-42cd-bd34-79a099b1c210",
+ "requestMsgId": "359f7925-68de-42cd-bd34-79a099b1c210",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "our_structured.a = 21\n",
+ "print(MyConfigurable(**our_structured))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659460599142,
+ "executionStopTime": 1659460599149,
+ "originalKey": "eac7d385-9365-4098-acf9-4f0a0dbdcb85",
+ "requestMsgId": "eac7d385-9365-4098-acf9-4f0a0dbdcb85",
+ "showInput": false
+ },
+ "source": [
+ "## 4. First enhancement: nested types 🪺\n",
+ "\n",
+ "Our system allows Configurable classes to contain each other. \n",
+ "One thing to remember: add a call to `run_auto_creation` in `__post_init__`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659465752418,
+ "executionStopTime": 1659465752976,
+ "originalKey": "9bd70ee5-4ec1-4021-bce5-9638b5088c0a",
+ "requestMsgId": "9bd70ee5-4ec1-4021-bce5-9638b5088c0a",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class Inner(Configurable):\n",
+ " a: int = 8\n",
+ " b: bool = True\n",
+ " c: Tuple[int, ...] = (2, 3, 4, 6)\n",
+ "\n",
+ "\n",
+ "class Outer(Configurable):\n",
+ " inner: Inner\n",
+ " x: str = \"hello\"\n",
+ " xx: bool = False\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " run_auto_creation(self)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659465762326,
+ "executionStopTime": 1659465762339,
+ "originalKey": "9f2b9f98-b54b-46cc-9b02-9e902cb279e7",
+ "requestMsgId": "9f2b9f98-b54b-46cc-9b02-9e902cb279e7",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "outer_dc = get_default_args(Outer)\n",
+ "print(OmegaConf.to_yaml(outer_dc))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659465772894,
+ "executionStopTime": 1659465772911,
+ "originalKey": "0254204b-8c7a-4d40-bba6-5132185f63d7",
+ "requestMsgId": "0254204b-8c7a-4d40-bba6-5132185f63d7",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "outer = Outer(**outer_dc)\n",
+ "assert isinstance(outer, Outer)\n",
+ "assert isinstance(outer.inner, Inner)\n",
+ "print(vars(outer))\n",
+ "print(outer.inner)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "44a78c13-ec92-4a87-808a-c4674b320c22",
+ "showInput": false
+ },
+ "source": [
+ "Note how inner_args is an extra member of outer. `run_auto_creation(self)` is equivalent to\n",
+ "```\n",
+ " self.inner = Inner(**self.inner_args)\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659461071129,
+ "executionStopTime": 1659461071137,
+ "originalKey": "af0ec78b-7888-4b0d-9346-63d970d43293",
+ "requestMsgId": "af0ec78b-7888-4b0d-9346-63d970d43293",
+ "showInput": false
+ },
+ "source": [
+ "## 5. Second enhancement: pluggable/replaceable components 🔌\n",
+ "\n",
+ "If a class uses `ReplaceableBase` as a base class instead of `Configurable`, we call it a replaceable.\n",
+ "It indicates that it is designed for child classes to use in its place.\n",
+ "We might use `NotImplementedError` to indicate functionality which subclasses are expected to implement.\n",
+ "The system maintains a global `registry` containing subclasses of each ReplaceableBase.\n",
+ "The subclasses register themselves with it with a decorator.\n",
+ "\n",
+ "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",
+ "contain a corresponding class_type field of type `str` which indicates which concrete child class to use."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463453457,
+ "executionStopTime": 1659463453467,
+ "originalKey": "f2898703-d147-4394-978e-fc7f1f559395",
+ "requestMsgId": "f2898703-d147-4394-978e-fc7f1f559395",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class InnerBase(ReplaceableBase):\n",
+ " def say_something(self):\n",
+ " raise NotImplementedError\n",
+ "\n",
+ "\n",
+ "@registry.register\n",
+ "class Inner1(InnerBase):\n",
+ " a: int = 1\n",
+ " b: str = \"h\"\n",
+ "\n",
+ " def say_something(self):\n",
+ " print(\"hello from an Inner1\")\n",
+ "\n",
+ "\n",
+ "@registry.register\n",
+ "class Inner2(InnerBase):\n",
+ " a: int = 2\n",
+ "\n",
+ " def say_something(self):\n",
+ " print(\"hello from an Inner2\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463453514,
+ "executionStopTime": 1659463453592,
+ "originalKey": "6f171599-51ee-440f-82d7-a59f84d24624",
+ "requestMsgId": "6f171599-51ee-440f-82d7-a59f84d24624",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class Out(Configurable):\n",
+ " inner: InnerBase\n",
+ " inner_class_type: str = \"Inner1\"\n",
+ " x: int = 19\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " run_auto_creation(self)\n",
+ "\n",
+ " def talk(self):\n",
+ " self.inner.say_something()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463191360,
+ "executionStopTime": 1659463191428,
+ "originalKey": "7abaecec-96e6-44df-8c8d-69c36a14b913",
+ "requestMsgId": "7abaecec-96e6-44df-8c8d-69c36a14b913",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "Out_dc = get_default_args(Out)\n",
+ "print(OmegaConf.to_yaml(Out_dc))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463192717,
+ "executionStopTime": 1659463192754,
+ "originalKey": "c82dc2ca-ba8f-4a44-aed3-43f6b52ec28c",
+ "requestMsgId": "c82dc2ca-ba8f-4a44-aed3-43f6b52ec28c",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "Out_dc.inner_class_type = \"Inner2\"\n",
+ "out = Out(**Out_dc)\n",
+ "print(out.inner)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463193751,
+ "executionStopTime": 1659463193791,
+ "originalKey": "aa0e1b04-963a-4724-81b7-5748b598b541",
+ "requestMsgId": "aa0e1b04-963a-4724-81b7-5748b598b541",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "out.talk()"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "4f78a56c-39cd-4563-a97e-041e5f360f6b",
+ "showInput": false
+ },
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462145294,
+ "executionStopTime": 1659462145307,
+ "originalKey": "ce7069d5-a813-4286-a7cd-6ff40362105a",
+ "requestMsgId": "ce7069d5-a813-4286-a7cd-6ff40362105a",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "print(vars(out))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462231114,
+ "executionStopTime": 1659462231130,
+ "originalKey": "c7f051ff-c264-4b89-80dc-36cf179aafaf",
+ "requestMsgId": "c7f051ff-c264-4b89-80dc-36cf179aafaf",
+ "showInput": false
+ },
+ "source": [
+ "## 6. Example with torch.nn.Module 🔥\n",
+ "Typically in implicitron, we use this system in combination with [`Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)s. \n",
+ "Note in this case it is necessary to call `Module.__init__` explicitly in `__post_init__`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462645018,
+ "executionStopTime": 1659462645037,
+ "originalKey": "42d210d6-09e0-4daf-8ccb-411d30f268f4",
+ "requestMsgId": "42d210d6-09e0-4daf-8ccb-411d30f268f4",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class MyLinear(torch.nn.Module, Configurable):\n",
+ " d_in: int = 2\n",
+ " d_out: int = 200\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " super().__init__()\n",
+ " self.linear = torch.nn.Linear(in_features=self.d_in, out_features=self.d_out)\n",
+ "\n",
+ " def forward(self, x):\n",
+ " return self.linear.forward(x)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462692309,
+ "executionStopTime": 1659462692346,
+ "originalKey": "546781fe-5b95-4e48-9cb5-34a634a31313",
+ "requestMsgId": "546781fe-5b95-4e48-9cb5-34a634a31313",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "my_linear = MyLinear()\n",
+ "input = torch.zeros(2)\n",
+ "output = my_linear(input)\n",
+ "print(\"output shape:\", output.shape)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462738302,
+ "executionStopTime": 1659462738419,
+ "originalKey": "b6cb71e1-1d54-4e89-a422-0a70772c5c03",
+ "requestMsgId": "b6cb71e1-1d54-4e89-a422-0a70772c5c03",
+ "showInput": false
+ },
+ "source": [
+ "`my_linear` has all the usual features of a Module.\n",
+ "E.g. it can be saved and loaded with `torch.save` and `torch.load`.\n",
+ "It has parameters:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462821485,
+ "executionStopTime": 1659462821501,
+ "originalKey": "47e8c53e-2d2c-4b41-8aa3-65aa3ea8a7d3",
+ "requestMsgId": "47e8c53e-2d2c-4b41-8aa3-65aa3ea8a7d3",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "for name, value in my_linear.named_parameters():\n",
+ " print(name, value.shape)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463222379,
+ "executionStopTime": 1659463222409,
+ "originalKey": "a01f0ea7-55f2-4af9-8e81-45dddf40f13b",
+ "requestMsgId": "a01f0ea7-55f2-4af9-8e81-45dddf40f13b",
+ "showInput": false
+ },
+ "source": [
+ "## 7. Example of implementing your own pluggable component \n",
+ "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",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463694644,
+ "executionStopTime": 1659463694653,
+ "originalKey": "d9635511-a52b-43d5-8dae-d5c1a3dd9157",
+ "requestMsgId": "d9635511-a52b-43d5-8dae-d5c1a3dd9157",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "@registry.register\n",
+ "class UserImplementedInner(InnerBase):\n",
+ " a: int = 200\n",
+ "\n",
+ " def say_something(self):\n",
+ " print(\"hello from the user\")"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "f1511aa2-56b8-4ed0-a453-17e2bbfeefe7",
+ "showInput": false
+ },
+ "source": [
+ "At this point, we need to redefine the class Out. \n",
+ "Otherwise if it has already been expanded without UserImplementedInner, then the following would not work,\n",
+ "because the implementations known to a class are fixed when it is expanded.\n",
+ "\n",
+ "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",
+ "before you *use* the library classes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463745967,
+ "executionStopTime": 1659463745986,
+ "originalKey": "c7bb5a6e-682b-4eb0-a214-e0f5990b9406",
+ "requestMsgId": "c7bb5a6e-682b-4eb0-a214-e0f5990b9406",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class Out(Configurable):\n",
+ " inner: InnerBase\n",
+ " inner_class_type: str = \"Inner1\"\n",
+ " x: int = 19\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " run_auto_creation(self)\n",
+ "\n",
+ " def talk(self):\n",
+ " self.inner.say_something()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659463747398,
+ "executionStopTime": 1659463747431,
+ "originalKey": "b6ecdc86-4b7b-47c6-9f45-a7e557c94979",
+ "requestMsgId": "b6ecdc86-4b7b-47c6-9f45-a7e557c94979",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "out2 = Out(inner_class_type=\"UserImplementedInner\")\n",
+ "print(out2.inner)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464033633,
+ "executionStopTime": 1659464033643,
+ "originalKey": "c7fe0df3-da13-40b8-9b06-6b1f37f37bb9",
+ "requestMsgId": "c7fe0df3-da13-40b8-9b06-6b1f37f37bb9",
+ "showInput": false
+ },
+ "source": [
+ "## 8: Example of making a subcomponent pluggable\n",
+ "\n",
+ "Let's look what needs to happen if we have a subcomponent which we make pluggable, to allow users to supply their own."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464709922,
+ "executionStopTime": 1659464709933,
+ "originalKey": "e37227b2-6897-4033-8560-9f2040abdeeb",
+ "requestMsgId": "e37227b2-6897-4033-8560-9f2040abdeeb",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class SubComponent(Configurable):\n",
+ " x: float = 0.25\n",
+ "\n",
+ " def apply(self, a: float) -> float:\n",
+ " return a + self.x\n",
+ "\n",
+ "\n",
+ "class LargeComponent(Configurable):\n",
+ " repeats: int = 4\n",
+ " subcomponent: SubComponent\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " run_auto_creation(self)\n",
+ "\n",
+ " def apply(self, a: float) -> float:\n",
+ " for _ in range(self.repeats):\n",
+ " a = self.subcomponent.apply(a)\n",
+ " return a"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464710339,
+ "executionStopTime": 1659464710459,
+ "originalKey": "cab4c121-350e-443f-9a49-bd542a9735a2",
+ "requestMsgId": "cab4c121-350e-443f-9a49-bd542a9735a2",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "large_component = LargeComponent()\n",
+ "assert large_component.apply(3) == 4\n",
+ "print(OmegaConf.to_yaml(LargeComponent))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "be60323a-badf-46e4-a259-72cae1391028",
+ "showInput": false
+ },
+ "source": [
+ "Made generic:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464717226,
+ "executionStopTime": 1659464717261,
+ "originalKey": "fc0d8cdb-4627-4427-b92a-17ac1c1b37b8",
+ "requestMsgId": "fc0d8cdb-4627-4427-b92a-17ac1c1b37b8",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "class SubComponentBase(ReplaceableBase):\n",
+ " def apply(self, a: float) -> float:\n",
+ " raise NotImplementedError\n",
+ "\n",
+ "\n",
+ "@registry.register\n",
+ "class SubComponent(SubComponentBase):\n",
+ " x: float = 0.25\n",
+ "\n",
+ " def apply(self, a: float) -> float:\n",
+ " return a + self.x\n",
+ "\n",
+ "\n",
+ "class LargeComponent(Configurable):\n",
+ " repeats: int = 4\n",
+ " subcomponent: SubComponentBase\n",
+ " subcomponent_class_type: str = \"SubComponent\"\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " run_auto_creation(self)\n",
+ "\n",
+ " def apply(self, a: float) -> float:\n",
+ " for _ in range(self.repeats):\n",
+ " a = self.subcomponent.apply(a)\n",
+ " return a"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464725473,
+ "executionStopTime": 1659464725587,
+ "originalKey": "bbc3d321-6b49-4356-be75-1a173b1fc3a5",
+ "requestMsgId": "bbc3d321-6b49-4356-be75-1a173b1fc3a5",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "large_component = LargeComponent()\n",
+ "assert large_component.apply(3) == 4\n",
+ "print(OmegaConf.to_yaml(LargeComponent))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659464672680,
+ "executionStopTime": 1659464673231,
+ "originalKey": "5115453a-1d96-4022-97e7-46433e6dcf60",
+ "requestMsgId": "5115453a-1d96-4022-97e7-46433e6dcf60",
+ "showInput": false
+ },
+ "source": [
+ "The following things had to change:\n",
+ "* The base class SubComponentBase was defined.\n",
+ "* SubComponent gained a `@registry.register` decoration and had its base class changed to the new one.\n",
+ "* `subcomponent_class_type` was added as a member of the outer class.\n",
+ "* In any saved configuration yaml files, the key `subcomponent_args` had to be changed to `subcomponent_SubComponent_args`."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659462041307,
+ "executionStopTime": 1659462041637,
+ "originalKey": "0739269e-5c0e-4551-b06f-f4aab386ba54",
+ "requestMsgId": "0739269e-5c0e-4551-b06f-f4aab386ba54",
+ "showInput": false
+ },
+ "source": [
+ "## Appendix: gotchas ⚠️\n",
+ "\n",
+ "* Omitting to define `__post_init__` or not calling `run_auto_creation` in it.\n",
+ "* Omitting a type annotation on a field. For example, writing \n",
+ "```\n",
+ " subcomponent_class_type = \"SubComponent\"\n",
+ "```\n",
+ "instead of \n",
+ "```\n",
+ " subcomponent_class_type: str = \"SubComponent\"\n",
+ "```\n",
+ "\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "bento_stylesheets": {
+ "bento/extensions/flow/main.css": true,
+ "bento/extensions/kernel_selector/main.css": true,
+ "bento/extensions/kernel_ui/main.css": true,
+ "bento/extensions/new_kernel/main.css": true,
+ "bento/extensions/system_usage/main.css": true,
+ "bento/extensions/theme/main.css": true
+ },
+ "captumWidgetMessage": {},
+ "dataExplorerConfig": {},
+ "kernelspec": {
+ "display_name": "pytorch3d",
+ "language": "python",
+ "metadata": {
+ "cinder_runtime": false,
+ "fbpkg_supported": true,
+ "is_prebuilt": true,
+ "kernel_name": "bento_kernel_pytorch3d",
+ "nightly_builds": true
+ },
+ "name": "bento_kernel_pytorch3d"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3"
+ },
+ "last_base_url": "https://9177.od.fbinfra.net:443/",
+ "last_kernel_id": "90755407-3729-46f4-ab67-ff2cb1daa5cb",
+ "last_msg_id": "f61034eb-826226915ad9548ffbe495ba_6317",
+ "last_server_session_id": "d6b46f14-cee7-44c1-8c51-39a38a4ea4c2",
+ "outputWidgetContext": {}
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_volumes.ipynb b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_volumes.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..7035fe9ac4f7ba8e161262130b19edc74572f344
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/implicitron_volumes.ipynb
@@ -0,0 +1,902 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659619824914,
+ "executionStopTime": 1659619825485,
+ "originalKey": "d38652e8-200a-413c-a36a-f4d349b78a9d",
+ "requestMsgId": "641de8aa-0e42-4446-9304-c160a2d226bf",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "a48a9dcf-e80f-474b-a0c4-2c9a765b15c5",
+ "showInput": false
+ },
+ "source": [
+ "# A simple model using Implicitron\n",
+ "\n",
+ "In this demo, we use the VolumeRenderer from PyTorch3D as a custom implicit function in Implicitron. We will see\n",
+ "* some of the main objects in Implicitron\n",
+ "* how to plug in a custom part of a model"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "51337c0e-ad27-4b75-ad6a-737dca5d7b95",
+ "showInput": false
+ },
+ "source": [
+ "## 0. Install and import modules\n",
+ "\n",
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659619898147,
+ "executionStopTime": 1659619898274,
+ "originalKey": "76f1ecd4-6b73-4214-81b0-118ef8d86872",
+ "requestMsgId": "deb6a860-6923-4227-abef-d31388b5142d",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import sys\n",
+ "import torch\n",
+ "import subprocess\n",
+ "need_pytorch3d=False\n",
+ "try:\n",
+ " import pytorch3d\n",
+ "except ModuleNotFoundError:\n",
+ " need_pytorch3d=True\n",
+ "if need_pytorch3d:\n",
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
+ " version_str=\"\".join([\n",
+ " f\"py3{sys.version_info.minor}_cu\",\n",
+ " torch.version.cuda.replace(\".\",\"\"),\n",
+ " f\"_pyt{pyt_version_str}\"\n",
+ " ])\n",
+ " !pip install iopath\n",
+ " if sys.platform.startswith(\"linux\"):\n",
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
+ " pip_list = !pip freeze\n",
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
+ " if need_pytorch3d:\n",
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
+ "if need_pytorch3d:\n",
+ " print(\"Installing PyTorch3D from source\")\n",
+ " !pip install ninja\n",
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "2c1020e6-eb4a-4644-9719-9147500d8e4f",
+ "showInput": false
+ },
+ "source": [
+ "Ensure omegaconf and visdom are installed. If not, run this cell. (It should not be necessary to restart the runtime.)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "customInput": null,
+ "customOutput": null,
+ "originalKey": "9e751931-a38d-44c9-9ff1-ac2f7d3a3f99",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "!pip install omegaconf visdom"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customOutput": null,
+ "executionStartTime": 1659612480556,
+ "executionStopTime": 1659612480644,
+ "hidden_ranges": [],
+ "originalKey": "86807e4a-1675-4520-a033-c7af85b233ec",
+ "requestMsgId": "880a7e20-4a90-4b37-a5eb-bccc0b23cac6"
+ },
+ "outputs": [],
+ "source": [
+ "import logging\n",
+ "from typing import Tuple\n",
+ "\n",
+ "import matplotlib.animation as animation\n",
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "import torch\n",
+ "import tqdm\n",
+ "from IPython.display import HTML\n",
+ "from omegaconf import OmegaConf\n",
+ "from PIL import Image\n",
+ "from pytorch3d.implicitron.dataset.dataset_base import FrameData\n",
+ "from pytorch3d.implicitron.dataset.rendered_mesh_dataset_map_provider import RenderedMeshDatasetMapProvider\n",
+ "from pytorch3d.implicitron.models.generic_model import GenericModel\n",
+ "from pytorch3d.implicitron.models.implicit_function.base import ImplicitFunctionBase, ImplicitronRayBundle\n",
+ "from pytorch3d.implicitron.models.renderer.base import EvaluationMode\n",
+ "from pytorch3d.implicitron.tools.config import get_default_args, registry, remove_unused_components\n",
+ "from pytorch3d.renderer.implicit.renderer import VolumeSampler\n",
+ "from pytorch3d.structures import Volumes\n",
+ "from pytorch3d.vis.plotly_vis import plot_batch_individually, plot_scene"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659610929375,
+ "executionStopTime": 1659610929383,
+ "hidden_ranges": [],
+ "originalKey": "b2d9f5bd-a9d4-4f78-b21e-92f2658e0fe9",
+ "requestMsgId": "7e43e623-4030-438b-af4e-b96170c9a052",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "output_resolution = 80"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659610930042,
+ "executionStopTime": 1659610930050,
+ "hidden_ranges": [],
+ "originalKey": "0b0c2087-4c86-4c57-b0ee-6f48a70a9c78",
+ "requestMsgId": "46883aad-f00b-4fd4-ac17-eec0b2ac272a",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "torch.set_printoptions(sci_mode=False)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "37809d0d-b02e-42df-85b6-cdd038373653",
+ "showInput": false
+ },
+ "source": [
+ "## 1. Load renders of a mesh (the cow mesh) as a dataset\n",
+ "\n",
+ "A dataset's train, val and test parts in Implicitron are represented as a `dataset_map`, and provided by an implementation of `DatasetMapProvider`. \n",
+ "`RenderedMeshDatasetMapProvider` is one which generates a single-scene dataset with only a train component by taking a mesh and rendering it.\n",
+ "We use it with the cow mesh."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659620739780,
+ "executionStopTime": 1659620739914,
+ "originalKey": "cc68cb9c-b8bf-4e9e-bef1-2cfafdf6caa2",
+ "requestMsgId": "398cfcae-5d43-4b6f-9c75-db3d297364d4",
+ "showInput": false
+ },
+ "source": [
+ "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",
+ "If running locally, the data is already available at the correct path."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "customInput": null,
+ "customOutput": null,
+ "originalKey": "2c55e002-a885-4169-8fdc-af9078b05968",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "!mkdir -p data/cow_mesh\n",
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.obj\n",
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.mtl\n",
+ "!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow_texture.png"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customOutput": null,
+ "executionStartTime": 1659621652237,
+ "executionStopTime": 1659621652903,
+ "hidden_ranges": [],
+ "originalKey": "eb77aaec-048c-40bd-bd69-0e66b6ab60b1",
+ "requestMsgId": "09b9975c-ff86-41c9-b4a9-975d23afc562",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "cow_provider = RenderedMeshDatasetMapProvider(\n",
+ " data_file=\"data/cow_mesh/cow.obj\",\n",
+ " use_point_light=False,\n",
+ " resolution=output_resolution,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659610966145,
+ "executionStopTime": 1659610966255,
+ "hidden_ranges": [],
+ "originalKey": "8210e15b-da48-4306-a49a-41c4e7e7d42f",
+ "requestMsgId": "c243edd2-a106-4fba-8471-dfa4f99a2088",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "dataset_map = cow_provider.get_dataset_map()\n",
+ "tr_cameras = [training_frame.camera for training_frame in dataset_map.train]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659610967703,
+ "executionStopTime": 1659610967848,
+ "hidden_ranges": [],
+ "originalKey": "458d72ad-d9a7-4f13-b5b7-90d2aec61c16",
+ "requestMsgId": "7f9431f3-8717-4d89-a7fe-1420dd0e00c4",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# The cameras are all in the XZ plane, in a circle about 2.7 from the origin\n",
+ "centers = torch.cat([i.get_camera_center() for i in tr_cameras])\n",
+ "print(centers.min(0).values)\n",
+ "print(centers.max(0).values)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659552920194,
+ "executionStopTime": 1659552923122,
+ "hidden_ranges": [],
+ "originalKey": "931e712b-b141-437a-97fb-dc2a07ce3458",
+ "requestMsgId": "931e712b-b141-437a-97fb-dc2a07ce3458",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# visualization of the cameras\n",
+ "plot = plot_scene({\"k\": {i: camera for i, camera in enumerate(tr_cameras)}}, camera_scale=0.25)\n",
+ "plot.layout.scene.aspectmode = \"data\"\n",
+ "plot"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "afa9c02d-f76b-4f68-83e9-9733c615406b",
+ "showInput": false
+ },
+ "source": [
+ "## 2. Custom implicit function 🧊\n",
+ "\n",
+ "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",
+ "(Often those functions can additionally take other data as well, such as view direction.)\n",
+ "A common rendering process is ray marching over densities and colors provided by an implicit function.\n",
+ "In our case, taking samples from a 3D volume grid is a very simple function of spatial coordinates. \n",
+ "\n",
+ "Here we define our own implicit function, which uses PyTorch3D's existing functionality for sampling from a volume grid.\n",
+ "We do this by subclassing `ImplicitFunctionBase`.\n",
+ "We need to register our subclass with a special decorator.\n",
+ "We use Python's dataclass annotations for configuring the module."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659613575850,
+ "executionStopTime": 1659613575940,
+ "hidden_ranges": [],
+ "originalKey": "61b55043-dc52-4de7-992e-e2195edd2123",
+ "requestMsgId": "dfaace3c-098c-4ffe-9240-6a7ae0ff271e",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "@registry.register\n",
+ "class MyVolumes(ImplicitFunctionBase, torch.nn.Module):\n",
+ " grid_resolution: int = 50 # common HWD of volumes, the number of voxels in each direction\n",
+ " extent: float = 1.0 # In world coordinates, the volume occupies is [-extent, extent] along each axis\n",
+ "\n",
+ " def __post_init__(self):\n",
+ " # We have to call this explicitly if there are other base classes like Module\n",
+ " super().__init__()\n",
+ "\n",
+ " # We define parameters like other torch.nn.Module objects.\n",
+ " # In this case, both our parameter tensors are trainable; they govern the contents of the volume grid.\n",
+ " density = torch.full((self.grid_resolution, self.grid_resolution, self.grid_resolution), -2.0)\n",
+ " self.density = torch.nn.Parameter(density)\n",
+ " color = torch.full((3, self.grid_resolution, self.grid_resolution, self.grid_resolution), 0.0)\n",
+ " self.color = torch.nn.Parameter(color)\n",
+ " self.density_activation = torch.nn.Softplus()\n",
+ "\n",
+ " def forward(\n",
+ " self,\n",
+ " ray_bundle: ImplicitronRayBundle,\n",
+ " fun_viewpool=None,\n",
+ " global_code=None,\n",
+ " ):\n",
+ " densities = self.density_activation(self.density[None, None])\n",
+ " voxel_size = 2.0 * float(self.extent) / self.grid_resolution\n",
+ " features = self.color.sigmoid()[None]\n",
+ "\n",
+ " # Like other PyTorch3D structures, the actual Volumes object should only exist as long\n",
+ " # as one iteration of training. It is local to this function.\n",
+ "\n",
+ " volume = Volumes(densities=densities, features=features, voxel_size=voxel_size)\n",
+ " sampler = VolumeSampler(volumes=volume)\n",
+ " densities, features = sampler(ray_bundle)\n",
+ "\n",
+ " # When an implicit function is used for raymarching, i.e. for MultiPassEmissionAbsorptionRenderer,\n",
+ " # it must return (densities, features, an auxiliary tuple)\n",
+ " return densities, features, {}\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "abaf2cd6-1b68-400e-a142-8fb9f49953f3",
+ "showInput": false
+ },
+ "source": [
+ "## 3. Construct the model object.\n",
+ "\n",
+ "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",
+ "There are two ways to construct it which are equivalent here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621267561,
+ "executionStopTime": 1659621267938,
+ "originalKey": "f26c3dce-fbae-4592-bd0e-e4a8abc57c2c",
+ "requestMsgId": "9213687e-1caf-46a8-a4e5-a9c531530092",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "CONSTRUCT_MODEL_FROM_CONFIG = True\n",
+ "if CONSTRUCT_MODEL_FROM_CONFIG:\n",
+ " # Via a DictConfig - this is how our training loop with hydra works\n",
+ " cfg = get_default_args(GenericModel)\n",
+ " cfg.implicit_function_class_type = \"MyVolumes\"\n",
+ " cfg.render_image_height=output_resolution\n",
+ " cfg.render_image_width=output_resolution\n",
+ " cfg.loss_weights={\"loss_rgb_huber\": 1.0}\n",
+ " cfg.tqdm_trigger_threshold=19000\n",
+ " cfg.raysampler_AdaptiveRaySampler_args.scene_extent= 4.0\n",
+ " gm = GenericModel(**cfg)\n",
+ "else:\n",
+ " # constructing GenericModel directly\n",
+ " gm = GenericModel(\n",
+ " implicit_function_class_type=\"MyVolumes\",\n",
+ " render_image_height=output_resolution,\n",
+ " render_image_width=output_resolution,\n",
+ " loss_weights={\"loss_rgb_huber\": 1.0},\n",
+ " tqdm_trigger_threshold=19000,\n",
+ " raysampler_AdaptiveRaySampler_args = {\"scene_extent\": 4.0}\n",
+ " )\n",
+ "\n",
+ " # In this case we can get the equivalent DictConfig cfg object to the way gm is configured as follows\n",
+ " cfg = OmegaConf.structured(gm)\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659611214689,
+ "executionStopTime": 1659611214748,
+ "hidden_ranges": [],
+ "originalKey": "4e659f7d-ce66-4999-83de-005eb09d7705",
+ "requestMsgId": "7b815b2b-cf19-44d0-ae89-76fde6df35ec",
+ "showInput": false
+ },
+ "source": [
+ " The default renderer is an emission-absorbtion raymarcher. We keep that default."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621268007,
+ "executionStopTime": 1659621268190,
+ "hidden_ranges": [],
+ "originalKey": "d37ae488-c57c-44d3-9def-825dc1a6495b",
+ "requestMsgId": "71143ec1-730f-4876-8a14-e46eea9d6dd1",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# We can display the configuration in use as follows.\n",
+ "remove_unused_components(cfg)\n",
+ "yaml = OmegaConf.to_yaml(cfg, sort_keys=False)\n",
+ "%page -r yaml"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621268727,
+ "executionStopTime": 1659621268776,
+ "hidden_ranges": [],
+ "originalKey": "52e53179-3c6e-4c1f-a38a-3a6d803687bb",
+ "requestMsgId": "05de9bc3-3f74-4a6f-851c-9ec919b59506",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "device = torch.device(\"cuda:0\")\n",
+ "gm.to(device)\n",
+ "assert next(gm.parameters()).is_cuda"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "customInput": null,
+ "originalKey": "528a7d53-c645-49c2-9021-09adbb18cd23",
+ "showInput": false
+ },
+ "source": [
+ "## 4. train the model "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621270236,
+ "executionStopTime": 1659621270446,
+ "hidden_ranges": [],
+ "originalKey": "953280bd-3161-42ba-8dcb-0c8ef2d5cc25",
+ "requestMsgId": "9bba424b-7bfd-4e5a-9d79-ae316e20bab0",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "train_data_collated = [FrameData.collate([frame.to(device)]) for frame in dataset_map.train]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621270815,
+ "executionStopTime": 1659621270948,
+ "hidden_ranges": [],
+ "originalKey": "2fcf07f0-0c28-49c7-8c76-1c9a9d810167",
+ "requestMsgId": "821deb43-6084-4ece-83c3-dee214562c47",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "gm.train()\n",
+ "optimizer = torch.optim.Adam(gm.parameters(), lr=0.1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customOutput": null,
+ "executionStartTime": 1659621271875,
+ "executionStopTime": 1659621298146,
+ "hidden_ranges": [],
+ "originalKey": "105099f7-ed0c-4e7f-a976-61a93fd0a8fe",
+ "requestMsgId": "0c87c108-83e3-4129-ad02-85e0140f1368",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "iterator = tqdm.tqdm(range(2000))\n",
+ "for n_batch in iterator:\n",
+ " optimizer.zero_grad()\n",
+ "\n",
+ " frame = train_data_collated[n_batch % len(dataset_map.train)]\n",
+ " out = gm(**frame, evaluation_mode=EvaluationMode.TRAINING)\n",
+ " out[\"objective\"].backward()\n",
+ " if n_batch % 100 == 0:\n",
+ " iterator.set_postfix_str(f\"loss: {float(out['objective']):.5f}\")\n",
+ " optimizer.step()"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659535024768,
+ "executionStopTime": 1659535024906,
+ "originalKey": "e3cd494a-536b-48bc-8290-c048118c82eb",
+ "requestMsgId": "e3cd494a-536b-48bc-8290-c048118c82eb",
+ "showInput": false
+ },
+ "source": [
+ "## 5. Evaluate the module\n",
+ "\n",
+ "We generate complete images from all the viewpoints to see how they look."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621299859,
+ "executionStopTime": 1659621311133,
+ "hidden_ranges": [],
+ "originalKey": "fbe1b2ea-cc24-4b20-a2d7-0249185e34a5",
+ "requestMsgId": "771ef1f8-5eee-4932-9e81-33604bf0512a",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "def to_numpy_image(image):\n",
+ " # Takes an image of shape (C, H, W) in [0,1], where C=3 or 1\n",
+ " # to a numpy uint image of shape (H, W, 3)\n",
+ " return (image * 255).to(torch.uint8).permute(1, 2, 0).detach().cpu().expand(-1, -1, 3).numpy()\n",
+ "def resize_image(image):\n",
+ " # Takes images of shape (B, C, H, W) to (B, C, output_resolution, output_resolution)\n",
+ " return torch.nn.functional.interpolate(image, size=(output_resolution, output_resolution))\n",
+ "\n",
+ "gm.eval()\n",
+ "images = []\n",
+ "expected = []\n",
+ "masks = []\n",
+ "masks_expected = []\n",
+ "for frame in tqdm.tqdm(train_data_collated):\n",
+ " with torch.no_grad():\n",
+ " out = gm(**frame, evaluation_mode=EvaluationMode.EVALUATION)\n",
+ "\n",
+ " image_rgb = to_numpy_image(out[\"images_render\"][0])\n",
+ " mask = to_numpy_image(out[\"masks_render\"][0])\n",
+ " expd = to_numpy_image(resize_image(frame.image_rgb)[0])\n",
+ " mask_expected = to_numpy_image(resize_image(frame.fg_probability)[0])\n",
+ "\n",
+ " images.append(image_rgb)\n",
+ " masks.append(mask)\n",
+ " expected.append(expd)\n",
+ " masks_expected.append(mask_expected)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659614622542,
+ "executionStopTime": 1659614622757,
+ "originalKey": "24953039-9780-40fd-bd81-5d63e9f40069",
+ "requestMsgId": "7af895a3-dfe4-4c28-ac3b-4ff0fbb40c7f",
+ "showInput": false
+ },
+ "source": [
+ "We draw a grid showing predicted image and expected image, followed by predicted mask and expected mask, from each viewpoint. \n",
+ "This is a grid of four rows of images, wrapped in to several large rows, i.e..\n",
+ "\n",
+ "```\n",
+ "┌────────┬────────┐ ┌────────┐\n",
+ "│pred │pred │ │pred │\n",
+ "│image │image │ │image │\n",
+ "│1 │2 │ │n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│expected│expected│ │expected│\n",
+ "│image │image │ ... │image │\n",
+ "│1 │2 │ │n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│pred │pred │ │pred │\n",
+ "│mask │mask │ │mask │\n",
+ "│1 │2 │ │n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│expected│expected│ │expected│\n",
+ "│mask │mask │ │mask │\n",
+ "│1 │2 │ │n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│pred │pred │ │pred │\n",
+ "│image │image │ │image │\n",
+ "│n+1 │n+1 │ │2n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│expected│expected│ │expected│\n",
+ "│image │image │ ... │image │\n",
+ "│n+1 │n+2 │ │2n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│pred │pred │ │pred │\n",
+ "│mask │mask │ │mask │\n",
+ "│n+1 │n+2 │ │2n │\n",
+ "├────────┼────────┤ ├────────┤\n",
+ "│expected│expected│ │expected│\n",
+ "│mask │mask │ │mask │\n",
+ "│n+1 │n+2 │ │2n │\n",
+ "└────────┴────────┘ └────────┘\n",
+ " ...\n",
+ "```\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621313894,
+ "executionStopTime": 1659621314042,
+ "hidden_ranges": [],
+ "originalKey": "c488a34a-e46d-4649-93fb-4b1bb5a0e439",
+ "requestMsgId": "4221e632-fca1-4fe5-b2e3-f92c37aa40e4",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "images_to_display = [images.copy(), expected.copy(), masks.copy(), masks_expected.copy()]\n",
+ "n_rows = 4\n",
+ "n_images = len(images)\n",
+ "blank_image = images[0] * 0\n",
+ "n_per_row = 1+(n_images-1)//n_rows\n",
+ "for _ in range(n_per_row*n_rows - n_images):\n",
+ " for group in images_to_display:\n",
+ " group.append(blank_image)\n",
+ "\n",
+ "images_to_display_listed = [[[i] for i in j] for j in images_to_display]\n",
+ "split = []\n",
+ "for row in range(n_rows):\n",
+ " for group in images_to_display_listed:\n",
+ " split.append(group[row*n_per_row:(row+1)*n_per_row]) \n",
+ "\n",
+ "Image.fromarray(np.block(split))\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621323795,
+ "executionStopTime": 1659621323820,
+ "hidden_ranges": [],
+ "originalKey": "49eab9e1-4fe2-4fbe-b4f3-7b6953340170",
+ "requestMsgId": "85b402ad-f903-431f-a13e-c2d697e869bb",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# Print the maximum channel intensity in the first image.\n",
+ "print(images[1].max()/255)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "code_folding": [],
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621408642,
+ "executionStopTime": 1659621409559,
+ "hidden_ranges": [],
+ "originalKey": "137d2c43-d39d-4266-ac5e-2b714da5e0ee",
+ "requestMsgId": "8e27ec57-c2d6-4ae0-be69-b63b6af929ff",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "plt.ioff()\n",
+ "fig, ax = plt.subplots(figsize=(3,3))\n",
+ "\n",
+ "ax.grid(None)\n",
+ "ims = [[ax.imshow(im, animated=True)] for im in images]\n",
+ "ani = animation.ArtistAnimation(fig, ims, interval=80, blit=True)\n",
+ "ani_html = ani.to_jshtml()\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659621409620,
+ "executionStopTime": 1659621409725,
+ "originalKey": "783e70d6-7cf1-4d76-a126-ba11ffc2f5be",
+ "requestMsgId": "b6843506-c5fa-4508-80fc-8ecae51a934a",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "HTML(ani_html)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false,
+ "customInput": null,
+ "customOutput": null,
+ "executionStartTime": 1659614670081,
+ "executionStopTime": 1659614670168,
+ "originalKey": "0286c350-2362-4f47-8181-2fc2ba51cfcf",
+ "requestMsgId": "976f4db9-d4c7-466c-bcfd-218234400226",
+ "showInput": true
+ },
+ "outputs": [],
+ "source": [
+ "# If you want to see the output of the model with the volume forced to opaque white, run this and re-evaluate\n",
+ "# with torch.no_grad():\n",
+ "# gm._implicit_functions[0]._fn.density.fill_(9.0)\n",
+ "# gm._implicit_functions[0]._fn.color.fill_(9.0)\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "bento_stylesheets": {
+ "bento/extensions/flow/main.css": true,
+ "bento/extensions/kernel_selector/main.css": true,
+ "bento/extensions/kernel_ui/main.css": true,
+ "bento/extensions/new_kernel/main.css": true,
+ "bento/extensions/system_usage/main.css": true,
+ "bento/extensions/theme/main.css": true
+ },
+ "captumWidgetMessage": {},
+ "dataExplorerConfig": {},
+ "kernelspec": {
+ "display_name": "pytorch3d",
+ "language": "python",
+ "metadata": {
+ "cinder_runtime": false,
+ "fbpkg_supported": true,
+ "is_prebuilt": true,
+ "kernel_name": "bento_kernel_pytorch3d",
+ "nightly_builds": true
+ },
+ "name": "bento_kernel_pytorch3d"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3"
+ },
+ "last_base_url": "https://9177.od.fbinfra.net:443/",
+ "last_kernel_id": "bb33cd83-7924-489a-8bd8-2d9d62eb0126",
+ "last_msg_id": "99f7088e-d22b355b859660479ef0574e_5743",
+ "last_server_session_id": "2944b203-9ea8-4c0e-9634-645dfea5f26b",
+ "outputWidgetContext": {}
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_colored_points.ipynb b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_colored_points.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..4c1812c5b8dd45ceda0e780773ceabaa6a8c0f9e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_colored_points.ipynb
@@ -0,0 +1,485 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Render a colored point cloud\n",
+ "\n",
+ "This tutorial shows how to:\n",
+ "- set up a renderer \n",
+ "- render the point cloud \n",
+ "- vary the rendering settings such as compositing and camera position"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Import modules"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import sys\n",
+ "import torch\n",
+ "import subprocess\n",
+ "need_pytorch3d=False\n",
+ "try:\n",
+ " import pytorch3d\n",
+ "except ModuleNotFoundError:\n",
+ " need_pytorch3d=True\n",
+ "if need_pytorch3d:\n",
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
+ " version_str=\"\".join([\n",
+ " f\"py3{sys.version_info.minor}_cu\",\n",
+ " torch.version.cuda.replace(\".\",\"\"),\n",
+ " f\"_pyt{pyt_version_str}\"\n",
+ " ])\n",
+ " !pip install iopath\n",
+ " if sys.platform.startswith(\"linux\"):\n",
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
+ " pip_list = !pip freeze\n",
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
+ " if need_pytorch3d:\n",
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
+ "if need_pytorch3d:\n",
+ " print(\"Installing PyTorch3D from source\")\n",
+ " !pip install ninja\n",
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import torch\n",
+ "import torch.nn.functional as F\n",
+ "import matplotlib.pyplot as plt\n",
+ "\n",
+ "# Util function for loading point clouds|\n",
+ "import numpy as np\n",
+ "\n",
+ "# Data structures and functions for rendering\n",
+ "from pytorch3d.structures import Pointclouds\n",
+ "from pytorch3d.vis.plotly_vis import AxisArgs, plot_batch_individually, plot_scene\n",
+ "from pytorch3d.renderer import (\n",
+ " look_at_view_transform,\n",
+ " FoVOrthographicCameras, \n",
+ " PointsRasterizationSettings,\n",
+ " PointsRenderer,\n",
+ " PulsarPointsRenderer,\n",
+ " PointsRasterizer,\n",
+ " AlphaCompositor,\n",
+ " NormWeightedCompositor\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Load a point cloud and corresponding colors\n",
+ "\n",
+ "Load and create a **Point Cloud** object. \n",
+ "\n",
+ "**Pointclouds** is a unique datastructure provided in PyTorch3D for working with batches of point clouds of different sizes. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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",
+ "If running locally, the data is already available at the correct path. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!mkdir -p data/PittsburghBridge\n",
+ "!wget -P data/PittsburghBridge https://dl.fbaipublicfiles.com/pytorch3d/data/PittsburghBridge/pointcloud.npz"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Setup\n",
+ "if torch.cuda.is_available():\n",
+ " device = torch.device(\"cuda:0\")\n",
+ " torch.cuda.set_device(device)\n",
+ "else:\n",
+ " device = torch.device(\"cpu\")\n",
+ "\n",
+ "# Set paths\n",
+ "DATA_DIR = \"./data\"\n",
+ "obj_filename = os.path.join(DATA_DIR, \"PittsburghBridge/pointcloud.npz\")\n",
+ "\n",
+ "# Load point cloud\n",
+ "pointcloud = np.load(obj_filename)\n",
+ "verts = torch.Tensor(pointcloud['verts']).to(device)\n",
+ " \n",
+ "rgb = torch.Tensor(pointcloud['rgb']).to(device)\n",
+ "\n",
+ "point_cloud = Pointclouds(points=[verts], features=[rgb])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Create a renderer\n",
+ "\n",
+ "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",
+ "\n",
+ "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",
+ "\n",
+ "[1] SynSin: End to end View Synthesis from a Single Image. Olivia Wiles, Georgia Gkioxari, Richard Szeliski, Justin Johnson. CVPR 2020."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize a camera.\n",
+ "R, T = look_at_view_transform(20, 10, 0)\n",
+ "cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)\n",
+ "\n",
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
+ "# and blur_radius=0.0. Refer to raster_points.py for explanations of these parameters. \n",
+ "raster_settings = PointsRasterizationSettings(\n",
+ " image_size=512, \n",
+ " radius = 0.003,\n",
+ " points_per_pixel = 10\n",
+ ")\n",
+ "\n",
+ "\n",
+ "# Create a points renderer by compositing points using an alpha compositor (nearer points\n",
+ "# are weighted more heavily). See [1] for an explanation.\n",
+ "rasterizer = PointsRasterizer(cameras=cameras, raster_settings=raster_settings)\n",
+ "renderer = PointsRenderer(\n",
+ " rasterizer=rasterizer,\n",
+ " compositor=AlphaCompositor()\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "images = renderer(point_cloud)\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We will now modify the **renderer** to use **alpha compositing** with a set background color. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "renderer = PointsRenderer(\n",
+ " rasterizer=rasterizer,\n",
+ " # Pass in background_color to the alpha compositor, setting the background color \n",
+ " # to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case blue\n",
+ " compositor=AlphaCompositor(background_color=(0, 0, 1))\n",
+ ")\n",
+ "images = renderer(point_cloud)\n",
+ "\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this example we will first create a **renderer** which uses an **orthographic camera**, and applies **weighted compositing**. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize a camera.\n",
+ "R, T = look_at_view_transform(20, 10, 0)\n",
+ "cameras = FoVOrthographicCameras(device=device, R=R, T=T, znear=0.01)\n",
+ "\n",
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
+ "# and blur_radius=0.0. Refer to rasterize_points.py for explanations of these parameters. \n",
+ "raster_settings = PointsRasterizationSettings(\n",
+ " image_size=512, \n",
+ " radius = 0.003,\n",
+ " points_per_pixel = 10\n",
+ ")\n",
+ "\n",
+ "\n",
+ "# Create a points renderer by compositing points using an weighted compositor (3D points are\n",
+ "# weighted according to their distance to a pixel and accumulated using a weighted sum)\n",
+ "renderer = PointsRenderer(\n",
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
+ " compositor=NormWeightedCompositor()\n",
+ ")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "images = renderer(point_cloud)\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We will now modify the **renderer** to use **weighted compositing** with a set background color. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "renderer = PointsRenderer(\n",
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
+ " # Pass in background_color to the norm weighted compositor, setting the background color \n",
+ " # to the 3 item tuple, representing rgb on a scale of 0 -> 1, in this case red\n",
+ " compositor=NormWeightedCompositor(background_color=(1,0,0))\n",
+ ")\n",
+ "images = renderer(point_cloud)\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Using the pulsar backend\n",
+ "\n",
+ "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",
+ "\n",
+ "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",
+ "Sphere-based Representations](https://arxiv.org/pdf/2004.07484.pdf).\n",
+ "\n",
+ "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`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "renderer = PulsarPointsRenderer(\n",
+ " rasterizer=PointsRasterizer(cameras=cameras, raster_settings=raster_settings),\n",
+ " n_channels=4\n",
+ ").to(device)\n",
+ "\n",
+ "images = renderer(point_cloud, gamma=(1e-4,),\n",
+ " bg_col=torch.tensor([0.0, 1.0, 0.0, 1.0], dtype=torch.float32, device=device))\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### View pointclouds in Plotly figures\n",
+ "\n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "plot_scene({\n",
+ " \"Pointcloud\": {\n",
+ " \"person\": point_cloud\n",
+ " }\n",
+ "})"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "point_cloud_batch = Pointclouds(points=[verts, verts + 2], features=[rgb, torch.zeros_like(rgb)])\n",
+ "# render both in the same plot in different traces\n",
+ "fig = plot_scene({\n",
+ " \"Pointcloud\": {\n",
+ " \"person\": point_cloud_batch[0],\n",
+ " \"person2\": point_cloud_batch[1]\n",
+ " }\n",
+ "})\n",
+ "fig.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# render both in the same plot in one trace\n",
+ "fig = plot_scene({\n",
+ " \"Pointcloud\": {\n",
+ " \"2 people\": point_cloud_batch\n",
+ " }\n",
+ "})\n",
+ "fig.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For batches, we can also use `plot_batch_individually` to avoid constructing the scene dictionary ourselves."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# render both in 1 row in different subplots\n",
+ "fig2 = plot_batch_individually(point_cloud_batch, ncols=2)\n",
+ "fig2.show()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# modify the plotly figure height and width\n",
+ "fig2.update_layout(height=500, width=500)\n",
+ "fig2.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can also modify the axis arguments and axis backgrounds for either function, and title our plots in `plot_batch_individually`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "fig3 = plot_batch_individually(\n",
+ " point_cloud_batch, \n",
+ " xaxis={\"backgroundcolor\":\"rgb(200, 200, 230)\"},\n",
+ " yaxis={\"backgroundcolor\":\"rgb(230, 200, 200)\"},\n",
+ " zaxis={\"backgroundcolor\":\"rgb(200, 230, 200)\"}, \n",
+ " subplot_titles=[\"Pointcloud1\", \"Pointcloud2\"], # this should have a title for each subplot, titles can be \"\"\n",
+ " axis_args=AxisArgs(showgrid=True))\n",
+ "fig3.show()"
+ ]
+ }
+ ],
+ "metadata": {
+ "bento_stylesheets": {
+ "bento/extensions/flow/main.css": true,
+ "bento/extensions/kernel_selector/main.css": true,
+ "bento/extensions/kernel_ui/main.css": true,
+ "bento/extensions/new_kernel/main.css": true,
+ "bento/extensions/system_usage/main.css": true,
+ "bento/extensions/theme/main.css": true
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.8"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_densepose.ipynb b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_densepose.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..f02ccd89e161622c4415526a39dea4dc75d0a125
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/render_densepose.ipynb
@@ -0,0 +1,441 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Render DensePose \n",
+ "\n",
+ "DensePose refers to dense human pose representation: https://github.com/facebookresearch/DensePose. \n",
+ "In this tutorial, we provide an example of using DensePose data in PyTorch3D.\n",
+ "\n",
+ "This tutorial shows how to:\n",
+ "- load a mesh and textures from densepose `.mat` and `.pkl` files\n",
+ "- set up a renderer \n",
+ "- render the mesh \n",
+ "- vary the rendering settings such as lighting and camera position"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "colab_type": "text",
+ "id": "Bnj3THhzfBLf"
+ },
+ "source": [
+ "## Import modules"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import sys\n",
+ "import torch\n",
+ "import subprocess\n",
+ "need_pytorch3d=False\n",
+ "try:\n",
+ " import pytorch3d\n",
+ "except ModuleNotFoundError:\n",
+ " need_pytorch3d=True\n",
+ "if need_pytorch3d:\n",
+ " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
+ " version_str=\"\".join([\n",
+ " f\"py3{sys.version_info.minor}_cu\",\n",
+ " torch.version.cuda.replace(\".\",\"\"),\n",
+ " f\"_pyt{pyt_version_str}\"\n",
+ " ])\n",
+ " !pip install iopath\n",
+ " if sys.platform.startswith(\"linux\"):\n",
+ " print(\"Trying to install wheel for PyTorch3D\")\n",
+ " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
+ " pip_list = !pip freeze\n",
+ " need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
+ " if need_pytorch3d:\n",
+ " print(f\"failed to find/install wheel for {version_str}\")\n",
+ "if need_pytorch3d:\n",
+ " print(\"Installing PyTorch3D from source\")\n",
+ " !pip install ninja\n",
+ " !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# We also install chumpy as it is needed to load the SMPL model pickle file.\n",
+ "!pip install chumpy"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import torch\n",
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np\n",
+ "\n",
+ "# libraries for reading data from files\n",
+ "from scipy.io import loadmat\n",
+ "from PIL import Image\n",
+ "import pickle\n",
+ "\n",
+ "# Data structures and functions for rendering\n",
+ "from pytorch3d.structures import Meshes\n",
+ "from pytorch3d.renderer import (\n",
+ " look_at_view_transform,\n",
+ " FoVPerspectiveCameras, \n",
+ " PointLights, \n",
+ " DirectionalLights, \n",
+ " Materials, \n",
+ " RasterizationSettings, \n",
+ " MeshRenderer, \n",
+ " MeshRasterizer, \n",
+ " SoftPhongShader,\n",
+ " TexturesUV\n",
+ ")\n",
+ "\n",
+ "# add path for demo utils functions \n",
+ "import sys\n",
+ "import os\n",
+ "sys.path.append(os.path.abspath(''))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Load the SMPL model\n",
+ "\n",
+ "#### Download the SMPL model\n",
+ "- Go to https://smpl.is.tue.mpg.de/download.php and sign up.\n",
+ "- Download SMPL for Python Users and unzip.\n",
+ "- Copy the file male template file **'models/basicModel_m_lbs_10_207_0_v1.0.0.pkl'** to the data/DensePose/ folder.\n",
+ " - rename the file to **'smpl_model.pkl'** or rename the string where it's commented below\n",
+ " \n",
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Texture image\n",
+ "!wget -P data/DensePose https://raw.githubusercontent.com/facebookresearch/DensePose/master/DensePoseData/demo_data/texture_from_SURREAL.png\n",
+ "\n",
+ "# UV_processed.mat\n",
+ "!wget https://dl.fbaipublicfiles.com/densepose/densepose_uv_data.tar.gz\n",
+ "!tar xvf densepose_uv_data.tar.gz -C data/DensePose\n",
+ "!rm densepose_uv_data.tar.gz"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Load our texture UV data and our SMPL data, with some processing to correct data values and format."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Setup\n",
+ "if torch.cuda.is_available():\n",
+ " device = torch.device(\"cuda:0\")\n",
+ " torch.cuda.set_device(device)\n",
+ "else:\n",
+ " device = torch.device(\"cpu\")\n",
+ " \n",
+ "# Set paths\n",
+ "DATA_DIR = \"./data\"\n",
+ "data_filename = os.path.join(DATA_DIR, \"DensePose/UV_Processed.mat\")\n",
+ "tex_filename = os.path.join(DATA_DIR,\"DensePose/texture_from_SURREAL.png\")\n",
+ "# rename your .pkl file or change this string\n",
+ "verts_filename = os.path.join(DATA_DIR, \"DensePose/smpl_model.pkl\")\n",
+ "\n",
+ "\n",
+ "# Load SMPL and texture data\n",
+ "with open(verts_filename, 'rb') as f:\n",
+ " data = pickle.load(f, encoding='latin1') \n",
+ " v_template = torch.Tensor(data['v_template']).to(device) # (6890, 3)\n",
+ "ALP_UV = loadmat(data_filename)\n",
+ "with Image.open(tex_filename) as image:\n",
+ " np_image = np.asarray(image.convert(\"RGB\")).astype(np.float32)\n",
+ "tex = torch.from_numpy(np_image / 255.)[None].to(device)\n",
+ "\n",
+ "verts = torch.from_numpy((ALP_UV[\"All_vertices\"]).astype(int)).squeeze().to(device) # (7829,)\n",
+ "U = torch.Tensor(ALP_UV['All_U_norm']).to(device) # (7829, 1)\n",
+ "V = torch.Tensor(ALP_UV['All_V_norm']).to(device) # (7829, 1)\n",
+ "faces = torch.from_numpy((ALP_UV['All_Faces'] - 1).astype(int)).to(device) # (13774, 3)\n",
+ "face_indices = torch.Tensor(ALP_UV['All_FaceIndices']).squeeze() # (13774,)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Display the texture image\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(tex.squeeze(0).cpu())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "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."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Map each face to a (u, v) offset\n",
+ "offset_per_part = {}\n",
+ "already_offset = set()\n",
+ "cols, rows = 4, 6\n",
+ "for i, u in enumerate(np.linspace(0, 1, cols, endpoint=False)):\n",
+ " for j, v in enumerate(np.linspace(0, 1, rows, endpoint=False)):\n",
+ " part = rows * i + j + 1 # parts are 1-indexed in face_indices\n",
+ " offset_per_part[part] = (u, v)\n",
+ "\n",
+ "U_norm = U.clone()\n",
+ "V_norm = V.clone()\n",
+ "\n",
+ "# iterate over faces and offset the corresponding vertex u and v values\n",
+ "for i in range(len(faces)):\n",
+ " face_vert_idxs = faces[i]\n",
+ " part = face_indices[i]\n",
+ " offset_u, offset_v = offset_per_part[int(part.item())]\n",
+ " \n",
+ " for vert_idx in face_vert_idxs: \n",
+ " # vertices are reused, but we don't want to offset multiple times\n",
+ " if vert_idx.item() not in already_offset:\n",
+ " # offset u value\n",
+ " U_norm[vert_idx] = U[vert_idx] / cols + offset_u\n",
+ " # offset v value\n",
+ " # this also flips each part locally, as each part is upside down\n",
+ " V_norm[vert_idx] = (1 - V[vert_idx]) / rows + offset_v\n",
+ " # add vertex to our set tracking offsetted vertices\n",
+ " already_offset.add(vert_idx.item())\n",
+ "\n",
+ "# invert V values\n",
+ "V_norm = 1 - V_norm"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# create our verts_uv values\n",
+ "verts_uv = torch.cat([U_norm[None],V_norm[None]], dim=2) # (1, 7829, 2)\n",
+ "\n",
+ "# There are 6890 xyz vertex coordinates but 7829 vertex uv coordinates. \n",
+ "# This is because the same vertex can be shared by multiple faces where each face may correspond to a different body part. \n",
+ "# Therefore when initializing the Meshes class,\n",
+ "# we need to map each of the vertices referenced by the DensePose faces (in verts, which is the \"All_vertices\" field)\n",
+ "# to the correct xyz coordinate in the SMPL template mesh.\n",
+ "v_template_extended = v_template[verts-1][None] # (1, 7829, 3)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Create our textured mesh \n",
+ "\n",
+ "**Meshes** is a unique datastructure provided in PyTorch3D for working with batches of meshes of different sizes.\n",
+ "\n",
+ "**TexturesUV** is an auxiliary datastructure for storing vertex uv and texture maps for meshes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "texture = TexturesUV(maps=tex, faces_uvs=faces[None], verts_uvs=verts_uv)\n",
+ "mesh = Meshes(v_template_extended, faces[None], texture)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Create a renderer"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize a camera.\n",
+ "# World coordinates +Y up, +X left and +Z in.\n",
+ "R, T = look_at_view_transform(2.7, 0, 0) \n",
+ "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
+ "\n",
+ "# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
+ "# 512x512. As we are rendering images for visualization purposes only we will set faces_per_pixel=1\n",
+ "# and blur_radius=0.0. \n",
+ "raster_settings = RasterizationSettings(\n",
+ " image_size=512, \n",
+ " blur_radius=0.0, \n",
+ " faces_per_pixel=1, \n",
+ ")\n",
+ "\n",
+ "# Place a point light in front of the person. \n",
+ "lights = PointLights(device=device, location=[[0.0, 0.0, 2.0]])\n",
+ "\n",
+ "# Create a Phong renderer by composing a rasterizer and a shader. The textured Phong shader will \n",
+ "# interpolate the texture uv coordinates for each vertex, sample from a texture image and \n",
+ "# apply the Phong lighting model\n",
+ "renderer = MeshRenderer(\n",
+ " rasterizer=MeshRasterizer(\n",
+ " cameras=cameras, \n",
+ " raster_settings=raster_settings\n",
+ " ),\n",
+ " shader=SoftPhongShader(\n",
+ " device=device, \n",
+ " cameras=cameras,\n",
+ " lights=lights\n",
+ " )\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Render the textured mesh we created from the SMPL model and texture map."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "images = renderer(mesh)\n",
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Different view and lighting of the body\n",
+ "\n",
+ "We can also change many other settings in the rendering pipeline. Here we:\n",
+ "\n",
+ "- change the **viewing angle** of the camera\n",
+ "- change the **position** of the point light"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Rotate the person by increasing the elevation and azimuth angles to view the back of the person from above. \n",
+ "R, T = look_at_view_transform(2.7, 10, 180)\n",
+ "cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
+ "\n",
+ "# Move the light location so the light is shining on the person's back. \n",
+ "lights.location = torch.tensor([[2.0, 2.0, -2.0]], device=device)\n",
+ "\n",
+ "# Re render the mesh, passing in keyword arguments for the modified components.\n",
+ "images = renderer(mesh, lights=lights, cameras=cameras)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "plt.figure(figsize=(10, 10))\n",
+ "plt.imshow(images[0, ..., :3].cpu().numpy())\n",
+ "plt.axis(\"off\");"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conclusion\n",
+ "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."
+ ]
+ }
+ ],
+ "metadata": {
+ "bento_stylesheets": {
+ "bento/extensions/flow/main.css": true,
+ "bento/extensions/kernel_selector/main.css": true,
+ "bento/extensions/kernel_ui/main.css": true,
+ "bento/extensions/new_kernel/main.css": true,
+ "bento/extensions/system_usage/main.css": true,
+ "bento/extensions/theme/main.css": true
+ },
+ "kernelspec": {
+ "display_name": "pytorch3d_etc (local)",
+ "language": "python",
+ "name": "pytorch3d_etc_local"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.7.5+"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d71a6bbae320f97bf5f4bd33ab60f37b9eba5594
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__init__.py
@@ -0,0 +1,12 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from .datatypes import Device, get_device, make_device
+
+
+__all__ = [k for k in globals().keys() if not k.startswith("_")]
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__pycache__/datatypes.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__pycache__/datatypes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d25c2e0cc6b96b2e115f71901312332b8d8b7976
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/__pycache__/datatypes.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/compat.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..e90680c85352f2f1042f0ba0159fba29dce59062
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/compat.py
@@ -0,0 +1,45 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from typing import Sequence, Tuple, Union
+
+import torch
+
+
+"""
+Some functions which depend on PyTorch or Python versions.
+"""
+
+
+def meshgrid_ij(
+ *A: Union[torch.Tensor, Sequence[torch.Tensor]]
+) -> Tuple[torch.Tensor, ...]: # pragma: no cover
+ """
+ Like torch.meshgrid was before PyTorch 1.10.0, i.e. with indexing set to ij
+ """
+ if (
+ # pyre-fixme[16]: Callable `meshgrid` has no attribute `__kwdefaults__`.
+ torch.meshgrid.__kwdefaults__ is not None
+ and "indexing" in torch.meshgrid.__kwdefaults__
+ ):
+ # PyTorch >= 1.10.0
+ # pyre-fixme[6]: For 1st param expected `Union[List[Tensor], Tensor]` but
+ # got `Union[Sequence[Tensor], Tensor]`.
+ return torch.meshgrid(*A, indexing="ij")
+ # pyre-fixme[6]: For 1st param expected `Union[List[Tensor], Tensor]` but got
+ # `Union[Sequence[Tensor], Tensor]`.
+ return torch.meshgrid(*A)
+
+
+def prod(iterable, *, start=1):
+ """
+ Like math.prod in Python 3.8 and later.
+ """
+ for i in iterable:
+ start *= i
+ return start
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/datatypes.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5aa08d9ea32465ccda996ceeaafb3dec5fbea1c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/datatypes.py
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from typing import Optional, Union
+
+import torch
+
+
+Device = Union[str, torch.device]
+
+
+def make_device(device: Device) -> torch.device:
+ """
+ Makes an actual torch.device object from the device specified as
+ either a string or torch.device object. If the device is `cuda` without
+ a specific index, the index of the current device is assigned.
+
+ Args:
+ device: Device (as str or torch.device)
+
+ Returns:
+ A matching torch.device object
+ """
+ device = torch.device(device) if isinstance(device, str) else device
+ if device.type == "cuda" and device.index is None:
+ # If cuda but with no index, then the current cuda device is indicated.
+ # In that case, we fix to that device
+ device = torch.device(f"cuda:{torch.cuda.current_device()}")
+ return device
+
+
+def get_device(x, device: Optional[Device] = None) -> torch.device:
+ """
+ Gets the device of the specified variable x if it is a tensor, or
+ falls back to a default CPU device otherwise. Allows overriding by
+ providing an explicit device.
+
+ Args:
+ x: a torch.Tensor to get the device from or another type
+ device: Device (as str or torch.device) to fall back to
+
+ Returns:
+ A matching torch.device object
+ """
+
+ # User overrides device
+ if device is not None:
+ return make_device(device)
+
+ # Set device based on input tensor
+ if torch.is_tensor(x):
+ return x.device
+
+ # Default device is cpu
+ return torch.device("cpu")
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/linear_with_repeat.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/linear_with_repeat.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b234ed10aebe9b66cfa82ad02379c8c10e424a5
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/linear_with_repeat.py
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+import math
+from typing import Tuple
+
+import torch
+import torch.nn.functional as F
+from torch.nn import init, Parameter
+
+
+class LinearWithRepeat(torch.nn.Module):
+ """
+ if x has shape (..., k, n1)
+ and y has shape (..., n2)
+ then
+ LinearWithRepeat(n1 + n2, out_features).forward((x,y))
+ is equivalent to
+ Linear(n1 + n2, out_features).forward(
+ torch.cat([x, y.unsqueeze(-2).expand(..., k, n2)], dim=-1)
+ )
+
+ Or visually:
+ Given the following, for each ray,
+
+ feature ->
+
+ ray xxxxxxxx
+ position xxxxxxxx
+ | xxxxxxxx
+ v xxxxxxxx
+
+
+ and
+ yyyyyyyy
+
+ where the y's do not depend on the position
+ but only on the ray,
+ we want to evaluate a Linear layer on both
+ types of data at every position.
+
+ It's as if we constructed
+
+ xxxxxxxxyyyyyyyy
+ xxxxxxxxyyyyyyyy
+ xxxxxxxxyyyyyyyy
+ xxxxxxxxyyyyyyyy
+
+ and sent that through the Linear.
+ """
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ bias: bool = True,
+ device=None,
+ dtype=None,
+ ) -> None:
+ """
+ Copied from torch.nn.Linear.
+ """
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.weight = Parameter(
+ torch.empty((out_features, in_features), **factory_kwargs)
+ )
+ if bias:
+ self.bias = Parameter(torch.empty(out_features, **factory_kwargs))
+ else:
+ self.register_parameter("bias", None)
+ self.reset_parameters()
+
+ def reset_parameters(self) -> None:
+ """
+ Copied from torch.nn.Linear.
+ """
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
+ if self.bias is not None:
+ fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
+ bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
+ init.uniform_(self.bias, -bound, bound)
+
+ def forward(self, input: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
+ n1 = input[0].shape[-1]
+ output1 = F.linear(input[0], self.weight[:, :n1], self.bias)
+ output2 = F.linear(input[1], self.weight[:, n1:], None)
+ return output1 + output2.unsqueeze(-2)
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92ecd0473fa51ae10d2bc6c540bac3da375a645e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__init__.py
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from .symeig3x3 import symeig3x3
+from .utils import _safe_det_3x3
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bdc71b2ba62e6a7b2370c83c718b2c0eea3edf9b
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/__init__.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc1a3d1a04de7c6174b72eb5b70011777a7e9aeb
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/symeig3x3.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..773a062c70dfb635c6571ac4e50e4970cff99646
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/__pycache__/utils.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..412f40a4b6f6114b5dc1c38eba5bb14018844712
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/common/workaround/utils.py
@@ -0,0 +1,33 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+
+import torch
+
+
+def _safe_det_3x3(t: torch.Tensor):
+ """
+ Fast determinant calculation for a batch of 3x3 matrices.
+
+ Note, result of this function might not be the same as `torch.det()`.
+ The differences might be in the last significant digit.
+
+ Args:
+ t: Tensor of shape (N, 3, 3).
+
+ Returns:
+ Tensor of shape (N) with determinants.
+ """
+
+ det = (
+ t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1])
+ - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2])
+ + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1])
+ )
+
+ return det
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.cu b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.cu
new file mode 100644
index 0000000000000000000000000000000000000000..679d8a8231b45678c6ed95a1705e6c72edef454d
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.cu
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+#include
+
+__constant__ const float kEpsilon = 1e-9;
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void alphaCompositeCudaForwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 result,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = result.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * H * W;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Iterate over each feature in each pixel
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ // alphacomposite the different values
+ float cum_alpha = 1.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ float alpha = alphas[batch][k][j][i];
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &result[batch][ch][j][i], features[ch][n_idx] * cum_alpha * alpha);
+ cum_alpha = cum_alpha * (1 - alpha);
+ }
+ }
+}
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void alphaCompositeCudaBackwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 grad_features,
+ at::PackedTensorAccessor64 grad_alphas,
+ const at::PackedTensorAccessor64 grad_outputs,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * H * W;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Parallelize over each feature in each pixel in images of size H * W,
+ // for each image in the batch of size batch_size
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ // alphacomposite the different values
+ float cum_alpha = 1.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas[batch][k][j][i];
+
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &grad_alphas[batch][k][j][i],
+ cum_alpha * features[ch][n_idx] * grad_outputs[batch][ch][j][i]);
+ atomicAdd(
+ &grad_features[ch][n_idx],
+ cum_alpha * alpha * grad_outputs[batch][ch][j][i]);
+
+ // Iterate over all (K-1) nearest points to update gradient
+ for (int t = 0; t < k; ++t) {
+ int t_idx = points_idx[batch][t][j][i];
+ // Sentinel value is -1, indicating no point overlaps this pixel
+ if (t_idx < 0) {
+ continue;
+ }
+ float alpha_tvalue = alphas[batch][t][j][i];
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &grad_alphas[batch][t][j][i],
+ -grad_outputs[batch][ch][j][i] * features[ch][n_idx] * cum_alpha *
+ alpha / (1 - alpha_tvalue + kEpsilon));
+ }
+
+ cum_alpha = cum_alpha * (1 - alphas[batch][k][j][i]);
+ }
+ }
+}
+
+at::Tensor alphaCompositeCudaForward(
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg features_t{features, "features", 1},
+ alphas_t{alphas, "alphas", 2}, points_idx_t{points_idx, "points_idx", 3};
+ at::CheckedFrom c = "alphaCompositeCudaForward";
+ at::checkAllSameGPU(c, {features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ auto result = at::zeros({batch_size, C, H, W}, features.options());
+
+ if (result.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+ }
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(batch_size, 1024 / batch_size + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ alphaCompositeCudaForwardKernel<<>>(
+ // clang-format off
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ result.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+}
+
+std::tuple alphaCompositeCudaBackward(
+ const at::Tensor& grad_outputs,
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg grad_outputs_t{grad_outputs, "grad_outputs", 1},
+ features_t{features, "features", 2}, alphas_t{alphas, "alphas", 3},
+ points_idx_t{points_idx, "points_idx", 4};
+ at::CheckedFrom c = "alphaCompositeCudaBackward";
+ at::checkAllSameGPU(c, {grad_outputs_t, features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {grad_outputs_t, features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ auto grad_features = at::zeros_like(features);
+ auto grad_alphas = at::zeros_like(alphas);
+
+ if (grad_features.numel() == 0 || grad_alphas.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+ }
+
+ const int64_t bs = alphas.size(0);
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(bs, 1024 / bs + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ alphaCompositeCudaBackwardKernel<<>>(
+ // clang-format off
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ grad_features.packed_accessor64(),
+ grad_alphas.packed_accessor64(),
+ grad_outputs.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.h
new file mode 100644
index 0000000000000000000000000000000000000000..44ba1bf0fd2e848e682db4a46c0badeefb3c02e5
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include "utils/pytorch3d_cutils.h"
+
+#include
+
+// Perform alpha compositing of points in a z-buffer.
+//
+// Inputs:
+// features: FloatTensor of shape (C, P) which gives the features
+// of each point where C is the size of the feature and
+// P the number of points.
+// alphas: FloatTensor of shape (N, points_per_pixel, H, W) where
+// points_per_pixel is the number of points in the z-buffer
+// sorted in z-order, and (H, W) is the image size.
+// points_idx: IntTensor of shape (N, points_per_pixel, H, W) giving the
+// indices of the nearest points at each pixel, sorted in z-order.
+// Returns:
+// weighted_fs: FloatTensor of shape (N, C, H, W) giving the accumulated
+// feature for each point. Concretely, it gives:
+// weighted_fs[b,c,i,j] = sum_k cum_alpha_k *
+// features[c,points_idx[b,k,i,j]]
+// where cum_alpha_k =
+// alphas[b,k,i,j] * prod_l=0..k-1 (1 - alphas[b,l,i,j])
+
+// CUDA declarations
+#ifdef WITH_CUDA
+torch::Tensor alphaCompositeCudaForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple alphaCompositeCudaBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+#endif
+
+// C++ declarations
+torch::Tensor alphaCompositeCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple alphaCompositeCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+torch::Tensor alphaCompositeForward(
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (features.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+ return alphaCompositeCudaForward(features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return alphaCompositeCpuForward(features, alphas, points_idx);
+ }
+}
+
+std::tuple alphaCompositeBackward(
+ torch::Tensor& grad_outputs,
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ grad_outputs = grad_outputs.contiguous();
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (grad_outputs.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(grad_outputs);
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+
+ return alphaCompositeCudaBackward(
+ grad_outputs, features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return alphaCompositeCpuBackward(
+ grad_outputs, features, alphas, points_idx);
+ }
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite_cpu.cpp b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..41bc0ec76794228e7f770f0436453306ffc8aec0
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/alpha_composite_cpu.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+
+#include
+#include
+
+// Epsilon float
+const float kEps = 1e-9;
+
+torch::Tensor alphaCompositeCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ torch::Tensor result = torch::zeros({B, C, H, W}, features.options());
+
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto result_a = result.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate over the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ float cum_alpha = 1.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas_a[b][k][j][i];
+ result_a[b][c][j][i] += cum_alpha * alpha * features_a[c][n_idx];
+ cum_alpha = cum_alpha * (1 - alpha);
+ }
+ }
+ }
+ }
+ }
+ return result;
+}
+
+std::tuple alphaCompositeCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ torch::Tensor grad_features = torch::zeros_like(features);
+ torch::Tensor grad_alphas = torch::zeros_like(alphas);
+
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ auto grad_outputs_a = grad_outputs.accessor();
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto grad_features_a = grad_features.accessor();
+ auto grad_alphas_a = grad_alphas.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate over the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ float cum_alpha = 1.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinal value is -1, indicating no point overlaps this pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas_a[b][k][j][i];
+ grad_alphas_a[b][k][j][i] +=
+ grad_outputs_a[b][c][j][i] * features_a[c][n_idx] * cum_alpha;
+ grad_features_a[c][n_idx] +=
+ grad_outputs_a[b][c][j][i] * cum_alpha * alpha;
+
+ // Iterate over all (K-1) nearer points to update gradient
+ for (int t = 0; t < k; t++) {
+ int64_t t_idx = points_idx_a[b][t][j][i];
+ // Sentinal value is -1, indicating no point overlaps this pixel
+ if (t_idx < 0) {
+ continue;
+ }
+ float alpha_tvalue = alphas_a[b][t][j][i];
+ grad_alphas_a[b][t][j][i] -= grad_outputs_a[b][c][j][i] *
+ features_a[c][n_idx] * cum_alpha * alpha /
+ (1 - alpha_tvalue + kEps);
+ }
+
+ cum_alpha = cum_alpha * (1 - alpha);
+ }
+ }
+ }
+ }
+ }
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.cu b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.cu
new file mode 100644
index 0000000000000000000000000000000000000000..984647172f9a15277eab70b15158a9441355490d
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.cu
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+#include
+
+__constant__ const float kEpsilon = 1e-4;
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void weightedSumNormCudaForwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 result,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = result.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * H * W;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Parallelize over each feature in each pixel in images of size H * W,
+ // for each image in the batch of size batch_size
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ // Store the accumulated alpha value
+ float cum_alpha = 0.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ cum_alpha += alphas[batch][k][j][i];
+ }
+
+ if (cum_alpha < kEpsilon) {
+ cum_alpha = kEpsilon;
+ }
+
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas[batch][k][j][i];
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &result[batch][ch][j][i], features[ch][n_idx] * alpha / cum_alpha);
+ }
+ }
+}
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void weightedSumNormCudaBackwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 grad_features,
+ at::PackedTensorAccessor64 grad_alphas,
+ const at::PackedTensorAccessor64 grad_outputs,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * W * H;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Parallelize over each feature in each pixel in images of size H * W,
+ // for each image in the batch of size batch_size
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ float sum_alpha = 0.;
+ float sum_alphafs = 0.;
+ // Iterate through the closest K points for this pixel to calculate the
+ // cumulative sum of the alphas for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ sum_alpha += alphas[batch][k][j][i];
+ sum_alphafs += alphas[batch][k][j][i] * features[ch][n_idx];
+ }
+
+ if (sum_alpha < kEpsilon) {
+ sum_alpha = kEpsilon;
+ }
+
+ // Iterate again through the closest K points for this pixel to calculate
+ // the gradient.
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas[batch][k][j][i];
+
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &grad_alphas[batch][k][j][i],
+ (features[ch][n_idx] * sum_alpha - sum_alphafs) /
+ (sum_alpha * sum_alpha) * grad_outputs[batch][ch][j][i]);
+ atomicAdd(
+ &grad_features[ch][n_idx],
+ alpha * grad_outputs[batch][ch][j][i] / sum_alpha);
+ }
+ }
+}
+
+at::Tensor weightedSumNormCudaForward(
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg features_t{features, "features", 1},
+ alphas_t{alphas, "alphas", 2}, points_idx_t{points_idx, "points_idx", 3};
+ at::CheckedFrom c = "weightedSumNormCudaForward";
+ at::checkAllSameGPU(c, {features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ auto result = at::zeros({batch_size, C, H, W}, features.options());
+
+ if (result.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+ }
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(batch_size, 1024 / batch_size + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ // clang-format off
+ weightedSumNormCudaForwardKernel<<>>(
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ result.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+}
+
+std::tuple weightedSumNormCudaBackward(
+ const at::Tensor& grad_outputs,
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg grad_outputs_t{grad_outputs, "grad_outputs", 1},
+ features_t{features, "features", 2}, alphas_t{alphas, "alphas", 3},
+ points_idx_t{points_idx, "points_idx", 4};
+ at::CheckedFrom c = "weightedSumNormCudaBackward";
+ at::checkAllSameGPU(c, {grad_outputs_t, features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {grad_outputs_t, features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ auto grad_features = at::zeros_like(features);
+ auto grad_alphas = at::zeros_like(alphas);
+
+ if (grad_features.numel() == 0 || grad_alphas.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+ }
+
+ const int64_t bs = points_idx.size(0);
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(bs, 1024 / bs + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ weightedSumNormCudaBackwardKernel<<>>(
+ // clang-format off
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ grad_features.packed_accessor64(),
+ grad_alphas.packed_accessor64(),
+ grad_outputs.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.h
new file mode 100644
index 0000000000000000000000000000000000000000..5d0a5f5be08267ad33da8b704814c6c6c333930d
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include "utils/pytorch3d_cutils.h"
+
+#include
+
+// Perform normalized weighted sum compositing of points in a z-buffer.
+//
+// Inputs:
+// features: FloatTensor of shape (C, P) which gives the features
+// of each point where C is the size of the feature and
+// P the number of points.
+// alphas: FloatTensor of shape (N, points_per_pixel, H, W) where
+// points_per_pixel is the number of points in the z-buffer
+// sorted in z-order, and (H, W) is the image size.
+// points_idx: IntTensor of shape (N, points_per_pixel, H, W) giving the
+// indices of the nearest points at each pixel, sorted in z-order.
+// Returns:
+// weighted_fs: FloatTensor of shape (N, C, H, W) giving the accumulated
+// feature in each point. Concretely, it gives:
+// weighted_fs[b,c,i,j] = sum_k alphas[b,k,i,j] *
+// features[c,points_idx[b,k,i,j]] / sum_k alphas[b,k,i,j]
+
+// CUDA declarations
+#ifdef WITH_CUDA
+torch::Tensor weightedSumNormCudaForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple weightedSumNormCudaBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+#endif
+
+// C++ declarations
+torch::Tensor weightedSumNormCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple weightedSumNormCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+torch::Tensor weightedSumNormForward(
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (features.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+
+ return weightedSumNormCudaForward(features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return weightedSumNormCpuForward(features, alphas, points_idx);
+ }
+}
+
+std::tuple weightedSumNormBackward(
+ torch::Tensor& grad_outputs,
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ grad_outputs = grad_outputs.contiguous();
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (grad_outputs.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(grad_outputs);
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+
+ return weightedSumNormCudaBackward(
+ grad_outputs, features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return weightedSumNormCpuBackward(
+ grad_outputs, features, alphas, points_idx);
+ }
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum_cpu.cpp b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..840ef3d24ae652fb42384afc755c0a889543e649
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/norm_weighted_sum_cpu.cpp
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+
+#include
+#include
+
+// Epsilon float
+const float kEps = 1e-4;
+
+torch::Tensor weightedSumNormCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ torch::Tensor result = torch::zeros({B, C, H, W}, features.options());
+
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto result_a = result.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate oer the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ float t_alpha = 0.;
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ if (n_idx < 0) {
+ continue;
+ }
+
+ t_alpha += alphas_a[b][k][j][i];
+ }
+
+ if (t_alpha < kEps) {
+ t_alpha = kEps;
+ }
+
+ // Iterate over the different zs to combine
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas_a[b][k][j][i];
+ result_a[b][c][j][i] += alpha * features_a[c][n_idx] / t_alpha;
+ }
+ }
+ }
+ }
+ }
+ return result;
+}
+
+std::tuple weightedSumNormCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ torch::Tensor grad_features = torch::zeros_like(features);
+ torch::Tensor grad_alphas = torch::zeros_like(alphas);
+
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ auto grad_outputs_a = grad_outputs.accessor();
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto grad_features_a = grad_features.accessor();
+ auto grad_alphas_a = grad_alphas.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate oer the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ float t_alpha = 0.;
+ float t_alphafs = 0.;
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinel value is -1, indicating no point overlaps this pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ t_alpha += alphas_a[b][k][j][i];
+ t_alphafs += alphas_a[b][k][j][i] * features_a[c][n_idx];
+ }
+
+ if (t_alpha < kEps) {
+ t_alpha = kEps;
+ }
+
+ // Iterate through the closest K points for this pixel ordered by z
+ // distance.
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas_a[b][k][j][i];
+ grad_alphas_a[b][k][j][i] += grad_outputs_a[b][c][j][i] *
+ (features_a[c][n_idx] * t_alpha - t_alphafs) /
+ (t_alpha * t_alpha);
+ grad_features_a[c][n_idx] +=
+ grad_outputs_a[b][c][j][i] * alpha / t_alpha;
+ }
+ }
+ }
+ }
+ }
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.cu b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.cu
new file mode 100644
index 0000000000000000000000000000000000000000..17a35bf924438408a0f039daac4c719b4496c716
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.cu
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+#include
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void weightedSumCudaForwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 result,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = result.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * H * W;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Parallelize over each feature in each pixel in images of size H * W,
+ // for each image in the batch of size batch_size
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ // Accumulate the values
+ float alpha = alphas[batch][k][j][i];
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(&result[batch][ch][j][i], features[ch][n_idx] * alpha);
+ }
+ }
+}
+
+// TODO(gkioxari) support all data types once AtomicAdd supports doubles.
+// Currently, support is for floats only.
+__global__ void weightedSumCudaBackwardKernel(
+ // clang-format off
+ at::PackedTensorAccessor64 grad_features,
+ at::PackedTensorAccessor64 grad_alphas,
+ const at::PackedTensorAccessor64 grad_outputs,
+ const at::PackedTensorAccessor64 features,
+ const at::PackedTensorAccessor64 alphas,
+ const at::PackedTensorAccessor64 points_idx) {
+ // clang-format on
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ // Get the batch and index
+ const int batch = blockIdx.x;
+
+ const int num_pixels = C * H * W;
+ const int num_threads = gridDim.y * blockDim.x;
+ const int tid = blockIdx.y * blockDim.x + threadIdx.x;
+
+ // Iterate over each pixel to compute the contribution to the
+ // gradient for the features and weights
+ for (int pid = tid; pid < num_pixels; pid += num_threads) {
+ int ch = pid / (H * W);
+ int j = (pid % (H * W)) / W;
+ int i = (pid % (H * W)) % W;
+
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < points_idx.size(1); ++k) {
+ int n_idx = points_idx[batch][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+ float alpha = alphas[batch][k][j][i];
+
+ // TODO(gkioxari) It might be more efficient to have threads write in a
+ // local variable, and move atomicAdd outside of the loop such that
+ // atomicAdd is executed once per thread.
+ atomicAdd(
+ &grad_alphas[batch][k][j][i],
+ features[ch][n_idx] * grad_outputs[batch][ch][j][i]);
+ atomicAdd(
+ &grad_features[ch][n_idx], alpha * grad_outputs[batch][ch][j][i]);
+ }
+ }
+}
+
+at::Tensor weightedSumCudaForward(
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg features_t{features, "features", 1},
+ alphas_t{alphas, "alphas", 2}, points_idx_t{points_idx, "points_idx", 3};
+ at::CheckedFrom c = "weightedSumCudaForward";
+ at::checkAllSameGPU(c, {features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ const int64_t batch_size = points_idx.size(0);
+ const int64_t C = features.size(0);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+
+ auto result = at::zeros({batch_size, C, H, W}, features.options());
+
+ if (result.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+ }
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(batch_size, 1024 / batch_size + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ weightedSumCudaForwardKernel<<>>(
+ // clang-format off
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ result.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+ AT_CUDA_CHECK(cudaGetLastError());
+ return result;
+}
+
+std::tuple weightedSumCudaBackward(
+ const at::Tensor& grad_outputs,
+ const at::Tensor& features,
+ const at::Tensor& alphas,
+ const at::Tensor& points_idx) {
+ // Check inputs are on the same device
+ at::TensorArg grad_outputs_t{grad_outputs, "grad_outputs", 1},
+ features_t{features, "features", 2}, alphas_t{alphas, "alphas", 3},
+ points_idx_t{points_idx, "points_idx", 4};
+ at::CheckedFrom c = "weightedSumCudaBackward";
+ at::checkAllSameGPU(c, {grad_outputs_t, features_t, alphas_t, points_idx_t});
+ at::checkAllSameType(c, {grad_outputs_t, features_t, alphas_t});
+
+ // Set the device for the kernel launch based on the device of the input
+ at::cuda::CUDAGuard device_guard(features.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
+
+ auto grad_features = at::zeros_like(features);
+ auto grad_alphas = at::zeros_like(alphas);
+
+ if (grad_features.numel() == 0 || grad_alphas.numel() == 0) {
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+ }
+
+ const int64_t bs = points_idx.size(0);
+
+ const dim3 threadsPerBlock(64);
+ const dim3 numBlocks(bs, 1024 / bs + 1);
+
+ // TODO(gkioxari) add AT_DISPATCH_FLOATING_TYPES once atomicAdd supports
+ // doubles. Currently, support is for floats only.
+ weightedSumCudaBackwardKernel<<>>(
+ // clang-format off
+ // As we are using packed accessors here the tensors
+ // do not need to be made contiguous.
+ grad_features.packed_accessor64(),
+ grad_alphas.packed_accessor64(),
+ grad_outputs.packed_accessor64(),
+ features.packed_accessor64(),
+ alphas.packed_accessor64(),
+ points_idx.packed_accessor64());
+ // clang-format on
+ AT_CUDA_CHECK(cudaGetLastError());
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.h
new file mode 100644
index 0000000000000000000000000000000000000000..0be6e4988419da7710b8f9c412caf0f8699cf35f
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include "utils/pytorch3d_cutils.h"
+
+#include
+
+// Perform weighted sum compositing of points in a z-buffer.
+//
+// Inputs:
+// features: FloatTensor of shape (C, P) which gives the features
+// of each point where C is the size of the feature and
+// P the number of points.
+// alphas: FloatTensor of shape (N, points_per_pixel, H, W) where
+// points_per_pixel is the number of points in the z-buffer
+// sorted in z-order, and (H, W) is the image size.
+// points_idx: IntTensor of shape (N, points_per_pixel, W, W) giving the
+// indices of the nearest points at each pixel, sorted in z-order.
+// Returns:
+// weighted_fs: FloatTensor of shape (N, C, H, W) giving the accumulated
+// feature in each point. Concretely, it gives:
+// weighted_fs[b,c,i,j] = sum_k alphas[b,k,i,j] *
+// features[c,points_idx[b,k,i,j]]
+
+// CUDA declarations
+#ifdef WITH_CUDA
+torch::Tensor weightedSumCudaForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple weightedSumCudaBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+#endif
+
+// C++ declarations
+torch::Tensor weightedSumCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+std::tuple weightedSumCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx);
+
+torch::Tensor weightedSumForward(
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (features.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+ return weightedSumCudaForward(features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return weightedSumCpuForward(features, alphas, points_idx);
+ }
+}
+
+std::tuple weightedSumBackward(
+ torch::Tensor& grad_outputs,
+ torch::Tensor& features,
+ torch::Tensor& alphas,
+ torch::Tensor& points_idx) {
+ grad_outputs = grad_outputs.contiguous();
+ features = features.contiguous();
+ alphas = alphas.contiguous();
+ points_idx = points_idx.contiguous();
+
+ if (grad_outputs.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(grad_outputs);
+ CHECK_CUDA(features);
+ CHECK_CUDA(alphas);
+ CHECK_CUDA(points_idx);
+
+ return weightedSumCudaBackward(grad_outputs, features, alphas, points_idx);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return weightedSumCpuBackward(grad_outputs, features, alphas, points_idx);
+ }
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum_cpu.cpp b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b7bddee3c9791647352b686d368dd2e6adccf27f
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/compositing/weighted_sum_cpu.cpp
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+
+#include
+#include
+
+torch::Tensor weightedSumCpuForward(
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ torch::Tensor result = torch::zeros({B, C, H, W}, features.options());
+
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto result_a = result.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate over the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinel value is -1 indicating no point overlaps the pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ float alpha = alphas_a[b][k][j][i];
+ result_a[b][c][j][i] += alpha * features_a[c][n_idx];
+ }
+ }
+ }
+ }
+ }
+ return result;
+}
+
+std::tuple weightedSumCpuBackward(
+ const torch::Tensor& grad_outputs,
+ const torch::Tensor& features,
+ const torch::Tensor& alphas,
+ const torch::Tensor& points_idx) {
+ const int64_t B = points_idx.size(0);
+ const int64_t K = points_idx.size(1);
+ const int64_t H = points_idx.size(2);
+ const int64_t W = points_idx.size(3);
+ const int64_t C = features.size(0);
+
+ torch::Tensor grad_features = torch::zeros_like(features);
+ torch::Tensor grad_alphas = torch::zeros_like(alphas);
+
+ auto grad_outputs_a = grad_outputs.accessor();
+ auto features_a = features.accessor();
+ auto alphas_a = alphas.accessor();
+ auto points_idx_a = points_idx.accessor();
+ auto grad_features_a = grad_features.accessor();
+ auto grad_alphas_a = grad_alphas.accessor();
+
+ // Iterate over the batch
+ for (int b = 0; b < B; ++b) {
+ // Iterate oer the features
+ for (int c = 0; c < C; ++c) {
+ // Iterate through the horizontal lines of the image from top to bottom
+ for (int j = 0; j < H; ++j) {
+ // Iterate over pixels in a horizontal line, left to right
+ for (int i = 0; i < W; ++i) {
+ // Iterate through the closest K points for this pixel
+ for (int k = 0; k < K; ++k) {
+ int64_t n_idx = points_idx_a[b][k][j][i];
+ // Sentinal value is -1, indicating no point overlaps this pixel
+ if (n_idx < 0) {
+ continue;
+ }
+
+ float alpha = alphas_a[b][k][j][i];
+ grad_alphas_a[b][k][j][i] +=
+ grad_outputs_a[b][c][j][i] * features_a[c][n_idx];
+ grad_features_a[c][n_idx] += grad_outputs_a[b][c][j][i] * alpha;
+ }
+ }
+ }
+ }
+ }
+ return std::make_tuple(grad_features, grad_alphas);
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/README.md b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e963ff043abdbbf88af350512f60fb70a02a4774
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/README.md
@@ -0,0 +1,16 @@
+# The `include` folder
+
+This folder contains header files with implementations of several useful
+algorithms. These implementations are usually done in files called `x.device.h`
+and use macros that route every device specific command to the right
+implementation (see `commands.h`).
+
+If you're using a device specific implementation, include `x.device.h`.
+This gives you the high-speed, device specific implementation that lets
+you work with all the details of the datastructure. All function calls are
+inlined. If you need to work with the high-level interface and be able to
+dynamically pick a device, only include `x.h`. The functions there are
+templated with a boolean `DEV` flag and are instantiated in device specific
+compilation units. You will not be able to use any other functions, but can
+use `func(params)` to work on a CUDA device, or `func(params)`
+to work on the host.
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/camera.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/camera.h
new file mode 100644
index 0000000000000000000000000000000000000000..cbb583a14e7ee4349d11fea9faf8a6f09cb5e66c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/camera.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_CAMERA_H_
+#define PULSAR_NATIVE_INCLUDE_CAMERA_H_
+
+#include
+#include "../global.h"
+
+namespace pulsar {
+/**
+ * Everything that's needed to raycast with our camera model.
+ */
+struct CamInfo {
+ float3 eye; /** Position in world coordinates. */
+ float3 pixel_0_0_center; /** LUC center of pixel position in world
+ coordinates. */
+ float3 pixel_dir_x; /** Direction for increasing x for one pixel to the next,
+ * in world coordinates. */
+ float3 pixel_dir_y; /** Direction for increasing y for one pixel to the next,
+ * in world coordinates. */
+ float3 sensor_dir_z; /** Normalized direction vector from eye through the
+ * sensor in z direction (optical axis). */
+ float half_pixel_size; /** Half size of a pixel, in world coordinates. This
+ * must be consistent with pixel_dir_x and pixel_dir_y!
+ */
+ float focal_length; /** The focal length, if applicable. */
+ uint aperture_width; /** Full image width in px, possibly not fully used
+ * in case of a shifted principal point. */
+ uint aperture_height; /** Full image height in px, possibly not fully used
+ * in case of a shifted principal point. */
+ uint film_width; /** Resulting image width. */
+ uint film_height; /** Resulting image height. */
+ /** The top left coordinates (inclusive) of the film in the full aperture. */
+ uint film_border_left, film_border_top;
+ int32_t principal_point_offset_x; /** Horizontal principal point offset. */
+ int32_t principal_point_offset_y; /** Vertical principal point offset. */
+ float min_dist; /** Minimum distance for a ball to be rendered. */
+ float max_dist; /** Maximum distance for a ball to be rendered. */
+ float norm_fac; /** 1 / (max_dist - min_dist), pre-computed. */
+ /** The depth where to place the background, in normalized coordinates where
+ * 0. is the backmost depth and 1. the frontmost. */
+ float background_normalization_depth;
+ /** The number of image content channels to use. Usually three. */
+ uint n_channels;
+ /** Whether to use an orthogonal instead of a perspective projection. */
+ bool orthogonal_projection;
+ /** Whether to use a right-handed system (inverts the z axis). */
+ bool right_handed;
+};
+
+inline bool operator==(const CamInfo& a, const CamInfo& b) {
+ return a.film_width == b.film_width && a.film_height == b.film_height &&
+ a.background_normalization_depth == b.background_normalization_depth &&
+ a.n_channels == b.n_channels &&
+ a.orthogonal_projection == b.orthogonal_projection &&
+ a.right_handed == b.right_handed;
+};
+
+struct CamGradInfo {
+ HOST DEVICE CamGradInfo();
+ float3 cam_pos;
+ float3 pixel_0_0_center;
+ float3 pixel_dir_x;
+ float3 pixel_dir_y;
+};
+
+// TODO: remove once https://github.com/NVlabs/cub/issues/172 is resolved.
+struct IntWrapper {
+ int val;
+};
+
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/closest_sphere_tracker.device.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/closest_sphere_tracker.device.h
new file mode 100644
index 0000000000000000000000000000000000000000..a533dd0048e7f624af7c14a4017b19fde3accff5
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/closest_sphere_tracker.device.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_CLOSEST_SPHERE_TRACKER_DEVICE_H_
+#define PULSAR_NATIVE_INCLUDE_CLOSEST_SPHERE_TRACKER_DEVICE_H_
+
+#include "../global.h"
+
+namespace pulsar {
+namespace Renderer {
+
+/**
+ * A facility to track the closest spheres to the camera.
+ *
+ * Their max number is defined by MAX_GRAD_SPHERES (this is defined in
+ * `pulsar/native/global.h`). This is done to keep the performance as high as
+ * possible because this struct needs to do updates continuously on the GPU.
+ */
+struct ClosestSphereTracker {
+ public:
+ IHD ClosestSphereTracker(const int& n_track) : n_hits(0), n_track(n_track) {
+ PASSERT(n_track < MAX_GRAD_SPHERES);
+ // Initialize the sphere IDs to -1 and the weights to 0.
+ for (int i = 0; i < n_track; ++i) {
+ this->most_important_sphere_ids[i] = -1;
+ this->closest_sphere_intersection_depths[i] = MAX_FLOAT;
+ }
+ };
+
+ IHD void track(
+ const uint& sphere_idx,
+ const float& intersection_depth,
+ const uint& coord_x,
+ const uint& coord_y) {
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_TRACKER_PIX,
+ "tracker|tracking sphere %u (depth: %f).\n",
+ sphere_idx,
+ intersection_depth);
+ for (int i = IMIN(this->n_hits, n_track) - 1; i >= -1; --i) {
+ if (i < 0 ||
+ this->closest_sphere_intersection_depths[i] < intersection_depth) {
+ // Write position is i+1.
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_TRACKER_PIX,
+ "tracker|determined writing position: %d.\n",
+ i + 1);
+ if (i + 1 < n_track) {
+ // Shift every other sphere back.
+ for (int j = n_track - 1; j > i + 1; --j) {
+ this->closest_sphere_intersection_depths[j] =
+ this->closest_sphere_intersection_depths[j - 1];
+ this->most_important_sphere_ids[j] =
+ this->most_important_sphere_ids[j - 1];
+ }
+ this->closest_sphere_intersection_depths[i + 1] = intersection_depth;
+ this->most_important_sphere_ids[i + 1] = sphere_idx;
+ }
+ break;
+ }
+ }
+#if PULSAR_LOG_TRACKER_PIX
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_TRACKER_PIX,
+ "tracker|sphere list after adding sphere %u:\n",
+ sphere_idx);
+ for (int i = 0; i < n_track; ++i) {
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_TRACKER_PIX,
+ "tracker|sphere %d: %d (depth: %f).\n",
+ i,
+ this->most_important_sphere_ids[i],
+ this->closest_sphere_intersection_depths[i]);
+ }
+#endif // PULSAR_LOG_TRACKER_PIX
+ this->n_hits += 1;
+ }
+
+ /**
+ * Get the number of hits registered.
+ */
+ IHD int get_n_hits() const {
+ return this->n_hits;
+ }
+
+ /**
+ * Get the idx closest sphere ID.
+ *
+ * For example, get_closest_sphere_id(0) gives the overall closest
+ * sphere id.
+ *
+ * This method is implemented for highly optimized scenarios and will *not*
+ * perform an index check at runtime if assertions are disabled. idx must be
+ * >=0 and < IMIN(n_hits, n_track) for a valid result, if it is >=
+ * n_hits it will return -1.
+ */
+ IHD int get_closest_sphere_id(const int& idx) {
+ PASSERT(idx >= 0 && idx < n_track);
+ return this->most_important_sphere_ids[idx];
+ }
+
+ /**
+ * Get the idx closest sphere normalized_depth.
+ *
+ * For example, get_closest_sphere_depth(0) gives the overall closest
+ * sphere depth (normalized).
+ *
+ * This method is implemented for highly optimized scenarios and will *not*
+ * perform an index check at runtime if assertions are disabled. idx must be
+ * >=0 and < IMIN(n_hits, n_track) for a valid result, if it is >=
+ * n_hits it will return 1. + FEPS.
+ */
+ IHD float get_closest_sphere_depth(const int& idx) {
+ PASSERT(idx >= 0 && idx < n_track);
+ return this->closest_sphere_intersection_depths[idx];
+ }
+
+ private:
+ /** The number of registered hits so far. */
+ int n_hits;
+ /** The number of intersections to track. Must be (malloc(sizeof(TYPE) * (SIZE)))
+#define FREE_HOST(PTR) free(PTR)
+
+/* Include command definitions depending on CPU or GPU use. */
+
+#ifdef __CUDACC__
+// TODO: find out which compiler we're using here and use the suppression.
+// #pragma push
+// #pragma diag_suppress = 68
+#include
+// #pragma pop
+#include "../cuda/commands.h"
+#else
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Weverything"
+#pragma clang diagnostic pop
+#include "../host/commands.h"
+#endif
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.backward.instantiate.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.backward.instantiate.h
new file mode 100644
index 0000000000000000000000000000000000000000..75e85fd4dc88befc63e84ed4891f8ecb4b659bc4
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.backward.instantiate.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "./renderer.backward.device.h"
+
+namespace pulsar {
+namespace Renderer {
+
+template void backward(
+ Renderer* self,
+ const float* grad_im,
+ const float* image,
+ const float* forw_info,
+ const float* vert_pos,
+ const float* vert_col,
+ const float* vert_rad,
+ const CamInfo& cam,
+ const float& gamma,
+ float percent_allowed_difference,
+ const uint& max_n_hits,
+ const float* vert_opy,
+ const size_t& num_balls,
+ const uint& mode,
+ const bool& dif_pos,
+ const bool& dif_col,
+ const bool& dif_rad,
+ const bool& dif_cam,
+ const bool& dif_opy,
+ cudaStream_t stream);
+
+} // namespace Renderer
+} // namespace pulsar
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.construct.instantiate.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.construct.instantiate.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5ce722e29b063b04cb8efc0e880d9332bd35f23
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.construct.instantiate.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_RENDERER_CONSTRUCT_INSTANTIATE_H_
+#define PULSAR_NATIVE_INCLUDE_RENDERER_CONSTRUCT_INSTANTIATE_H_
+
+#include "./renderer.construct.device.h"
+
+namespace pulsar {
+namespace Renderer {
+template void construct(
+ Renderer* self,
+ const size_t& max_num_balls,
+ const int& width,
+ const int& height,
+ const bool& orthogonal_projection,
+ const bool& right_handed_system,
+ const float& background_normalization_depth,
+ const uint& n_channels,
+ const uint& n_track);
+}
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.create_selector.instantiate.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.create_selector.instantiate.h
new file mode 100644
index 0000000000000000000000000000000000000000..8e91a8bfb8e9b0f03db39c001e9363920b2eb35f
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.create_selector.instantiate.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_RENDERER_CREATE_SELECTOR_INSTANTIATE_H_
+#define PULSAR_NATIVE_INCLUDE_RENDERER_CREATE_SELECTOR_INSTANTIATE_H_
+
+#include "./renderer.create_selector.device.h"
+
+namespace pulsar {
+namespace Renderer {
+
+template GLOBAL void create_selector(
+ IntersectInfo const* const RESTRICT ii_sorted_d,
+ const uint num_balls,
+ const int min_x,
+ const int max_x,
+ const int min_y,
+ const int max_y,
+ /* Out variables. */
+ char* RESTRICT region_flags_d);
+
+}
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.destruct.instantiate.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.destruct.instantiate.h
new file mode 100644
index 0000000000000000000000000000000000000000..d41ba5a323d0bed9196dc804fab87929b2a726af
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.destruct.instantiate.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_RENDERER_DESTRUCT_INSTANTIATE_H_
+#define PULSAR_NATIVE_INCLUDE_RENDERER_DESTRUCT_INSTANTIATE_H_
+
+#include "./renderer.destruct.device.h"
+
+namespace pulsar {
+namespace Renderer {
+template void destruct(Renderer* self);
+}
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.fill_bg.device.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.fill_bg.device.h
new file mode 100644
index 0000000000000000000000000000000000000000..2a737d3eb609781f08120eb734982987866637f4
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.fill_bg.device.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_RENDERER_FILL_BG_DEVICE_H_
+#define PULSAR_NATIVE_INCLUDE_RENDERER_FILL_BG_DEVICE_H_
+
+#include "../global.h"
+#include "./camera.h"
+#include "./commands.h"
+#include "./renderer.h"
+
+namespace pulsar {
+namespace Renderer {
+
+template
+GLOBAL void fill_bg(
+ Renderer renderer,
+ const CamInfo cam,
+ float const* const bg_col_d,
+ const float gamma,
+ const uint mode) {
+ GET_PARALLEL_IDS_2D(coord_x, coord_y, cam.film_width, cam.film_height);
+ int write_loc = coord_y * cam.film_width * (3 + 2 * renderer.n_track) +
+ coord_x * (3 + 2 * renderer.n_track);
+ if (renderer.forw_info_d[write_loc + 1] // sm_d
+ == 0.f) {
+ // This location has not been processed yet.
+ // Write first the forw_info:
+ // sm_m
+ renderer.forw_info_d[write_loc] =
+ cam.background_normalization_depth / gamma;
+ // sm_d
+ renderer.forw_info_d[write_loc + 1] = 1.f;
+ // max_closest_possible_intersection_hit
+ renderer.forw_info_d[write_loc + 2] = -1.f;
+ // sphere IDs and intersection depths.
+ for (int i = 0; i < renderer.n_track; ++i) {
+ int sphere_id = -1;
+ IASF(sphere_id, renderer.forw_info_d[write_loc + 3 + i * 2]);
+ renderer.forw_info_d[write_loc + 3 + i * 2 + 1] = -1.f;
+ }
+ if (mode == 0) {
+ // Image background.
+ for (int i = 0; i < cam.n_channels; ++i) {
+ renderer.result_d
+ [coord_y * cam.film_width * cam.n_channels +
+ coord_x * cam.n_channels + i] = bg_col_d[i];
+ }
+ }
+ }
+ END_PARALLEL_2D_NORET();
+};
+
+} // namespace Renderer
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.render.device.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.render.device.h
new file mode 100644
index 0000000000000000000000000000000000000000..d1fe23f4ab5ac2723607c711268ece6954715480
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/pulsar/include/renderer.render.device.h
@@ -0,0 +1,416 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PULSAR_NATIVE_INCLUDE_RENDERER_RENDER_DEVICE_H_
+#define PULSAR_NATIVE_INCLUDE_RENDERER_RENDER_DEVICE_H_
+
+#include "../global.h"
+#include "./camera.device.h"
+#include "./commands.h"
+#include "./math.h"
+#include "./renderer.h"
+
+#include "./closest_sphere_tracker.device.h"
+#include "./renderer.draw.device.h"
+
+namespace pulsar {
+namespace Renderer {
+
+template
+GLOBAL void render(
+ size_t const* const RESTRICT
+ num_balls, /** Number of balls relevant for this pass. */
+ IntersectInfo const* const RESTRICT ii_d, /** Intersect information. */
+ DrawInfo const* const RESTRICT di_d, /** Draw information. */
+ float const* const RESTRICT min_depth_d, /** Minimum depth per sphere. */
+ int const* const RESTRICT ids_d, /** IDs. */
+ float const* const RESTRICT op_d, /** Opacity. */
+ const CamInfo cam_norm, /** Camera normalized with all vectors to be in the
+ * camera coordinate system.
+ */
+ const float gamma, /** Transparency parameter. **/
+ const float percent_allowed_difference, /** Maximum allowed
+ error in color. */
+ const uint max_n_hits,
+ const float* bg_col,
+ const uint mode,
+ const int x_min,
+ const int y_min,
+ const int x_step,
+ const int y_step,
+ // Out variables.
+ float* const RESTRICT result_d, /** The result image. */
+ float* const RESTRICT forw_info_d, /** Additional information needed for the
+ grad computation. */
+ const int n_track /** The number of spheres to track for backprop. */
+) {
+ // Do not early stop threads in this block here. They can all contribute to
+ // the scanning process, we just have to prevent from writing their result.
+ GET_PARALLEL_IDS_2D(offs_x, offs_y, x_step, y_step);
+ // Variable declarations and const initializations.
+ const float ln_pad_over_1minuspad =
+ FLN(percent_allowed_difference / (1.f - percent_allowed_difference));
+ /** A facility to track the closest spheres to the camera
+ (in preparation for gradient calculation). */
+ ClosestSphereTracker tracker(n_track);
+ const uint coord_x = x_min + offs_x; /** Ray coordinate x. */
+ const uint coord_y = y_min + offs_y; /** Ray coordinate y. */
+ float3 ray_dir_norm; /** Ray cast through the pixel, normalized. */
+ float2 projected_ray; /** Ray intersection with the sensor. */
+ if (cam_norm.orthogonal_projection) {
+ ray_dir_norm = cam_norm.sensor_dir_z;
+ projected_ray.x = static_cast(coord_x);
+ projected_ray.y = static_cast(coord_y);
+ } else {
+ ray_dir_norm = normalize(
+ cam_norm.pixel_0_0_center + coord_x * cam_norm.pixel_dir_x +
+ coord_y * cam_norm.pixel_dir_y);
+ // This is a reasonable assumption for normal focal lengths and image sizes.
+ PASSERT(FABS(ray_dir_norm.z) > FEPS);
+ projected_ray.x = ray_dir_norm.x / ray_dir_norm.z * cam_norm.focal_length;
+ projected_ray.y = ray_dir_norm.y / ray_dir_norm.z * cam_norm.focal_length;
+ }
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|ray_dir_norm: %.9f, %.9f, %.9f. projected_ray: %.9f, %.9f.\n",
+ ray_dir_norm.x,
+ ray_dir_norm.y,
+ ray_dir_norm.z,
+ projected_ray.x,
+ projected_ray.y);
+ // Set up shared infrastructure.
+ /** This entire thread block. */
+ cg::thread_block thread_block = cg::this_thread_block();
+ /** The collaborators within a warp. */
+ cg::coalesced_group thread_warp = cg::coalesced_threads();
+ /** The number of loaded balls in the load buffer di_l. */
+ SHARED uint n_loaded;
+ /** Draw information buffer. */
+ SHARED DrawInfo di_l[RENDER_BUFFER_SIZE];
+ /** The original sphere id of each loaded sphere. */
+ SHARED uint sphere_id_l[RENDER_BUFFER_SIZE];
+ /** The number of pixels in this block that are done. */
+ SHARED int n_pixels_done;
+ /** Whether loading of balls is completed. */
+ SHARED bool loading_done;
+ /** The number of balls loaded overall (just for statistics). */
+ [[maybe_unused]] SHARED int n_balls_loaded;
+ /** The area this thread block covers. */
+ SHARED IntersectInfo block_area;
+ if (thread_block.thread_rank() == 0) {
+ // Initialize the shared variables.
+ n_loaded = 0;
+ block_area.min.x = static_cast(coord_x);
+ block_area.max.x = static_cast(IMIN(
+ coord_x + blockDim.x, cam_norm.film_border_left + cam_norm.film_width));
+ block_area.min.y = static_cast(coord_y);
+ block_area.max.y = static_cast(IMIN(
+ coord_y + blockDim.y, cam_norm.film_border_top + cam_norm.film_height));
+ n_pixels_done = 0;
+ loading_done = false;
+ n_balls_loaded = 0;
+ }
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|block_area.min: %d, %d. block_area.max: %d, %d.\n",
+ block_area.min.x,
+ block_area.min.y,
+ block_area.max.x,
+ block_area.max.y);
+ // Initialization of the pixel with the background color.
+ /**
+ * The result of this very pixel.
+ * the offset calculation might overflow if this thread is out of
+ * bounds of the film. However, in this case result is not
+ * accessed, so this is fine.
+ */
+ float* result = result_d +
+ (coord_y - cam_norm.film_border_top) * cam_norm.film_width *
+ cam_norm.n_channels +
+ (coord_x - cam_norm.film_border_left) * cam_norm.n_channels;
+ if (coord_x >= cam_norm.film_border_left &&
+ coord_x < cam_norm.film_border_left + cam_norm.film_width &&
+ coord_y >= cam_norm.film_border_top &&
+ coord_y < cam_norm.film_border_top + cam_norm.film_height) {
+ // Initialize the result.
+ if (mode == 0u) {
+ for (uint c_id = 0; c_id < cam_norm.n_channels; ++c_id)
+ result[c_id] = bg_col[c_id];
+ } else {
+ result[0] = 0.f;
+ }
+ }
+ /** Normalization denominator. */
+ float sm_d = 1.f;
+ /** Normalization tracker for stable softmax. The maximum observed value. */
+ float sm_m = cam_norm.background_normalization_depth / gamma;
+ /** Whether this pixel has had all information needed for drawing. */
+ bool done =
+ (coord_x < cam_norm.film_border_left ||
+ coord_x >= cam_norm.film_border_left + cam_norm.film_width ||
+ coord_y < cam_norm.film_border_top ||
+ coord_y >= cam_norm.film_border_top + cam_norm.film_height);
+ /** The depth threshold for a new point to have at least
+ * `percent_allowed_difference` influence on the result color. All points that
+ * are further away than this are ignored.
+ */
+ float depth_threshold = done ? -1.f : MAX_FLOAT;
+ /** The closest intersection possible of a ball that was hit by this pixel
+ * ray. */
+ float max_closest_possible_intersection_hit = -1.f;
+ bool hit; /** Whether a sphere was hit. */
+ float intersection_depth; /** The intersection_depth for a sphere at this
+ pixel. */
+ float closest_possible_intersection; /** The closest possible intersection
+ for this sphere. */
+ float max_closest_possible_intersection;
+ // Sync up threads so that everyone is similarly initialized.
+ thread_block.sync();
+ //! Coalesced loading and intersection analysis of balls.
+ for (uint ball_idx = thread_block.thread_rank();
+ ball_idx < iDivCeil(static_cast(*num_balls), thread_block.size()) *
+ thread_block.size() &&
+ !loading_done && n_pixels_done < thread_block.size();
+ ball_idx += thread_block.size()) {
+ if (ball_idx < static_cast(*num_balls)) { // Account for overflow.
+ const IntersectInfo& ii = ii_d[ball_idx];
+ hit = (ii.min.x <= block_area.max.x) && (ii.max.x > block_area.min.x) &&
+ (ii.min.y <= block_area.max.y) && (ii.max.y > block_area.min.y);
+ if (hit) {
+ uint write_idx = ATOMICADD_B(&n_loaded, 1u);
+ di_l[write_idx] = di_d[ball_idx];
+ sphere_id_l[write_idx] = static_cast(ids_d[ball_idx]);
+ PULSAR_LOG_DEV_PIXB(
+ PULSAR_LOG_RENDER_PIX,
+ "render|found intersection with sphere %u.\n",
+ sphere_id_l[write_idx]);
+ }
+ if (ii.min.x == MAX_USHORT)
+ // This is an invalid sphere (out of image). These spheres have
+ // maximum depth. Since we ordered the spheres by earliest possible
+ // intersection depth we re certain that there will no other sphere
+ // that is relevant after this one.
+ loading_done = true;
+ }
+ // Reset n_pixels_done.
+ n_pixels_done = 0;
+ thread_block.sync(); // Make sure n_loaded is updated.
+ if (n_loaded > RENDER_BUFFER_LOAD_THRESH) {
+ // The load buffer is full enough. Draw.
+ if (thread_block.thread_rank() == 0)
+ n_balls_loaded += n_loaded;
+ max_closest_possible_intersection = 0.f;
+ // This excludes threads outside of the image boundary. Also, it reduces
+ // block artifacts.
+ if (!done) {
+ for (uint draw_idx = 0; draw_idx < n_loaded; ++draw_idx) {
+ intersection_depth = 0.f;
+ if (cam_norm.orthogonal_projection) {
+ // The closest possible intersection is the distance to the camera
+ // plane.
+ closest_possible_intersection = min_depth_d[sphere_id_l[draw_idx]];
+ } else {
+ closest_possible_intersection =
+ di_l[draw_idx].t_center - di_l[draw_idx].radius;
+ }
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|drawing sphere %u (depth: %f, "
+ "closest possible intersection: %f).\n",
+ sphere_id_l[draw_idx],
+ di_l[draw_idx].t_center,
+ closest_possible_intersection);
+ hit = draw(
+ di_l[draw_idx], // Sphere to draw.
+ op_d == NULL ? 1.f : op_d[sphere_id_l[draw_idx]], // Opacity.
+ cam_norm, // Cam.
+ gamma, // Gamma.
+ ray_dir_norm, // Ray direction.
+ projected_ray, // Ray intersection with the image.
+ // Mode switches.
+ true, // Draw.
+ false,
+ false,
+ false,
+ false,
+ false, // No gradients.
+ // Position info.
+ coord_x,
+ coord_y,
+ sphere_id_l[draw_idx],
+ // Optional in variables.
+ NULL, // intersect information.
+ NULL, // ray_dir.
+ NULL, // norm_ray_dir.
+ NULL, // grad_pix.
+ &ln_pad_over_1minuspad,
+ // in/out variables
+ &sm_d,
+ &sm_m,
+ result,
+ // Optional out.
+ &depth_threshold,
+ &intersection_depth,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL // gradients.
+ );
+ if (hit) {
+ max_closest_possible_intersection_hit = FMAX(
+ max_closest_possible_intersection_hit,
+ closest_possible_intersection);
+ tracker.track(
+ sphere_id_l[draw_idx], intersection_depth, coord_x, coord_y);
+ }
+ max_closest_possible_intersection = FMAX(
+ max_closest_possible_intersection, closest_possible_intersection);
+ }
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|max_closest_possible_intersection: %f, "
+ "depth_threshold: %f.\n",
+ max_closest_possible_intersection,
+ depth_threshold);
+ }
+ done = done ||
+ (percent_allowed_difference > 0.f &&
+ max_closest_possible_intersection > depth_threshold) ||
+ tracker.get_n_hits() >= max_n_hits;
+ uint warp_done = thread_warp.ballot(done);
+ if (thread_warp.thread_rank() == 0)
+ ATOMICADD_B(&n_pixels_done, POPC(warp_done));
+ // This sync is necessary to keep n_loaded until all threads are done with
+ // painting.
+ thread_block.sync();
+ n_loaded = 0;
+ }
+ thread_block.sync();
+ }
+ if (thread_block.thread_rank() == 0)
+ n_balls_loaded += n_loaded;
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|loaded %d balls in total.\n",
+ n_balls_loaded);
+ if (!done) {
+ for (uint draw_idx = 0; draw_idx < n_loaded; ++draw_idx) {
+ intersection_depth = 0.f;
+ if (cam_norm.orthogonal_projection) {
+ // The closest possible intersection is the distance to the camera
+ // plane.
+ closest_possible_intersection = min_depth_d[sphere_id_l[draw_idx]];
+ } else {
+ closest_possible_intersection =
+ di_l[draw_idx].t_center - di_l[draw_idx].radius;
+ }
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|drawing sphere %u (depth: %f, "
+ "closest possible intersection: %f).\n",
+ sphere_id_l[draw_idx],
+ di_l[draw_idx].t_center,
+ closest_possible_intersection);
+ hit = draw(
+ di_l[draw_idx], // Sphere to draw.
+ op_d == NULL ? 1.f : op_d[sphere_id_l[draw_idx]], // Opacity.
+ cam_norm, // Cam.
+ gamma, // Gamma.
+ ray_dir_norm, // Ray direction.
+ projected_ray, // Ray intersection with the image.
+ // Mode switches.
+ true, // Draw.
+ false,
+ false,
+ false,
+ false,
+ false, // No gradients.
+ // Logging info.
+ coord_x,
+ coord_y,
+ sphere_id_l[draw_idx],
+ // Optional in variables.
+ NULL, // intersect information.
+ NULL, // ray_dir.
+ NULL, // norm_ray_dir.
+ NULL, // grad_pix.
+ &ln_pad_over_1minuspad,
+ // in/out variables
+ &sm_d,
+ &sm_m,
+ result,
+ // Optional out.
+ &depth_threshold,
+ &intersection_depth,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL // gradients.
+ );
+ if (hit) {
+ max_closest_possible_intersection_hit = FMAX(
+ max_closest_possible_intersection_hit,
+ closest_possible_intersection);
+ tracker.track(
+ sphere_id_l[draw_idx], intersection_depth, coord_x, coord_y);
+ }
+ }
+ }
+ if (coord_x < cam_norm.film_border_left ||
+ coord_y < cam_norm.film_border_top ||
+ coord_x >= cam_norm.film_border_left + cam_norm.film_width ||
+ coord_y >= cam_norm.film_border_top + cam_norm.film_height) {
+ RETURN_PARALLEL();
+ }
+ if (mode == 1u) {
+ // The subtractions, for example coord_y - cam_norm.film_border_left, are
+ // safe even though both components are uints. We checked their relation
+ // just above.
+ result_d
+ [(coord_y - cam_norm.film_border_top) * cam_norm.film_width *
+ cam_norm.n_channels +
+ (coord_x - cam_norm.film_border_left) * cam_norm.n_channels] =
+ static_cast(tracker.get_n_hits());
+ } else {
+ float sm_d_normfac = FRCP(FMAX(sm_d, FEPS));
+ for (uint c_id = 0; c_id < cam_norm.n_channels; ++c_id)
+ result[c_id] *= sm_d_normfac;
+ int write_loc = (coord_y - cam_norm.film_border_top) * cam_norm.film_width *
+ (3 + 2 * n_track) +
+ (coord_x - cam_norm.film_border_left) * (3 + 2 * n_track);
+ forw_info_d[write_loc] = sm_m;
+ forw_info_d[write_loc + 1] = sm_d;
+ forw_info_d[write_loc + 2] = max_closest_possible_intersection_hit;
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|writing the %d most important ball infos.\n",
+ IMIN(n_track, tracker.get_n_hits()));
+ for (int i = 0; i < n_track; ++i) {
+ int sphere_id = tracker.get_closest_sphere_id(i);
+ IASF(sphere_id, forw_info_d[write_loc + 3 + i * 2]);
+ forw_info_d[write_loc + 3 + i * 2 + 1] =
+ tracker.get_closest_sphere_depth(i) == MAX_FLOAT
+ ? -1.f
+ : tracker.get_closest_sphere_depth(i);
+ PULSAR_LOG_DEV_PIX(
+ PULSAR_LOG_RENDER_PIX,
+ "render|writing %d most important: id: %d, normalized depth: %f.\n",
+ i,
+ tracker.get_closest_sphere_id(i),
+ tracker.get_closest_sphere_depth(i));
+ }
+ }
+ END_PARALLEL_2D();
+}
+
+} // namespace Renderer
+} // namespace pulsar
+
+#endif
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.cuh b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..600d7a1afff8a5089ad2d8d8023e195bcaab480c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.cuh
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// The default value of the NDC range is [-1, 1], however in the case that
+// H != W, the NDC range is set such that the shorter side has range [-1, 1] and
+// the longer side is scaled by the ratio of H:W. S1 is the dimension for which
+// the NDC range is calculated and S2 is the other image dimension.
+// e.g. to get the NDC x range S1 = W and S2 = H
+__device__ inline float NonSquareNdcRange(int S1, int S2) {
+ float range = 2.0f;
+ if (S1 > S2) {
+ // First multiply S1 by float range so that division results
+ // in a float value.
+ range = (S1 * range) / S2;
+ }
+ return range;
+}
+
+// Given a pixel coordinate 0 <= i < S1, convert it to a normalized device
+// coordinates. We divide the NDC range into S1 evenly-sized
+// pixels, and assume that each pixel falls in the *center* of its range.
+// The default value of the NDC range is [-1, 1], however in the case that
+// H != W, the NDC range is set such that the shorter side has range [-1, 1] and
+// the longer side is scaled by the ratio of H:W. The dimension of i should be
+// S1 and the other image dimension is S2 For example, to get the x and y NDC
+// coordinates or a given pixel i:
+// x = PixToNonSquareNdc(i, W, H)
+// y = PixToNonSquareNdc(i, H, W)
+__device__ inline float PixToNonSquareNdc(int i, int S1, int S2) {
+ float range = NonSquareNdcRange(S1, S2);
+ // NDC: offset + (i * pixel_width + half_pixel_width)
+ // The NDC range is [-range/2, range/2].
+ float offset = (range / 2.0f);
+ return -offset + (range * i + offset) / S1;
+}
+
+// The maximum number of points per pixel that we can return. Since we use
+// thread-local arrays to hold and sort points, the maximum size of the array
+// needs to be known at compile time. There might be some fancy template magic
+// we could use to make this more dynamic, but for now just fix a constant.
+// TODO: is 8 enough? Would increasing have performance considerations?
+const int32_t kMaxPointsPerPixel = 150;
+
+const int32_t kMaxItemsPerBin = 22;
+
+template
+__device__ inline void BubbleSort(T* arr, int n) {
+ // Bubble sort. We only use it for tiny thread-local arrays (n < 8); in this
+ // regime we care more about warp divergence than computational complexity.
+ for (int i = 0; i < n - 1; ++i) {
+ for (int j = 0; j < n - i - 1; ++j) {
+ if (arr[j + 1] < arr[j]) {
+ T temp = arr[j];
+ arr[j] = arr[j + 1];
+ arr[j + 1] = temp;
+ }
+ }
+ }
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..6980afc4a49962760283c46ac415faa5ab76ce8e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterization_utils.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// The default value of the NDC range is [-1, 1], however in the case that
+// H != W, the NDC range is set such that the shorter side has range [-1, 1] and
+// the longer side is scaled by the ratio of H:W. S1 is the dimension for which
+// the NDC range is calculated and S2 is the other image dimension.
+// e.g. to get the NDC x range S1 = W and S2 = H
+inline float NonSquareNdcRange(int S1, int S2) {
+ float range = 2.0f;
+ if (S1 > S2) {
+ range = (S1 * range) / S2;
+ }
+ return range;
+}
+
+// Given a pixel coordinate 0 <= i < S1, convert it to a normalized device
+// coordinates. We divide the NDC range into S1 evenly-sized
+// pixels, and assume that each pixel falls in the *center* of its range.
+// The default value of the NDC range is [-1, 1], however in the case that
+// H != W, the NDC range is set such that the shorter side has range [-1, 1] and
+// the longer side is scaled by the ratio of H:W. The dimension of i should be
+// S1 and the other image dimension is S2 For example, to get the x and y NDC
+// coordinates or a given pixel i:
+// x = PixToNonSquareNdc(i, W, H)
+// y = PixToNonSquareNdc(i, H, W)
+inline float PixToNonSquareNdc(int i, int S1, int S2) {
+ float range = NonSquareNdcRange(S1, S2);
+ // NDC: offset + (i * pixel_width + half_pixel_width)
+ // The NDC range is [-range/2, range/2].
+ const float offset = (range / 2.0f);
+ return -offset + (range * i + offset) / S1;
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points.h b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points.h
new file mode 100644
index 0000000000000000000000000000000000000000..4e74e9e2b0600dccbcbe3e745e80f13a8149ca99
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points.h
@@ -0,0 +1,360 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+#include
+#include
+#include
+#include "rasterize_coarse/rasterize_coarse.h"
+#include "utils/pytorch3d_cutils.h"
+
+// ****************************************************************************
+// * NAIVE RASTERIZATION *
+// ****************************************************************************
+
+std::tuple RasterizePointsNaiveCpu(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int points_per_pixel);
+
+#ifdef WITH_CUDA
+std::tuple
+RasterizePointsNaiveCuda(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int points_per_pixel);
+#endif
+// Naive (forward) pointcloud rasterization: For each pixel, for each point,
+// check whether that point hits the pixel.
+//
+// Args:
+// points: Tensor of shape (P, 3) giving (packed) positions for
+// points in all N pointclouds in the batch where P is the total
+// number of points in the batch across all pointclouds. These points
+// are expected to be in NDC coordinates in the range [-1, 1].
+// cloud_to_packed_first_idx: LongTensor of shape (N) giving the index in
+// points_packed of the first point in each pointcloud
+// in the batch where N is the batch size.
+// num_points_per_cloud: LongTensor of shape (N) giving the number of points
+// for each pointcloud in the batch.
+// image_size: Tuple (H, W) giving the size in pixels of the output
+// image to be rasterized.
+// radius: FloatTensor of shape (P) giving the radius (in NDC units) of
+// each point in points.
+// points_per_pixel: (K) The number closest of points to return for each pixel
+//
+// Returns:
+// A 4 element tuple of:
+// idxs: int32 Tensor of shape (N, S, S, K) giving the indices of the
+// closest K points along the z-axis for each pixel, padded with -1 for
+// pixels hit by fewer than K points. The indices refer to points in
+// points packed i.e a tensor of shape (P, 3) representing the flattened
+// points for all pointclouds in the batch.
+// zbuf: float32 Tensor of shape (N, S, S, K) giving the depth of each
+// closest point for each pixel.
+// dists: float32 Tensor of shape (N, S, S, K) giving squared Euclidean
+// distance in the (NDC) x/y plane between each pixel and its K closest
+// points along the z axis.
+std::tuple RasterizePointsNaive(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int points_per_pixel) {
+ if (points.is_cuda() && cloud_to_packed_first_idx.is_cuda() &&
+ num_points_per_cloud.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(points);
+ CHECK_CUDA(cloud_to_packed_first_idx);
+ CHECK_CUDA(num_points_per_cloud);
+ CHECK_CUDA(radius);
+ return RasterizePointsNaiveCuda(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ points_per_pixel);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return RasterizePointsNaiveCpu(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ points_per_pixel);
+ }
+}
+
+// ****************************************************************************
+// * COARSE RASTERIZATION *
+// ****************************************************************************
+
+// RasterizePointsCoarseCuda in rasterize_coarse/rasterize_coarse.h
+
+torch::Tensor RasterizePointsCoarseCpu(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int bin_size,
+ const int max_points_per_bin);
+
+// Args:
+// points: Tensor of shape (P, 3) giving (packed) positions for
+// points in all N pointclouds in the batch where P is the total
+// number of points in the batch across all pointclouds. These points
+// are expected to be in NDC coordinates in the range [-1, 1].
+// cloud_to_packed_first_idx: LongTensor of shape (N) giving the index in
+// points_packed of the first point in each pointcloud
+// in the batch where N is the batch size.
+// num_points_per_cloud: LongTensor of shape (N) giving the number of points
+// for each pointcloud in the batch.
+// image_size: Tuple (H, W) giving the size in pixels of the output
+// image to be rasterized.
+// radius: FloatTensor of shape (P) giving the radius (in NDC units) of
+// each point in points.
+// bin_size: Size of each bin within the image (in pixels)
+// max_points_per_bin: The maximum number of points allowed to fall into each
+// bin when using coarse-to-fine rasterization.
+//
+// Returns:
+// points_per_bin: Tensor of shape (N, num_bins, num_bins) giving the number
+// of points that fall in each bin
+// bin_points: Tensor of shape (N, num_bins, num_bins, K) giving the indices
+// of points that fall into each bin.
+torch::Tensor RasterizePointsCoarse(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int bin_size,
+ const int max_points_per_bin) {
+ if (points.is_cuda() && cloud_to_packed_first_idx.is_cuda() &&
+ num_points_per_cloud.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(points);
+ CHECK_CUDA(cloud_to_packed_first_idx);
+ CHECK_CUDA(num_points_per_cloud);
+ CHECK_CUDA(radius);
+ return RasterizePointsCoarseCuda(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ bin_size,
+ max_points_per_bin);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return RasterizePointsCoarseCpu(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ bin_size,
+ max_points_per_bin);
+ }
+}
+
+// ****************************************************************************
+// * FINE RASTERIZATION *
+// ****************************************************************************
+
+#ifdef WITH_CUDA
+std::tuple RasterizePointsFineCuda(
+ const torch::Tensor& points,
+ const torch::Tensor& bin_points,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int bin_size,
+ const int points_per_pixel);
+#endif
+// Args:
+// points: Tensor of shape (P, 3) giving (packed) positions for
+// points in all N pointclouds in the batch where P is the total
+// number of points in the batch across all pointclouds. These points
+// are expected to be in NDC coordinates in the range [-1, 1].
+// bin_points: int32 Tensor of shape (N, B, B, M) giving the indices of points
+// that fall into each bin (output from coarse rasterization)
+// image_size: Tuple (H, W) giving the size in pixels of the output
+// image to be rasterized.
+// radius: FloatTensor of shape (P) giving the radius (in NDC units) of
+// each point in points.
+// bin_size: Size of each bin (in pixels)
+// points_per_pixel: How many points to rasterize for each pixel
+//
+// Returns (same as rasterize_points):
+// idxs: int32 Tensor of shape (N, S, S, K) giving the indices of the
+// closest K points along the z-axis for each pixel, padded with -1 for
+// pixels hit by fewer than K points. The indices refer to points in
+// points packed i.e a tensor of shape (P, 3) representing the flattened
+// points for all pointclouds in the batch.
+// zbuf: float32 Tensor of shape (N, S, S, K) giving the depth of each of each
+// closest point for each pixel
+// dists: float32 Tensor of shape (N, S, S, K) giving squared Euclidean
+// distance in the (NDC) x/y plane between each pixel and its K closest
+// points along the z axis.
+std::tuple RasterizePointsFine(
+ const torch::Tensor& points,
+ const torch::Tensor& bin_points,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int bin_size,
+ const int points_per_pixel) {
+ if (points.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(points);
+ CHECK_CUDA(bin_points);
+ return RasterizePointsFineCuda(
+ points, bin_points, image_size, radius, bin_size, points_per_pixel);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ AT_ERROR("NOT IMPLEMENTED");
+ }
+}
+
+// ****************************************************************************
+// * BACKWARD PASS *
+// ****************************************************************************
+
+torch::Tensor RasterizePointsBackwardCpu(
+ const torch::Tensor& points,
+ const torch::Tensor& idxs,
+ const torch::Tensor& grad_zbuf,
+ const torch::Tensor& grad_dists);
+
+#ifdef WITH_CUDA
+torch::Tensor RasterizePointsBackwardCuda(
+ const torch::Tensor& points,
+ const torch::Tensor& idxs,
+ const torch::Tensor& grad_zbuf,
+ const torch::Tensor& grad_dists);
+#endif
+// Args:
+// points: Tensor of shape (P, 3) giving (packed) positions for
+// points in all N pointclouds in the batch where P is the total
+// number of points in the batch across all pointclouds. These points
+// are expected to be in NDC coordinates in the range [-1, 1].
+// idxs: int32 Tensor of shape (N, H, W, K) (from forward pass)
+// grad_zbuf: float32 Tensor of shape (N, H, W, K) giving upstream gradient
+// d(loss)/d(zbuf) of the distances from each pixel to its nearest
+// points.
+// grad_dists: Tensor of shape (N, H, W, K) giving upstream gradient
+// d(loss)/d(dists) of the dists tensor returned by the forward
+// pass.
+//
+// Returns:
+// grad_points: float32 Tensor of shape (N, P, 3) giving downstream gradients
+torch::Tensor RasterizePointsBackward(
+ const torch::Tensor& points,
+ const torch::Tensor& idxs,
+ const torch::Tensor& grad_zbuf,
+ const torch::Tensor& grad_dists) {
+ if (points.is_cuda()) {
+#ifdef WITH_CUDA
+ CHECK_CUDA(points);
+ CHECK_CUDA(idxs);
+ CHECK_CUDA(grad_zbuf);
+ CHECK_CUDA(grad_dists);
+ return RasterizePointsBackwardCuda(points, idxs, grad_zbuf, grad_dists);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ return RasterizePointsBackwardCpu(points, idxs, grad_zbuf, grad_dists);
+ }
+}
+
+// ****************************************************************************
+// * MAIN ENTRY POINT *
+// ****************************************************************************
+
+// This is the main entry point for the forward pass of the point rasterizer;
+// it uses either naive or coarse-to-fine rasterization based on bin_size.
+//
+// Args:
+// points: Tensor of shape (P, 3) giving (packed) positions for
+// points in all N pointclouds in the batch where P is the total
+// number of points in the batch across all pointclouds. These points
+// are expected to be in NDC coordinates in the range [-1, 1].
+// cloud_to_packed_first_idx: LongTensor of shape (N) giving the index in
+// points_packed of the first point in each pointcloud
+// in the batch where N is the batch size.
+// num_points_per_cloud: LongTensor of shape (N) giving the number of points
+// for each pointcloud in the batch.
+// image_size: Tuple (H, W) giving the size in pixels of the output
+// image to be rasterized.
+// radius: FloatTensor of shape (P) giving the radius (in NDC units) of
+// each point in points.
+// points_per_pixel: (K) The number of points to return for each pixel
+// bin_size: Bin size (in pixels) for coarse-to-fine rasterization. Setting
+// bin_size=0 uses naive rasterization instead.
+// max_points_per_bin: The maximum number of points allowed to fall into each
+// bin when using coarse-to-fine rasterization.
+//
+// Returns:
+// idxs: int32 Tensor of shape (N, S, S, K) giving the indices of the
+// closest K points along the z-axis for each pixel, padded with -1 for
+// pixels hit by fewer than K points. The indices refer to points in
+// points packed i.e a tensor of shape (P, 3) representing the flattened
+// points for all pointclouds in the batch.
+// zbuf: float32 Tensor of shape (N, S, S, K) giving the depth of each of each
+// closest point for each pixel
+// dists: float32 Tensor of shape (N, S, S, K) giving squared Euclidean
+// distance in the (NDC) x/y plane between each pixel and its K closest
+// points along the z axis.
+std::tuple RasterizePoints(
+ const torch::Tensor& points,
+ const torch::Tensor& cloud_to_packed_first_idx,
+ const torch::Tensor& num_points_per_cloud,
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int points_per_pixel,
+ const int bin_size,
+ const int max_points_per_bin) {
+ if (bin_size == 0) {
+ // Use the naive per-pixel implementation
+ return RasterizePointsNaive(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ points_per_pixel);
+ } else {
+ // Use coarse-to-fine rasterization
+ const auto bin_points = RasterizePointsCoarse(
+ points,
+ cloud_to_packed_first_idx,
+ num_points_per_cloud,
+ image_size,
+ radius,
+ bin_size,
+ max_points_per_bin);
+ return RasterizePointsFine(
+ points, bin_points, image_size, radius, bin_size, points_per_pixel);
+ }
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points_cpu.cpp b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..29da4c497b89b2fe3e2e2d5b2563adbbcd6ef326
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/csrc/rasterize_points/rasterize_points_cpu.cpp
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include
+#include
+#include
+#include "rasterization_utils.h"
+
+std::tuple RasterizePointsNaiveCpu(
+ const torch::Tensor& points, // (P, 3)
+ const torch::Tensor& cloud_to_packed_first_idx, // (N)
+ const torch::Tensor& num_points_per_cloud, // (N)
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int points_per_pixel) {
+ const int32_t N = cloud_to_packed_first_idx.size(0); // batch_size.
+
+ const int H = std::get<0>(image_size);
+ const int W = std::get<1>(image_size);
+ const int K = points_per_pixel;
+
+ // Initialize output tensors.
+ auto int_opts = num_points_per_cloud.options().dtype(torch::kInt32);
+ auto float_opts = points.options().dtype(torch::kFloat32);
+ torch::Tensor point_idxs = torch::full({N, H, W, K}, -1, int_opts);
+ torch::Tensor zbuf = torch::full({N, H, W, K}, -1, float_opts);
+ torch::Tensor pix_dists = torch::full({N, H, W, K}, -1, float_opts);
+
+ auto points_a = points.accessor();
+ auto point_idxs_a = point_idxs.accessor();
+ auto zbuf_a = zbuf.accessor();
+ auto pix_dists_a = pix_dists.accessor();
+ auto radius_a = radius.accessor();
+
+ for (int n = 0; n < N; ++n) {
+ // Loop through each pointcloud in the batch.
+ // Get the start index of the points in points_packed and the num points
+ // in the point cloud.
+ const int point_start_idx =
+ cloud_to_packed_first_idx[n].item().to();
+ const int point_stop_idx =
+ (point_start_idx + num_points_per_cloud[n].item().to());
+
+ for (int yi = 0; yi < H; ++yi) {
+ // Reverse the order of yi so that +Y is pointing upwards in the image.
+ const int yidx = H - 1 - yi;
+ const float yf = PixToNonSquareNdc(yidx, H, W);
+
+ for (int xi = 0; xi < W; ++xi) {
+ // Reverse the order of xi so that +X is pointing to the left in the
+ // image.
+ const int xidx = W - 1 - xi;
+ const float xf = PixToNonSquareNdc(xidx, W, H);
+
+ // Use a priority queue to hold (z, idx, r)
+ std::priority_queue> q;
+ for (int p = point_start_idx; p < point_stop_idx; ++p) {
+ const float px = points_a[p][0];
+ const float py = points_a[p][1];
+ const float pz = points_a[p][2];
+ const float p_radius = radius_a[p];
+ const float radius2 = p_radius * p_radius;
+ if (pz < 0) {
+ continue;
+ }
+ const float dx = px - xf;
+ const float dy = py - yf;
+ const float dist2 = dx * dx + dy * dy;
+ if (dist2 < radius2) {
+ // The current point hit the current pixel
+ q.emplace(pz, p, dist2);
+ if ((int)q.size() > K) {
+ q.pop();
+ }
+ }
+ }
+ // Now all the points have been seen, so pop elements off the queue
+ // one by one and write them into the output tensors.
+ while (!q.empty()) {
+ auto t = q.top();
+ q.pop();
+ int i = q.size();
+ zbuf_a[n][yi][xi][i] = std::get<0>(t);
+ point_idxs_a[n][yi][xi][i] = std::get<1>(t);
+ pix_dists_a[n][yi][xi][i] = std::get<2>(t);
+ }
+ }
+ }
+ }
+ return std::make_tuple(point_idxs, zbuf, pix_dists);
+}
+
+torch::Tensor RasterizePointsCoarseCpu(
+ const torch::Tensor& points, // (P, 3)
+ const torch::Tensor& cloud_to_packed_first_idx, // (N)
+ const torch::Tensor& num_points_per_cloud, // (N)
+ const std::tuple image_size,
+ const torch::Tensor& radius,
+ const int bin_size,
+ const int max_points_per_bin) {
+ const int32_t N = cloud_to_packed_first_idx.size(0); // batch_size.
+ const int M = max_points_per_bin;
+
+ const float H = std::get<0>(image_size);
+ const float W = std::get<1>(image_size);
+
+ // Integer division round up.
+ const int BH = 1 + (H - 1) / bin_size;
+ const int BW = 1 + (W - 1) / bin_size;
+
+ auto opts = num_points_per_cloud.options().dtype(torch::kInt32);
+ torch::Tensor points_per_bin = torch::zeros({N, BH, BW}, opts);
+ torch::Tensor bin_points = torch::full({N, BH, BW, M}, -1, opts);
+
+ auto points_a = points.accessor();
+ auto points_per_bin_a = points_per_bin.accessor();
+ auto bin_points_a = bin_points.accessor();
+ auto radius_a = radius.accessor();
+
+ const float ndc_x_range = NonSquareNdcRange(W, H);
+ const float pixel_width_x = ndc_x_range / W;
+ const float bin_width_x = pixel_width_x * bin_size;
+
+ const float ndc_y_range = NonSquareNdcRange(H, W);
+ const float pixel_width_y = ndc_y_range / H;
+ const float bin_width_y = pixel_width_y * bin_size;
+
+ for (int n = 0; n < N; ++n) {
+ // Loop through each pointcloud in the batch.
+ // Get the start index of the points in points_packed and the num points
+ // in the point cloud.
+ const int point_start_idx =
+ cloud_to_packed_first_idx[n].item().to();
+ const int point_stop_idx =
+ (point_start_idx + num_points_per_cloud[n].item().to());
+
+ float bin_y_min = -1.0f;
+ float bin_y_max = bin_y_min + bin_width_y;
+
+ // Iterate through the horizontal bins from top to bottom.
+ for (int by = 0; by < BH; by++) {
+ float bin_x_min = -1.0f;
+ float bin_x_max = bin_x_min + bin_width_x;
+
+ // Iterate through bins on this horizontal line, left to right.
+ for (int bx = 0; bx < BW; bx++) {
+ int32_t points_hit = 0;
+ for (int p = point_start_idx; p < point_stop_idx; ++p) {
+ float px = points_a[p][0];
+ float py = points_a[p][1];
+ float pz = points_a[p][2];
+ const float p_radius = radius_a[p];
+ if (pz < 0) {
+ continue;
+ }
+ float point_x_min = px - p_radius;
+ float point_x_max = px + p_radius;
+ float point_y_min = py - p_radius;
+ float point_y_max = py + p_radius;
+
+ // Use a half-open interval so that points exactly on the
+ // boundary between bins will fall into exactly one bin.
+ bool x_hit = (point_x_min <= bin_x_max) && (bin_x_min <= point_x_max);
+ bool y_hit = (point_y_min <= bin_y_max) && (bin_y_min <= point_y_max);
+ if (x_hit && y_hit) {
+ // Got too many points for this bin, so throw an error.
+ if (points_hit >= max_points_per_bin) {
+ AT_ERROR("Got too many points per bin");
+ }
+ // The current point falls in the current bin, so
+ // record it.
+ bin_points_a[n][by][bx][points_hit] = p;
+ points_hit++;
+ }
+ }
+ // Record the number of points found in this bin
+ points_per_bin_a[n][by][bx] = points_hit;
+
+ // Shift the bin to the right for the next loop iteration
+ bin_x_min = bin_x_max;
+ bin_x_max = bin_x_min + bin_width_x;
+ }
+ // Shift the bin down for the next loop iteration
+ bin_y_min = bin_y_max;
+ bin_y_max = bin_y_min + bin_width_y;
+ }
+ }
+ return bin_points;
+}
+
+torch::Tensor RasterizePointsBackwardCpu(
+ const torch::Tensor& points, // (P, 3)
+ const torch::Tensor& idxs, // (N, H, W, K)
+ const torch::Tensor& grad_zbuf, // (N, H, W, K)
+ const torch::Tensor& grad_dists) { // (N, H, W, K)
+
+ const int N = idxs.size(0);
+ const int P = points.size(0);
+ const int H = idxs.size(1);
+ const int W = idxs.size(2);
+ const int K = idxs.size(3);
+
+ torch::Tensor grad_points = torch::zeros({P, 3}, points.options());
+
+ auto points_a = points.accessor();
+ auto idxs_a = idxs.accessor();
+ auto grad_dists_a = grad_dists.accessor();
+ auto grad_zbuf_a = grad_zbuf.accessor();
+ auto grad_points_a = grad_points.accessor();
+
+ for (int n = 0; n < N; ++n) { // Loop over images in the batch
+ for (int y = 0; y < H; ++y) { // Loop over rows in the image
+ // Reverse the order of yi so that +Y is pointing upwards in the image.
+ const int yidx = H - 1 - y;
+ // Y coordinate of the top of the pixel.
+ const float yf = PixToNonSquareNdc(yidx, H, W);
+
+ // Iterate through pixels on this horizontal line, left to right.
+ for (int x = 0; x < W; ++x) { // Loop over pixels in the row
+
+ // Reverse the order of xi so that +X is pointing to the left in the
+ // image.
+ const int xidx = W - 1 - x;
+ const float xf = PixToNonSquareNdc(xidx, W, H);
+ for (int k = 0; k < K; ++k) { // Loop over points for the pixel
+ const int p = idxs_a[n][y][x][k];
+ if (p < 0) {
+ break;
+ }
+ const float grad_dist2 = grad_dists_a[n][y][x][k];
+ const float px = points_a[p][0];
+ const float py = points_a[p][1];
+ const float dx = px - xf;
+ const float dy = py - yf;
+ // Remember: dists[n][y][x][k] = dx * dx + dy * dy;
+ const float grad_px = 2.0f * grad_dist2 * dx;
+ const float grad_py = 2.0f * grad_dist2 * dy;
+ grad_points_a[p][0] += grad_px;
+ grad_points_a[p][1] += grad_py;
+ grad_points_a[p][2] += grad_zbuf_a[n][y][x][k];
+ }
+ }
+ }
+ }
+ return grad_points;
+}
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94b012c45290aa772c9905b4cc7d1c80d1e8736a
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/__init__.py
@@ -0,0 +1,20 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+
+from .chamfer import chamfer_distance
+
+from .mesh_edge_loss import mesh_edge_loss
+
+from .mesh_laplacian_smoothing import mesh_laplacian_smoothing
+
+from .mesh_normal_consistency import mesh_normal_consistency
+from .point_mesh_distance import point_mesh_edge_distance, point_mesh_face_distance
+
+
+__all__ = [k for k in globals().keys() if not k.startswith("_")]
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/chamfer.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/chamfer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d7876690301ef55f5d84632592f9c156e455015
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/chamfer.py
@@ -0,0 +1,292 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from typing import Union
+
+import torch
+import torch.nn.functional as F
+from pytorch3d.ops.knn import knn_gather, knn_points
+from pytorch3d.structures.pointclouds import Pointclouds
+
+
+def _validate_chamfer_reduction_inputs(
+ batch_reduction: Union[str, None], point_reduction: Union[str, None]
+) -> None:
+ """Check the requested reductions are valid.
+
+ Args:
+ batch_reduction: Reduction operation to apply for the loss across the
+ batch, can be one of ["mean", "sum"] or None.
+ point_reduction: Reduction operation to apply for the loss across the
+ points, can be one of ["mean", "sum"] or None.
+ """
+ if batch_reduction is not None and batch_reduction not in ["mean", "sum"]:
+ raise ValueError('batch_reduction must be one of ["mean", "sum"] or None')
+ if point_reduction is not None and point_reduction not in ["mean", "sum", "max"]:
+ raise ValueError(
+ 'point_reduction must be one of ["mean", "sum", "max"] or None'
+ )
+ if point_reduction is None and batch_reduction is not None:
+ raise ValueError("Batch reduction must be None if point_reduction is None")
+
+
+def _handle_pointcloud_input(
+ points: Union[torch.Tensor, Pointclouds],
+ lengths: Union[torch.Tensor, None],
+ normals: Union[torch.Tensor, None],
+):
+ """
+ If points is an instance of Pointclouds, retrieve the padded points tensor
+ along with the number of points per batch and the padded normals.
+ Otherwise, return the input points (and normals) with the number of points per cloud
+ set to the size of the second dimension of `points`.
+ """
+ if isinstance(points, Pointclouds):
+ X = points.points_padded()
+ lengths = points.num_points_per_cloud()
+ normals = points.normals_padded() # either a tensor or None
+ elif torch.is_tensor(points):
+ if points.ndim != 3:
+ raise ValueError("Expected points to be of shape (N, P, D)")
+ X = points
+ if lengths is not None:
+ if lengths.ndim != 1 or lengths.shape[0] != X.shape[0]:
+ raise ValueError("Expected lengths to be of shape (N,)")
+ if lengths.max() > X.shape[1]:
+ raise ValueError("A length value was too long")
+ if lengths is None:
+ lengths = torch.full(
+ (X.shape[0],), X.shape[1], dtype=torch.int64, device=points.device
+ )
+ if normals is not None and normals.ndim != 3:
+ raise ValueError("Expected normals to be of shape (N, P, 3")
+ else:
+ raise ValueError(
+ "The input pointclouds should be either "
+ + "Pointclouds objects or torch.Tensor of shape "
+ + "(minibatch, num_points, 3)."
+ )
+ return X, lengths, normals
+
+
+def _chamfer_distance_single_direction(
+ x,
+ y,
+ x_lengths,
+ y_lengths,
+ x_normals,
+ y_normals,
+ weights,
+ point_reduction: Union[str, None],
+ norm: int,
+ abs_cosine: bool,
+):
+ return_normals = x_normals is not None and y_normals is not None
+
+ N, P1, D = x.shape
+
+ # Check if inputs are heterogeneous and create a lengths mask.
+ is_x_heterogeneous = (x_lengths != P1).any()
+ x_mask = (
+ torch.arange(P1, device=x.device)[None] >= x_lengths[:, None]
+ ) # shape [N, P1]
+ if y.shape[0] != N or y.shape[2] != D:
+ raise ValueError("y does not have the correct shape.")
+ if weights is not None:
+ if weights.size(0) != N:
+ raise ValueError("weights must be of shape (N,).")
+ if not (weights >= 0).all():
+ raise ValueError("weights cannot be negative.")
+ if weights.sum() == 0.0:
+ weights = weights.view(N, 1)
+ return ((x.sum((1, 2)) * weights) * 0.0, (x.sum((1, 2)) * weights) * 0.0)
+
+ cham_norm_x = x.new_zeros(())
+
+ x_nn = knn_points(x, y, lengths1=x_lengths, lengths2=y_lengths, norm=norm, K=1)
+ cham_x = x_nn.dists[..., 0] # (N, P1)
+
+ if is_x_heterogeneous:
+ cham_x[x_mask] = 0.0
+
+ if weights is not None:
+ cham_x *= weights.view(N, 1)
+
+ if return_normals:
+ # Gather the normals using the indices and keep only value for k=0
+ x_normals_near = knn_gather(y_normals, x_nn.idx, y_lengths)[..., 0, :]
+
+ cosine_sim = F.cosine_similarity(x_normals, x_normals_near, dim=2, eps=1e-6)
+ # If abs_cosine, ignore orientation and take the absolute value of the cosine sim.
+ cham_norm_x = 1 - (torch.abs(cosine_sim) if abs_cosine else cosine_sim)
+
+ if is_x_heterogeneous:
+ cham_norm_x[x_mask] = 0.0
+
+ if weights is not None:
+ cham_norm_x *= weights.view(N, 1)
+
+ if point_reduction == "max":
+ assert not return_normals
+ cham_x = cham_x.max(1).values # (N,)
+ elif point_reduction is not None:
+ # Apply point reduction
+ cham_x = cham_x.sum(1) # (N,)
+ if return_normals:
+ cham_norm_x = cham_norm_x.sum(1) # (N,)
+ if point_reduction == "mean":
+ x_lengths_clamped = x_lengths.clamp(min=1)
+ cham_x /= x_lengths_clamped
+ if return_normals:
+ cham_norm_x /= x_lengths_clamped
+
+ cham_dist = cham_x
+ cham_normals = cham_norm_x if return_normals else None
+ return cham_dist, cham_normals
+
+
+def _apply_batch_reduction(
+ cham_x, cham_norm_x, weights, batch_reduction: Union[str, None]
+):
+ if batch_reduction is None:
+ return (cham_x, cham_norm_x)
+ # batch_reduction == "sum"
+ N = cham_x.shape[0]
+ cham_x = cham_x.sum()
+ if cham_norm_x is not None:
+ cham_norm_x = cham_norm_x.sum()
+ if batch_reduction == "mean":
+ if weights is None:
+ div = max(N, 1)
+ elif weights.sum() == 0.0:
+ div = 1
+ else:
+ div = weights.sum()
+ cham_x /= div
+ if cham_norm_x is not None:
+ cham_norm_x /= div
+ return (cham_x, cham_norm_x)
+
+
+def chamfer_distance(
+ x,
+ y,
+ x_lengths=None,
+ y_lengths=None,
+ x_normals=None,
+ y_normals=None,
+ weights=None,
+ batch_reduction: Union[str, None] = "mean",
+ point_reduction: Union[str, None] = "mean",
+ norm: int = 2,
+ single_directional: bool = False,
+ abs_cosine: bool = True,
+):
+ """
+ Chamfer distance between two pointclouds x and y.
+
+ Args:
+ x: FloatTensor of shape (N, P1, D) or a Pointclouds object representing
+ a batch of point clouds with at most P1 points in each batch element,
+ batch size N and feature dimension D.
+ y: FloatTensor of shape (N, P2, D) or a Pointclouds object representing
+ a batch of point clouds with at most P2 points in each batch element,
+ batch size N and feature dimension D.
+ x_lengths: Optional LongTensor of shape (N,) giving the number of points in each
+ cloud in x.
+ y_lengths: Optional LongTensor of shape (N,) giving the number of points in each
+ cloud in y.
+ x_normals: Optional FloatTensor of shape (N, P1, D).
+ y_normals: Optional FloatTensor of shape (N, P2, D).
+ weights: Optional FloatTensor of shape (N,) giving weights for
+ batch elements for reduction operation.
+ batch_reduction: Reduction operation to apply for the loss across the
+ batch, can be one of ["mean", "sum"] or None.
+ point_reduction: Reduction operation to apply for the loss across the
+ points, can be one of ["mean", "sum", "max"] or None. Using "max" leads to the
+ Hausdorff distance.
+ norm: int indicates the norm used for the distance. Supports 1 for L1 and 2 for L2.
+ single_directional: If False (default), loss comes from both the distance between
+ each point in x and its nearest neighbor in y and each point in y and its nearest
+ neighbor in x. If True, loss is the distance between each point in x and its
+ nearest neighbor in y.
+ abs_cosine: If False, loss_normals is from one minus the cosine similarity.
+ If True (default), loss_normals is from one minus the absolute value of the
+ cosine similarity, which means that exactly opposite normals are considered
+ equivalent to exactly matching normals, i.e. sign does not matter.
+
+ Returns:
+ 2-element tuple containing
+
+ - **loss**: Tensor giving the reduced distance between the pointclouds
+ in x and the pointclouds in y. If point_reduction is None, a 2-element
+ tuple of Tensors containing forward and backward loss terms shaped (N, P1)
+ and (N, P2) (if single_directional is False) or a Tensor containing loss
+ terms shaped (N, P1) (if single_directional is True) is returned.
+ - **loss_normals**: Tensor giving the reduced cosine distance of normals
+ between pointclouds in x and pointclouds in y. Returns None if
+ x_normals and y_normals are None. If point_reduction is None, a 2-element
+ tuple of Tensors containing forward and backward loss terms shaped (N, P1)
+ and (N, P2) (if single_directional is False) or a Tensor containing loss
+ terms shaped (N, P1) (if single_directional is True) is returned.
+ """
+ _validate_chamfer_reduction_inputs(batch_reduction, point_reduction)
+
+ if not ((norm == 1) or (norm == 2)):
+ raise ValueError("Support for 1 or 2 norm.")
+
+ if point_reduction == "max" and (x_normals is not None or y_normals is not None):
+ raise ValueError('Normals must be None if point_reduction is "max"')
+
+ x, x_lengths, x_normals = _handle_pointcloud_input(x, x_lengths, x_normals)
+ y, y_lengths, y_normals = _handle_pointcloud_input(y, y_lengths, y_normals)
+
+ cham_x, cham_norm_x = _chamfer_distance_single_direction(
+ x,
+ y,
+ x_lengths,
+ y_lengths,
+ x_normals,
+ y_normals,
+ weights,
+ point_reduction,
+ norm,
+ abs_cosine,
+ )
+ if single_directional:
+ loss = cham_x
+ loss_normals = cham_norm_x
+ else:
+ cham_y, cham_norm_y = _chamfer_distance_single_direction(
+ y,
+ x,
+ y_lengths,
+ x_lengths,
+ y_normals,
+ x_normals,
+ weights,
+ point_reduction,
+ norm,
+ abs_cosine,
+ )
+ if point_reduction == "max":
+ loss = torch.maximum(cham_x, cham_y)
+ loss_normals = None
+ elif point_reduction is not None:
+ loss = cham_x + cham_y
+ if cham_norm_x is not None:
+ loss_normals = cham_norm_x + cham_norm_y
+ else:
+ loss_normals = None
+ else:
+ loss = (cham_x, cham_y)
+ if cham_norm_x is not None:
+ loss_normals = (cham_norm_x, cham_norm_y)
+ else:
+ loss_normals = None
+ return _apply_batch_reduction(loss, loss_normals, weights, batch_reduction)
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_edge_loss.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_edge_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..615fe5072b4411405c0f8e3fbf1b78ea9814d6c9
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_edge_loss.py
@@ -0,0 +1,52 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+import torch
+
+
+def mesh_edge_loss(meshes, target_length: float = 0.0):
+ """
+ Computes mesh edge length regularization loss averaged across all meshes
+ in a batch. Each mesh contributes equally to the final loss, regardless of
+ the number of edges per mesh in the batch by weighting each mesh with the
+ inverse number of edges. For example, if mesh 3 (out of N) has only E=4
+ edges, then the loss for each edge in mesh 3 should be multiplied by 1/E to
+ contribute to the final loss.
+
+ Args:
+ meshes: Meshes object with a batch of meshes.
+ target_length: Resting value for the edge length.
+
+ Returns:
+ loss: Average loss across the batch. Returns 0 if meshes contains
+ no meshes or all empty meshes.
+ """
+ if meshes.isempty():
+ return torch.tensor(
+ [0.0], dtype=torch.float32, device=meshes.device, requires_grad=True
+ )
+
+ N = len(meshes)
+ edges_packed = meshes.edges_packed() # (sum(E_n), 3)
+ verts_packed = meshes.verts_packed() # (sum(V_n), 3)
+ edge_to_mesh_idx = meshes.edges_packed_to_mesh_idx() # (sum(E_n), )
+ num_edges_per_mesh = meshes.num_edges_per_mesh() # N
+
+ # Determine the weight for each edge based on the number of edges in the
+ # mesh it corresponds to.
+ # TODO (nikhilar) Find a faster way of computing the weights for each edge
+ # as this is currently a bottleneck for meshes with a large number of faces.
+ weights = num_edges_per_mesh.gather(0, edge_to_mesh_idx)
+ weights = 1.0 / weights.float()
+
+ verts_edges = verts_packed[edges_packed]
+ v0, v1 = verts_edges.unbind(1)
+ loss = ((v0 - v1).norm(dim=1, p=2) - target_length) ** 2.0
+ loss = loss * weights
+
+ return loss.sum() / N
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_laplacian_smoothing.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_laplacian_smoothing.py
new file mode 100644
index 0000000000000000000000000000000000000000..02037841d74f849c026e98192be3275be20522d7
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_laplacian_smoothing.py
@@ -0,0 +1,137 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+
+import torch
+from pytorch3d.ops import cot_laplacian
+
+
+def mesh_laplacian_smoothing(meshes, method: str = "uniform"):
+ r"""
+ Computes the laplacian smoothing objective for a batch of meshes.
+ This function supports three variants of Laplacian smoothing,
+ namely with uniform weights("uniform"), with cotangent weights ("cot"),
+ and cotangent curvature ("cotcurv").For more details read [1, 2].
+
+ Args:
+ meshes: Meshes object with a batch of meshes.
+ method: str specifying the method for the laplacian.
+ Returns:
+ loss: Average laplacian smoothing loss across the batch.
+ Returns 0 if meshes contains no meshes or all empty meshes.
+
+ Consider a mesh M = (V, F), with verts of shape Nx3 and faces of shape Mx3.
+ The Laplacian matrix L is a NxN tensor such that LV gives a tensor of vectors:
+ for a uniform Laplacian, LuV[i] points to the centroid of its neighboring
+ vertices, a cotangent Laplacian LcV[i] is known to be an approximation of
+ the surface normal, while the curvature variant LckV[i] scales the normals
+ by the discrete mean curvature. For vertex i, assume S[i] is the set of
+ neighboring vertices to i, a_ij and b_ij are the "outside" angles in the
+ two triangles connecting vertex v_i and its neighboring vertex v_j
+ for j in S[i], as seen in the diagram below.
+
+ .. code-block:: python
+
+ a_ij
+ /\
+ / \
+ / \
+ / \
+ v_i /________\ v_j
+ \ /
+ \ /
+ \ /
+ \ /
+ \/
+ b_ij
+
+ The definition of the Laplacian is LV[i] = sum_j w_ij (v_j - v_i)
+ For the uniform variant, w_ij = 1 / |S[i]|
+ For the cotangent variant,
+ w_ij = (cot a_ij + cot b_ij) / (sum_k cot a_ik + cot b_ik)
+ For the cotangent curvature, w_ij = (cot a_ij + cot b_ij) / (4 A[i])
+ where A[i] is the sum of the areas of all triangles containing vertex v_i.
+
+ There is a nice trigonometry identity to compute cotangents. Consider a triangle
+ with side lengths A, B, C and angles a, b, c.
+
+ .. code-block:: python
+
+ c
+ /|\
+ / | \
+ / | \
+ B / H| \ A
+ / | \
+ / | \
+ /a_____|_____b\
+ C
+
+ Then cot a = (B^2 + C^2 - A^2) / 4 * area
+ We know that area = CH/2, and by the law of cosines we have
+
+ A^2 = B^2 + C^2 - 2BC cos a => B^2 + C^2 - A^2 = 2BC cos a
+
+ Putting these together, we get:
+
+ B^2 + C^2 - A^2 2BC cos a
+ _______________ = _________ = (B/H) cos a = cos a / sin a = cot a
+ 4 * area 2CH
+
+
+ [1] Desbrun et al, "Implicit fairing of irregular meshes using diffusion
+ and curvature flow", SIGGRAPH 1999.
+
+ [2] Nealan et al, "Laplacian Mesh Optimization", Graphite 2006.
+ """
+
+ if meshes.isempty():
+ return torch.tensor(
+ [0.0], dtype=torch.float32, device=meshes.device, requires_grad=True
+ )
+
+ N = len(meshes)
+ verts_packed = meshes.verts_packed() # (sum(V_n), 3)
+ faces_packed = meshes.faces_packed() # (sum(F_n), 3)
+ num_verts_per_mesh = meshes.num_verts_per_mesh() # (N,)
+ verts_packed_idx = meshes.verts_packed_to_mesh_idx() # (sum(V_n),)
+ weights = num_verts_per_mesh.gather(0, verts_packed_idx) # (sum(V_n),)
+ weights = 1.0 / weights.float()
+
+ # We don't want to backprop through the computation of the Laplacian;
+ # just treat it as a magic constant matrix that is used to transform
+ # verts into normals
+ with torch.no_grad():
+ if method == "uniform":
+ L = meshes.laplacian_packed()
+ elif method in ["cot", "cotcurv"]:
+ L, inv_areas = cot_laplacian(verts_packed, faces_packed)
+ if method == "cot":
+ norm_w = torch.sparse.sum(L, dim=1).to_dense().view(-1, 1)
+ idx = norm_w > 0
+ # pyre-fixme[58]: `/` is not supported for operand types `float` and
+ # `Tensor`.
+ norm_w[idx] = 1.0 / norm_w[idx]
+ else:
+ L_sum = torch.sparse.sum(L, dim=1).to_dense().view(-1, 1)
+ norm_w = 0.25 * inv_areas
+ else:
+ raise ValueError("Method should be one of {uniform, cot, cotcurv}")
+
+ if method == "uniform":
+ loss = L.mm(verts_packed)
+ elif method == "cot":
+ # pyre-fixme[61]: `norm_w` is undefined, or not always defined.
+ loss = L.mm(verts_packed) * norm_w - verts_packed
+ elif method == "cotcurv":
+ # pyre-fixme[61]: `norm_w` may not be initialized here.
+ loss = (L.mm(verts_packed) - L_sum * verts_packed) * norm_w
+ loss = loss.norm(dim=1)
+
+ loss = loss * weights
+ return loss.sum() / N
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_normal_consistency.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_normal_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..5466df30d19a62bd90984acdb91847f3c412eeab
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/mesh_normal_consistency.py
@@ -0,0 +1,134 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+import torch
+from pytorch3d import _C
+
+
+def mesh_normal_consistency(meshes):
+ r"""
+ Computes the normal consistency of each mesh in meshes.
+ We compute the normal consistency for each pair of neighboring faces.
+ If e = (v0, v1) is the connecting edge of two neighboring faces f0 and f1,
+ then the normal consistency between f0 and f1
+
+ .. code-block:: python
+
+ a
+ /\
+ / \
+ / f0 \
+ / \
+ v0 /____e___\ v1
+ \ /
+ \ /
+ \ f1 /
+ \ /
+ \/
+ b
+
+ The normal consistency is
+
+ .. code-block:: python
+
+ nc(f0, f1) = 1 - cos(n0, n1)
+
+ where cos(n0, n1) = n0^n1 / ||n0|| / ||n1|| is the cosine of the angle
+ between the normals n0 and n1, and
+
+ n0 = (v1 - v0) x (a - v0)
+ n1 = - (v1 - v0) x (b - v0) = (b - v0) x (v1 - v0)
+
+ This means that if nc(f0, f1) = 0 then n0 and n1 point to the same
+ direction, while if nc(f0, f1) = 2 then n0 and n1 point opposite direction.
+
+ .. note::
+ For well-constructed meshes the assumption that only two faces share an
+ edge is true. This assumption could make the implementation easier and faster.
+ This implementation does not follow this assumption. All the faces sharing e,
+ which can be any in number, are discovered.
+
+ Args:
+ meshes: Meshes object with a batch of meshes.
+
+ Returns:
+ loss: Average normal consistency across the batch.
+ Returns 0 if meshes contains no meshes or all empty meshes.
+ """
+ if meshes.isempty():
+ return torch.tensor(
+ [0.0], dtype=torch.float32, device=meshes.device, requires_grad=True
+ )
+
+ N = len(meshes)
+ verts_packed = meshes.verts_packed() # (sum(V_n), 3)
+ faces_packed = meshes.faces_packed() # (sum(F_n), 3)
+ edges_packed = meshes.edges_packed() # (sum(E_n), 2)
+ verts_packed_to_mesh_idx = meshes.verts_packed_to_mesh_idx() # (sum(V_n),)
+ face_to_edge = meshes.faces_packed_to_edges_packed() # (sum(F_n), 3)
+ E = edges_packed.shape[0] # sum(E_n)
+ F = faces_packed.shape[0] # sum(F_n)
+
+ # We don't want gradients for the following operation. The goal is to
+ # find for each edge e all the vertices associated with e. In the example
+ # above, the vertices associated with e are (a, b), i.e. the points connected
+ # on faces to e.
+ with torch.no_grad():
+ edge_idx = face_to_edge.reshape(F * 3) # (3 * F,) indexes into edges
+ vert_idx = (
+ faces_packed.view(1, F, 3).expand(3, F, 3).transpose(0, 1).reshape(3 * F, 3)
+ )
+ edge_idx, edge_sort_idx = edge_idx.sort()
+ vert_idx = vert_idx[edge_sort_idx]
+
+ # In well constructed meshes each edge is shared by precisely 2 faces
+ # However, in many meshes, this assumption is not always satisfied.
+ # We want to find all faces that share an edge, a number which can
+ # vary and which depends on the topology.
+ # In particular, we find the vertices not on the edge on the shared faces.
+ # In the example above, we want to associate edge e with vertices a and b.
+ # This operation is done more efficiently in cpu with lists.
+ # TODO(gkioxari) find a better way to do this.
+
+ # edge_idx represents the index of the edge for each vertex. We can count
+ # the number of vertices which are associated with each edge.
+ # There can be a different number for each edge.
+ edge_num = edge_idx.bincount(minlength=E)
+
+ # This calculates all pairs of vertices which are opposite to the same edge.
+ vert_edge_pair_idx = _C.mesh_normal_consistency_find_verts(edge_num.cpu()).to(
+ edge_num.device
+ )
+
+ if vert_edge_pair_idx.shape[0] == 0:
+ return torch.tensor(
+ [0.0], dtype=torch.float32, device=meshes.device, requires_grad=True
+ )
+
+ v0_idx = edges_packed[edge_idx, 0]
+ v0 = verts_packed[v0_idx]
+ v1_idx = edges_packed[edge_idx, 1]
+ v1 = verts_packed[v1_idx]
+
+ # two of the following cross products are zeros as they are cross product
+ # with either (v1-v0)x(v1-v0) or (v1-v0)x(v0-v0)
+ n_temp0 = (v1 - v0).cross(verts_packed[vert_idx[:, 0]] - v0, dim=1)
+ n_temp1 = (v1 - v0).cross(verts_packed[vert_idx[:, 1]] - v0, dim=1)
+ n_temp2 = (v1 - v0).cross(verts_packed[vert_idx[:, 2]] - v0, dim=1)
+ n = n_temp0 + n_temp1 + n_temp2
+ n0 = n[vert_edge_pair_idx[:, 0]]
+ n1 = -n[vert_edge_pair_idx[:, 1]]
+ loss = 1 - torch.cosine_similarity(n0, n1, dim=1)
+
+ verts_packed_to_mesh_idx = verts_packed_to_mesh_idx[vert_idx[:, 0]]
+ verts_packed_to_mesh_idx = verts_packed_to_mesh_idx[vert_edge_pair_idx[:, 0]]
+ num_normals = verts_packed_to_mesh_idx.bincount(minlength=N)
+ weights = 1.0 / num_normals[verts_packed_to_mesh_idx].float()
+
+ loss = loss * weights
+ return loss.sum() / N
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/point_mesh_distance.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/point_mesh_distance.py
new file mode 100644
index 0000000000000000000000000000000000000000..b30cd05e88544c2b255107bae6001c12fbfdf307
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/loss/point_mesh_distance.py
@@ -0,0 +1,398 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from pytorch3d import _C
+from pytorch3d.structures import Meshes, Pointclouds
+from torch.autograd import Function
+from torch.autograd.function import once_differentiable
+
+
+"""
+This file defines distances between meshes and pointclouds.
+The functions make use of the definition of a distance between a point and
+an edge segment or the distance of a point and a triangle (face).
+
+The exact mathematical formulations and implementations of these
+distances can be found in `csrc/utils/geometry_utils.cuh`.
+"""
+
+_DEFAULT_MIN_TRIANGLE_AREA: float = 5e-3
+
+
+# PointFaceDistance
+class _PointFaceDistance(Function):
+ """
+ Torch autograd Function wrapper PointFaceDistance Cuda implementation
+ """
+
+ @staticmethod
+ def forward(
+ ctx,
+ points,
+ points_first_idx,
+ tris,
+ tris_first_idx,
+ max_points,
+ min_triangle_area=_DEFAULT_MIN_TRIANGLE_AREA,
+ ):
+ """
+ Args:
+ ctx: Context object used to calculate gradients.
+ points: FloatTensor of shape `(P, 3)`
+ points_first_idx: LongTensor of shape `(N,)` indicating the first point
+ index in each example in the batch
+ tris: FloatTensor of shape `(T, 3, 3)` of triangular faces. The `t`-th
+ triangular face is spanned by `(tris[t, 0], tris[t, 1], tris[t, 2])`
+ tris_first_idx: LongTensor of shape `(N,)` indicating the first face
+ index in each example in the batch
+ max_points: Scalar equal to maximum number of points in the batch
+ min_triangle_area: (float, defaulted) Triangles of area less than this
+ will be treated as points/lines.
+ Returns:
+ dists: FloatTensor of shape `(P,)`, where `dists[p]` is the squared
+ euclidean distance of `p`-th point to the closest triangular face
+ in the corresponding example in the batch
+ idxs: LongTensor of shape `(P,)` indicating the closest triangular face
+ in the corresponding example in the batch.
+
+ `dists[p]` is
+ `d(points[p], tris[idxs[p], 0], tris[idxs[p], 1], tris[idxs[p], 2])`
+ where `d(u, v0, v1, v2)` is the distance of point `u` from the triangular
+ face `(v0, v1, v2)`
+
+ """
+ dists, idxs = _C.point_face_dist_forward(
+ points,
+ points_first_idx,
+ tris,
+ tris_first_idx,
+ max_points,
+ min_triangle_area,
+ )
+ ctx.save_for_backward(points, tris, idxs)
+ ctx.min_triangle_area = min_triangle_area
+ return dists
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_dists):
+ grad_dists = grad_dists.contiguous()
+ points, tris, idxs = ctx.saved_tensors
+ min_triangle_area = ctx.min_triangle_area
+ grad_points, grad_tris = _C.point_face_dist_backward(
+ points, tris, idxs, grad_dists, min_triangle_area
+ )
+ return grad_points, None, grad_tris, None, None, None
+
+
+point_face_distance = _PointFaceDistance.apply
+
+
+# FacePointDistance
+class _FacePointDistance(Function):
+ """
+ Torch autograd Function wrapper FacePointDistance Cuda implementation
+ """
+
+ @staticmethod
+ def forward(
+ ctx,
+ points,
+ points_first_idx,
+ tris,
+ tris_first_idx,
+ max_tris,
+ min_triangle_area=_DEFAULT_MIN_TRIANGLE_AREA,
+ ):
+ """
+ Args:
+ ctx: Context object used to calculate gradients.
+ points: FloatTensor of shape `(P, 3)`
+ points_first_idx: LongTensor of shape `(N,)` indicating the first point
+ index in each example in the batch
+ tris: FloatTensor of shape `(T, 3, 3)` of triangular faces. The `t`-th
+ triangular face is spanned by `(tris[t, 0], tris[t, 1], tris[t, 2])`
+ tris_first_idx: LongTensor of shape `(N,)` indicating the first face
+ index in each example in the batch
+ max_tris: Scalar equal to maximum number of faces in the batch
+ min_triangle_area: (float, defaulted) Triangles of area less than this
+ will be treated as points/lines.
+ Returns:
+ dists: FloatTensor of shape `(T,)`, where `dists[t]` is the squared
+ euclidean distance of `t`-th triangular face to the closest point in the
+ corresponding example in the batch
+ idxs: LongTensor of shape `(T,)` indicating the closest point in the
+ corresponding example in the batch.
+
+ `dists[t] = d(points[idxs[t]], tris[t, 0], tris[t, 1], tris[t, 2])`,
+ where `d(u, v0, v1, v2)` is the distance of point `u` from the triangular
+ face `(v0, v1, v2)`.
+ """
+ dists, idxs = _C.face_point_dist_forward(
+ points, points_first_idx, tris, tris_first_idx, max_tris, min_triangle_area
+ )
+ ctx.save_for_backward(points, tris, idxs)
+ ctx.min_triangle_area = min_triangle_area
+ return dists
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_dists):
+ grad_dists = grad_dists.contiguous()
+ points, tris, idxs = ctx.saved_tensors
+ min_triangle_area = ctx.min_triangle_area
+ grad_points, grad_tris = _C.face_point_dist_backward(
+ points, tris, idxs, grad_dists, min_triangle_area
+ )
+ return grad_points, None, grad_tris, None, None, None
+
+
+face_point_distance = _FacePointDistance.apply
+
+
+# PointEdgeDistance
+class _PointEdgeDistance(Function):
+ """
+ Torch autograd Function wrapper PointEdgeDistance Cuda implementation
+ """
+
+ @staticmethod
+ def forward(ctx, points, points_first_idx, segms, segms_first_idx, max_points):
+ """
+ Args:
+ ctx: Context object used to calculate gradients.
+ points: FloatTensor of shape `(P, 3)`
+ points_first_idx: LongTensor of shape `(N,)` indicating the first point
+ index for each example in the mesh
+ segms: FloatTensor of shape `(S, 2, 3)` of edge segments. The `s`-th
+ edge segment is spanned by `(segms[s, 0], segms[s, 1])`
+ segms_first_idx: LongTensor of shape `(N,)` indicating the first edge
+ index for each example in the mesh
+ max_points: Scalar equal to maximum number of points in the batch
+ Returns:
+ dists: FloatTensor of shape `(P,)`, where `dists[p]` is the squared
+ euclidean distance of `p`-th point to the closest edge in the
+ corresponding example in the batch
+ idxs: LongTensor of shape `(P,)` indicating the closest edge in the
+ corresponding example in the batch.
+
+ `dists[p] = d(points[p], segms[idxs[p], 0], segms[idxs[p], 1])`,
+ where `d(u, v0, v1)` is the distance of point `u` from the edge segment
+ spanned by `(v0, v1)`.
+ """
+ dists, idxs = _C.point_edge_dist_forward(
+ points, points_first_idx, segms, segms_first_idx, max_points
+ )
+ ctx.save_for_backward(points, segms, idxs)
+ return dists
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_dists):
+ grad_dists = grad_dists.contiguous()
+ points, segms, idxs = ctx.saved_tensors
+ grad_points, grad_segms = _C.point_edge_dist_backward(
+ points, segms, idxs, grad_dists
+ )
+ return grad_points, None, grad_segms, None, None
+
+
+point_edge_distance = _PointEdgeDistance.apply
+
+
+# EdgePointDistance
+class _EdgePointDistance(Function):
+ """
+ Torch autograd Function wrapper EdgePointDistance Cuda implementation
+ """
+
+ @staticmethod
+ def forward(ctx, points, points_first_idx, segms, segms_first_idx, max_segms):
+ """
+ Args:
+ ctx: Context object used to calculate gradients.
+ points: FloatTensor of shape `(P, 3)`
+ points_first_idx: LongTensor of shape `(N,)` indicating the first point
+ index for each example in the mesh
+ segms: FloatTensor of shape `(S, 2, 3)` of edge segments. The `s`-th
+ edge segment is spanned by `(segms[s, 0], segms[s, 1])`
+ segms_first_idx: LongTensor of shape `(N,)` indicating the first edge
+ index for each example in the mesh
+ max_segms: Scalar equal to maximum number of edges in the batch
+ Returns:
+ dists: FloatTensor of shape `(S,)`, where `dists[s]` is the squared
+ euclidean distance of `s`-th edge to the closest point in the
+ corresponding example in the batch
+ idxs: LongTensor of shape `(S,)` indicating the closest point in the
+ corresponding example in the batch.
+
+ `dists[s] = d(points[idxs[s]], edges[s, 0], edges[s, 1])`,
+ where `d(u, v0, v1)` is the distance of point `u` from the segment
+ spanned by `(v0, v1)`.
+ """
+ dists, idxs = _C.edge_point_dist_forward(
+ points, points_first_idx, segms, segms_first_idx, max_segms
+ )
+ ctx.save_for_backward(points, segms, idxs)
+ return dists
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_dists):
+ grad_dists = grad_dists.contiguous()
+ points, segms, idxs = ctx.saved_tensors
+ grad_points, grad_segms = _C.edge_point_dist_backward(
+ points, segms, idxs, grad_dists
+ )
+ return grad_points, None, grad_segms, None, None
+
+
+edge_point_distance = _EdgePointDistance.apply
+
+
+def point_mesh_edge_distance(meshes: Meshes, pcls: Pointclouds):
+ """
+ Computes the distance between a pointcloud and a mesh within a batch.
+ Given a pair `(mesh, pcl)` in the batch, we define the distance to be the
+ sum of two distances, namely `point_edge(mesh, pcl) + edge_point(mesh, pcl)`
+
+ `point_edge(mesh, pcl)`: Computes the squared distance of each point p in pcl
+ to the closest edge segment in mesh and averages across all points in pcl
+ `edge_point(mesh, pcl)`: Computes the squared distance of each edge segment in mesh
+ to the closest point in pcl and averages across all edges in mesh.
+
+ The above distance functions are applied for all `(mesh, pcl)` pairs in the batch
+ and then averaged across the batch.
+
+ Args:
+ meshes: A Meshes data structure containing N meshes
+ pcls: A Pointclouds data structure containing N pointclouds
+
+ Returns:
+ loss: The `point_edge(mesh, pcl) + edge_point(mesh, pcl)` distance
+ between all `(mesh, pcl)` in a batch averaged across the batch.
+ """
+ if len(meshes) != len(pcls):
+ raise ValueError("meshes and pointclouds must be equal sized batches")
+ N = len(meshes)
+
+ # packed representation for pointclouds
+ points = pcls.points_packed() # (P, 3)
+ points_first_idx = pcls.cloud_to_packed_first_idx()
+ max_points = pcls.num_points_per_cloud().max().item()
+
+ # packed representation for edges
+ verts_packed = meshes.verts_packed()
+ edges_packed = meshes.edges_packed()
+ segms = verts_packed[edges_packed] # (S, 2, 3)
+ segms_first_idx = meshes.mesh_to_edges_packed_first_idx()
+ max_segms = meshes.num_edges_per_mesh().max().item()
+
+ # point to edge distance: shape (P,)
+ point_to_edge = point_edge_distance(
+ points, points_first_idx, segms, segms_first_idx, max_points
+ )
+
+ # weight each example by the inverse of number of points in the example
+ point_to_cloud_idx = pcls.packed_to_cloud_idx() # (sum(P_i), )
+ num_points_per_cloud = pcls.num_points_per_cloud() # (N,)
+ weights_p = num_points_per_cloud.gather(0, point_to_cloud_idx)
+ # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
+ weights_p = 1.0 / weights_p.float()
+ point_to_edge = point_to_edge * weights_p
+ point_dist = point_to_edge.sum() / N
+
+ # edge to edge distance: shape (S,)
+ edge_to_point = edge_point_distance(
+ points, points_first_idx, segms, segms_first_idx, max_segms
+ )
+
+ # weight each example by the inverse of number of edges in the example
+ segm_to_mesh_idx = meshes.edges_packed_to_mesh_idx() # (sum(S_n),)
+ num_segms_per_mesh = meshes.num_edges_per_mesh() # (N,)
+ weights_s = num_segms_per_mesh.gather(0, segm_to_mesh_idx)
+ weights_s = 1.0 / weights_s.float()
+ edge_to_point = edge_to_point * weights_s
+ edge_dist = edge_to_point.sum() / N
+
+ return point_dist + edge_dist
+
+
+def point_mesh_face_distance(
+ meshes: Meshes,
+ pcls: Pointclouds,
+ min_triangle_area: float = _DEFAULT_MIN_TRIANGLE_AREA,
+):
+ """
+ Computes the distance between a pointcloud and a mesh within a batch.
+ Given a pair `(mesh, pcl)` in the batch, we define the distance to be the
+ sum of two distances, namely `point_face(mesh, pcl) + face_point(mesh, pcl)`
+
+ `point_face(mesh, pcl)`: Computes the squared distance of each point p in pcl
+ to the closest triangular face in mesh and averages across all points in pcl
+ `face_point(mesh, pcl)`: Computes the squared distance of each triangular face in
+ mesh to the closest point in pcl and averages across all faces in mesh.
+
+ The above distance functions are applied for all `(mesh, pcl)` pairs in the batch
+ and then averaged across the batch.
+
+ Args:
+ meshes: A Meshes data structure containing N meshes
+ pcls: A Pointclouds data structure containing N pointclouds
+ min_triangle_area: (float, defaulted) Triangles of area less than this
+ will be treated as points/lines.
+
+ Returns:
+ loss: The `point_face(mesh, pcl) + face_point(mesh, pcl)` distance
+ between all `(mesh, pcl)` in a batch averaged across the batch.
+ """
+
+ if len(meshes) != len(pcls):
+ raise ValueError("meshes and pointclouds must be equal sized batches")
+ N = len(meshes)
+
+ # packed representation for pointclouds
+ points = pcls.points_packed() # (P, 3)
+ points_first_idx = pcls.cloud_to_packed_first_idx()
+ max_points = pcls.num_points_per_cloud().max().item()
+
+ # packed representation for faces
+ verts_packed = meshes.verts_packed()
+ faces_packed = meshes.faces_packed()
+ tris = verts_packed[faces_packed] # (T, 3, 3)
+ tris_first_idx = meshes.mesh_to_faces_packed_first_idx()
+ max_tris = meshes.num_faces_per_mesh().max().item()
+
+ # point to face distance: shape (P,)
+ point_to_face = point_face_distance(
+ points, points_first_idx, tris, tris_first_idx, max_points, min_triangle_area
+ )
+
+ # weight each example by the inverse of number of points in the example
+ point_to_cloud_idx = pcls.packed_to_cloud_idx() # (sum(P_i),)
+ num_points_per_cloud = pcls.num_points_per_cloud() # (N,)
+ weights_p = num_points_per_cloud.gather(0, point_to_cloud_idx)
+ # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`.
+ weights_p = 1.0 / weights_p.float()
+ point_to_face = point_to_face * weights_p
+ point_dist = point_to_face.sum() / N
+
+ # face to point distance: shape (T,)
+ face_to_point = face_point_distance(
+ points, points_first_idx, tris, tris_first_idx, max_tris, min_triangle_area
+ )
+
+ # weight each example by the inverse of number of faces in the example
+ tri_to_mesh_idx = meshes.faces_packed_to_mesh_idx() # (sum(T_n),)
+ num_tris_per_mesh = meshes.num_faces_per_mesh() # (N, )
+ weights_t = num_tris_per_mesh.gather(0, tri_to_mesh_idx)
+ weights_t = 1.0 / weights_t.float()
+ face_to_point = face_to_point * weights_t
+ face_dist = face_to_point.sum() / N
+
+ return point_dist + face_dist
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/__pycache__/cameras.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/__pycache__/cameras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6913099a8d49bd0465fb8716da5ab70624d86840
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/__pycache__/cameras.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/__init__.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e654ca67331ee11f79c66973136b592549a3c4ad
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/__init__.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/harmonic_embedding.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/harmonic_embedding.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f30c268a322a44ab44dd9c5772072bbd27601c0
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/harmonic_embedding.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raymarching.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raymarching.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da83142709f5a8a713a5fa34dd950fc8563fec91
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raymarching.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raysampling.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raysampling.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..138582b6ef9c130fb44e7cc0975e7cb91121f7ed
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/raysampling.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/renderer.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/renderer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a3bbb3bcc010cc047123564a08d730c88c1816a
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/renderer.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/utils.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e0803af38bd62d4bfc22d422770294864a1b032
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/__pycache__/utils.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/raymarching.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/raymarching.py
new file mode 100644
index 0000000000000000000000000000000000000000..60eae7b765948bfc138fed6e4d8a11b89aa1f54c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/raymarching.py
@@ -0,0 +1,233 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+import warnings
+from typing import Optional, Tuple, Union
+
+import torch
+
+
+class EmissionAbsorptionRaymarcher(torch.nn.Module):
+ """
+ Raymarch using the Emission-Absorption (EA) algorithm.
+
+ The algorithm independently renders each ray by analyzing density and
+ feature values sampled at (typically uniformly) spaced 3D locations along
+ each ray. The density values `rays_densities` are of shape
+ `(..., n_points_per_ray)`, their values should range between [0, 1], and
+ represent the opaqueness of each point (the higher the less transparent).
+ The feature values `rays_features` of shape
+ `(..., n_points_per_ray, feature_dim)` represent the content of the
+ point that is supposed to be rendered in case the given point is opaque
+ (i.e. its density -> 1.0).
+
+ EA first utilizes `rays_densities` to compute the absorption function
+ along each ray as follows::
+
+ absorption = cumprod(1 - rays_densities, dim=-1)
+
+ The value of absorption at position `absorption[..., k]` specifies
+ how much light has reached `k`-th point along a ray since starting
+ its trajectory at `k=0`-th point.
+
+ Each ray is then rendered into a tensor `features` of shape `(..., feature_dim)`
+ by taking a weighed combination of per-ray features `rays_features` as follows::
+
+ weights = absorption * rays_densities
+ features = (rays_features * weights).sum(dim=-2)
+
+ Where `weights` denote a function that has a strong peak around the location
+ of the first surface point that a given ray passes through.
+
+ Note that for a perfectly bounded volume (with a strictly binary density),
+ the `weights = cumprod(1 - rays_densities, dim=-1) * rays_densities`
+ function would yield 0 everywhere. In order to prevent this,
+ the result of the cumulative product is shifted `self.surface_thickness`
+ elements along the ray direction.
+ """
+
+ def __init__(self, surface_thickness: int = 1) -> None:
+ """
+ Args:
+ surface_thickness: Denotes the overlap between the absorption
+ function and the density function.
+ """
+ super().__init__()
+ self.surface_thickness = surface_thickness
+
+ def forward(
+ self,
+ rays_densities: torch.Tensor,
+ rays_features: torch.Tensor,
+ eps: float = 1e-10,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Args:
+ rays_densities: Per-ray density values represented with a tensor
+ of shape `(..., n_points_per_ray, 1)` whose values range in [0, 1].
+ rays_features: Per-ray feature values represented with a tensor
+ of shape `(..., n_points_per_ray, feature_dim)`.
+ eps: A lower bound added to `rays_densities` before computing
+ the absorption function (cumprod of `1-rays_densities` along
+ each ray). This prevents the cumprod to yield exact 0
+ which would inhibit any gradient-based learning.
+
+ Returns:
+ features_opacities: A tensor of shape `(..., feature_dim+1)`
+ that concatenates two tensors along the last dimension:
+ 1) features: A tensor of per-ray renders
+ of shape `(..., feature_dim)`.
+ 2) opacities: A tensor of per-ray opacity values
+ of shape `(..., 1)`. Its values range between [0, 1] and
+ denote the total amount of light that has been absorbed
+ for each ray. E.g. a value of 0 corresponds to the ray
+ completely passing through a volume. Please refer to the
+ `AbsorptionOnlyRaymarcher` documentation for the
+ explanation of the algorithm that computes `opacities`.
+ """
+ _check_raymarcher_inputs(
+ rays_densities,
+ rays_features,
+ None,
+ z_can_be_none=True,
+ features_can_be_none=False,
+ density_1d=True,
+ )
+ _check_density_bounds(rays_densities)
+ rays_densities = rays_densities[..., 0]
+ absorption = _shifted_cumprod(
+ (1.0 + eps) - rays_densities, shift=self.surface_thickness
+ )
+ weights = rays_densities * absorption
+ features = (weights[..., None] * rays_features).sum(dim=-2)
+ opacities = 1.0 - torch.prod(1.0 - rays_densities, dim=-1, keepdim=True)
+
+ return torch.cat((features, opacities), dim=-1)
+
+
+class AbsorptionOnlyRaymarcher(torch.nn.Module):
+ """
+ Raymarch using the Absorption-Only (AO) algorithm.
+
+ The algorithm independently renders each ray by analyzing density and
+ feature values sampled at (typically uniformly) spaced 3D locations along
+ each ray. The density values `rays_densities` are of shape
+ `(..., n_points_per_ray, 1)`, their values should range between [0, 1], and
+ represent the opaqueness of each point (the higher the less transparent).
+ The algorithm only measures the total amount of light absorbed along each ray
+ and, besides outputting per-ray `opacity` values of shape `(...,)`,
+ does not produce any feature renderings.
+
+ The algorithm simply computes `total_transmission = prod(1 - rays_densities)`
+ of shape `(..., 1)` which, for each ray, measures the total amount of light
+ that passed through the volume.
+ It then returns `opacities = 1 - total_transmission`.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+
+ def forward(
+ self, rays_densities: torch.Tensor, **kwargs
+ ) -> Union[None, torch.Tensor]:
+ """
+ Args:
+ rays_densities: Per-ray density values represented with a tensor
+ of shape `(..., n_points_per_ray)` whose values range in [0, 1].
+
+ Returns:
+ opacities: A tensor of per-ray opacity values of shape `(..., 1)`.
+ Its values range between [0, 1] and denote the total amount
+ of light that has been absorbed for each ray. E.g. a value
+ of 0 corresponds to the ray completely passing through a volume.
+ """
+
+ _check_raymarcher_inputs(
+ rays_densities,
+ None,
+ None,
+ features_can_be_none=True,
+ z_can_be_none=True,
+ density_1d=True,
+ )
+ rays_densities = rays_densities[..., 0]
+ _check_density_bounds(rays_densities)
+ total_transmission = torch.prod(1 - rays_densities, dim=-1, keepdim=True)
+ opacities = 1.0 - total_transmission
+ return opacities
+
+
+def _shifted_cumprod(x, shift: int = 1):
+ """
+ Computes `torch.cumprod(x, dim=-1)` and prepends `shift` number of
+ ones and removes `shift` trailing elements to/from the last dimension
+ of the result.
+ """
+ x_cumprod = torch.cumprod(x, dim=-1)
+ x_cumprod_shift = torch.cat(
+ [torch.ones_like(x_cumprod[..., :shift]), x_cumprod[..., :-shift]], dim=-1
+ )
+ return x_cumprod_shift
+
+
+def _check_density_bounds(
+ rays_densities: torch.Tensor, bounds: Tuple[float, float] = (0.0, 1.0)
+) -> None:
+ """
+ Checks whether the elements of `rays_densities` range within `bounds`.
+ If not issues a warning.
+ """
+ with torch.no_grad():
+ if (rays_densities.max() > bounds[1]) or (rays_densities.min() < bounds[0]):
+ warnings.warn(
+ "One or more elements of rays_densities are outside of valid"
+ + f"range {str(bounds)}"
+ )
+
+
+def _check_raymarcher_inputs(
+ rays_densities: torch.Tensor,
+ rays_features: Optional[torch.Tensor],
+ rays_z: Optional[torch.Tensor],
+ features_can_be_none: bool = False,
+ z_can_be_none: bool = False,
+ density_1d: bool = True,
+) -> None:
+ """
+ Checks the validity of the inputs to raymarching algorithms.
+ """
+ if not torch.is_tensor(rays_densities):
+ raise ValueError("rays_densities has to be an instance of torch.Tensor.")
+
+ if not z_can_be_none and not torch.is_tensor(rays_z):
+ raise ValueError("rays_z has to be an instance of torch.Tensor.")
+
+ if not features_can_be_none and not torch.is_tensor(rays_features):
+ raise ValueError("rays_features has to be an instance of torch.Tensor.")
+
+ if rays_densities.ndim < 1:
+ raise ValueError("rays_densities have to have at least one dimension.")
+
+ if density_1d and rays_densities.shape[-1] != 1:
+ raise ValueError(
+ "The size of the last dimension of rays_densities has to be one."
+ + f" Got shape {rays_densities.shape}."
+ )
+
+ rays_shape = rays_densities.shape[:-1]
+
+ # pyre-fixme[16]: `Optional` has no attribute `shape`.
+ if not z_can_be_none and rays_z.shape != rays_shape:
+ raise ValueError("rays_z have to be of the same shape as rays_densities.")
+
+ if not features_can_be_none and rays_features.shape[:-1] != rays_shape:
+ raise ValueError(
+ "The first to previous to last dimensions of rays_features"
+ " have to be the same as all dimensions of rays_densities."
+ )
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/renderer.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/renderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..963f7d07ef1c8f7ba0ed274e79c631f3f349962d
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/implicit/renderer.py
@@ -0,0 +1,415 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from typing import Callable, Tuple, Union
+
+import torch
+
+from ...ops.utils import eyes
+from ...structures import Volumes
+from ...transforms import Transform3d
+from ..cameras import CamerasBase
+from .raysampling import HeterogeneousRayBundle, RayBundle
+from .utils import _validate_ray_bundle_variables, ray_bundle_variables_to_ray_points
+
+
+# The implicit renderer class should be initialized with a
+# function for raysampling and a function for raymarching.
+
+# During the forward pass:
+# 1) The raysampler:
+# - samples rays from input cameras
+# - transforms the rays to world coordinates
+# 2) The volumetric_function (which is a callable argument of the forward pass)
+# evaluates ray_densities and ray_features at the sampled ray-points.
+# 3) The raymarcher takes ray_densities and ray_features and uses a raymarching
+# algorithm to render each ray.
+
+
+class ImplicitRenderer(torch.nn.Module):
+ """
+ A class for rendering a batch of implicit surfaces. The class should
+ be initialized with a raysampler and raymarcher class which both have
+ to be a `Callable`.
+
+ VOLUMETRIC_FUNCTION
+
+ The `forward` function of the renderer accepts as input the rendering cameras
+ as well as the `volumetric_function` `Callable`, which defines a field of opacity
+ and feature vectors over the 3D domain of the scene.
+
+ A standard `volumetric_function` has the following signature::
+
+ def volumetric_function(
+ ray_bundle: Union[RayBundle, HeterogeneousRayBundle],
+ **kwargs,
+ ) -> Tuple[torch.Tensor, torch.Tensor]
+
+ With the following arguments:
+ `ray_bundle`: A RayBundle or HeterogeneousRayBundle object
+ containing the following variables:
+
+ `origins`: A tensor of shape `(minibatch, ..., 3)` denoting
+ the origins of the rendering rays.
+ `directions`: A tensor of shape `(minibatch, ..., 3)`
+ containing the direction vectors of rendering rays.
+ `lengths`: A tensor of shape
+ `(minibatch, ..., num_points_per_ray)`containing the
+ lengths at which the ray points are sampled.
+ `xys`: A tensor of shape
+ `(minibatch, ..., 2)` containing the
+ xy locations of each ray's pixel in the screen space.
+ Calling `volumetric_function` then returns the following:
+ `rays_densities`: A tensor of shape
+ `(minibatch, ..., num_points_per_ray, opacity_dim)` containing
+ the an opacity vector for each ray point.
+ `rays_features`: A tensor of shape
+ `(minibatch, ..., num_points_per_ray, feature_dim)` containing
+ the an feature vector for each ray point.
+
+ Note that, in order to increase flexibility of the API, we allow multiple
+ other arguments to enter the volumetric function via additional
+ (optional) keyword arguments `**kwargs`.
+ A typical use-case is passing a `CamerasBase` object as an additional
+ keyword argument, which can allow the volumetric function to adjust its
+ outputs based on the directions of the projection rays.
+
+ Example:
+ A simple volumetric function of a 0-centered
+ RGB sphere with a unit diameter is defined as follows::
+
+ def volumetric_function(
+ ray_bundle: Union[RayBundle, HeterogeneousRayBundle],
+ **kwargs,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+
+ # first convert the ray origins, directions and lengths
+ # to 3D ray point locations in world coords
+ rays_points_world = ray_bundle_to_ray_points(ray_bundle)
+
+ # set the densities as an inverse sigmoid of the
+ # ray point distance from the sphere centroid
+ rays_densities = torch.sigmoid(
+ -100.0 * rays_points_world.norm(dim=-1, keepdim=True)
+ )
+
+ # set the ray features to RGB colors proportional
+ # to the 3D location of the projection of ray points
+ # on the sphere surface
+ rays_features = torch.nn.functional.normalize(
+ rays_points_world, dim=-1
+ ) * 0.5 + 0.5
+
+ return rays_densities, rays_features
+
+ """
+
+ def __init__(self, raysampler: Callable, raymarcher: Callable) -> None:
+ """
+ Args:
+ raysampler: A `Callable` that takes as input scene cameras
+ (an instance of `CamerasBase`) and returns a
+ RayBundle or HeterogeneousRayBundle, that
+ describes the rays emitted from the cameras.
+ raymarcher: A `Callable` that receives the response of the
+ `volumetric_function` (an input to `self.forward`) evaluated
+ along the sampled rays, and renders the rays with a
+ ray-marching algorithm.
+ """
+ super().__init__()
+
+ if not callable(raysampler):
+ raise ValueError('"raysampler" has to be a "Callable" object.')
+ if not callable(raymarcher):
+ raise ValueError('"raymarcher" has to be a "Callable" object.')
+
+ self.raysampler = raysampler
+ self.raymarcher = raymarcher
+
+ def forward(
+ self, cameras: CamerasBase, volumetric_function: Callable, **kwargs
+ ) -> Tuple[torch.Tensor, Union[RayBundle, HeterogeneousRayBundle]]:
+ """
+ Render a batch of images using a volumetric function
+ represented as a callable (e.g. a Pytorch module).
+
+ Args:
+ cameras: A batch of cameras that render the scene. A `self.raysampler`
+ takes the cameras as input and samples rays that pass through the
+ domain of the volumetric function.
+ volumetric_function: A `Callable` that accepts the parametrizations
+ of the rendering rays and returns the densities and features
+ at the respective 3D of the rendering rays. Please refer to
+ the main class documentation for details.
+
+ Returns:
+ images: A tensor of shape `(minibatch, ..., feature_dim + opacity_dim)`
+ containing the result of the rendering.
+ ray_bundle: A `Union[RayBundle, HeterogeneousRayBundle]` containing
+ the parametrizations of the sampled rendering rays.
+ """
+
+ if not callable(volumetric_function):
+ raise ValueError('"volumetric_function" has to be a "Callable" object.')
+
+ # first call the ray sampler that returns the RayBundle or HeterogeneousRayBundle
+ # parametrizing the rendering rays.
+ ray_bundle = self.raysampler(
+ cameras=cameras, volumetric_function=volumetric_function, **kwargs
+ )
+ # ray_bundle.origins - minibatch x ... x 3
+ # ray_bundle.directions - minibatch x ... x 3
+ # ray_bundle.lengths - minibatch x ... x n_pts_per_ray
+ # ray_bundle.xys - minibatch x ... x 2
+
+ # given sampled rays, call the volumetric function that
+ # evaluates the densities and features at the locations of the
+ # ray points
+ # pyre-fixme[23]: Unable to unpack `object` into 2 values.
+ rays_densities, rays_features = volumetric_function(
+ ray_bundle=ray_bundle, cameras=cameras, **kwargs
+ )
+ # ray_densities - minibatch x ... x n_pts_per_ray x density_dim
+ # ray_features - minibatch x ... x n_pts_per_ray x feature_dim
+
+ # finally, march along the sampled rays to obtain the renders
+ images = self.raymarcher(
+ rays_densities=rays_densities,
+ rays_features=rays_features,
+ ray_bundle=ray_bundle,
+ **kwargs,
+ )
+ # images - minibatch x ... x (feature_dim + opacity_dim)
+
+ return images, ray_bundle
+
+
+# The volume renderer class should be initialized with a
+# function for raysampling and a function for raymarching.
+
+# During the forward pass:
+# 1) The raysampler:
+# - samples rays from input cameras
+# - transforms the rays to world coordinates
+# 2) The scene volumes (which are an argument of the forward function)
+# are then sampled at the locations of the ray-points to generate
+# ray_densities and ray_features.
+# 3) The raymarcher takes ray_densities and ray_features and uses a raymarching
+# algorithm to render each ray.
+
+
+class VolumeRenderer(torch.nn.Module):
+ """
+ A class for rendering a batch of Volumes. The class should
+ be initialized with a raysampler and a raymarcher class which both have
+ to be a `Callable`.
+ """
+
+ def __init__(
+ self, raysampler: Callable, raymarcher: Callable, sample_mode: str = "bilinear"
+ ) -> None:
+ """
+ Args:
+ raysampler: A `Callable` that takes as input scene cameras
+ (an instance of `CamerasBase`) and returns a
+ `Union[RayBundle, HeterogeneousRayBundle],` that
+ describes the rays emitted from the cameras.
+ raymarcher: A `Callable` that receives the `volumes`
+ (an instance of `Volumes` input to `self.forward`)
+ sampled at the ray-points, and renders the rays with a
+ ray-marching algorithm.
+ sample_mode: Defines the algorithm used to sample the volumetric
+ voxel grid. Can be either "bilinear" or "nearest".
+ """
+ super().__init__()
+
+ self.renderer = ImplicitRenderer(raysampler, raymarcher)
+ self._sample_mode = sample_mode
+
+ def forward(
+ self, cameras: CamerasBase, volumes: Volumes, **kwargs
+ ) -> Tuple[torch.Tensor, Union[RayBundle, HeterogeneousRayBundle]]:
+ """
+ Render a batch of images using raymarching over rays cast through
+ input `Volumes`.
+
+ Args:
+ cameras: A batch of cameras that render the scene. A `self.raysampler`
+ takes the cameras as input and samples rays that pass through the
+ domain of the volumetric function.
+ volumes: An instance of the `Volumes` class representing a
+ batch of volumes that are being rendered.
+
+ Returns:
+ images: A tensor of shape `(minibatch, ..., (feature_dim + opacity_dim)`
+ containing the result of the rendering.
+ ray_bundle: A `RayBundle` or `HeterogeneousRayBundle` containing the
+ parametrizations of the sampled rendering rays.
+ """
+ volumetric_function = VolumeSampler(volumes, sample_mode=self._sample_mode)
+ return self.renderer(
+ cameras=cameras, volumetric_function=volumetric_function, **kwargs
+ )
+
+
+class VolumeSampler(torch.nn.Module):
+ """
+ A module to sample a batch of volumes `Volumes`
+ at 3D points sampled along projection rays.
+ """
+
+ def __init__(
+ self,
+ volumes: Volumes,
+ sample_mode: str = "bilinear",
+ padding_mode: str = "zeros",
+ ) -> None:
+ """
+ Args:
+ volumes: An instance of the `Volumes` class representing a
+ batch of volumes that are being rendered.
+ sample_mode: Defines the algorithm used to sample the volumetric
+ voxel grid. Can be either "bilinear" or "nearest".
+ padding_mode: How to handle values outside of the volume.
+ One of: zeros, border, reflection
+ See torch.nn.functional.grid_sample for more information.
+ """
+ super().__init__()
+ if not isinstance(volumes, Volumes):
+ raise ValueError("'volumes' have to be an instance of the 'Volumes' class.")
+ self._volumes = volumes
+ self._sample_mode = sample_mode
+ self._padding_mode = padding_mode
+
+ def _get_ray_directions_transform(self):
+ """
+ Compose the ray-directions transform by removing the translation component
+ from the volume global-to-local coords transform.
+ """
+ world2local = self._volumes.get_world_to_local_coords_transform().get_matrix()
+ directions_transform_matrix = eyes(
+ 4,
+ N=world2local.shape[0],
+ device=world2local.device,
+ dtype=world2local.dtype,
+ )
+ directions_transform_matrix[:, :3, :3] = world2local[:, :3, :3]
+ directions_transform = Transform3d(matrix=directions_transform_matrix)
+ return directions_transform
+
+ def forward(
+ self, ray_bundle: Union[RayBundle, HeterogeneousRayBundle], **kwargs
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Given an input ray parametrization, the forward function samples
+ `self._volumes` at the respective 3D ray-points.
+ Can also accept ImplicitronRayBundle as argument for ray_bundle.
+
+ Args:
+ ray_bundle: A RayBundle or HeterogeneousRayBundle object with the following fields:
+ rays_origins_world: A tensor of shape `(minibatch, ..., 3)` denoting the
+ origins of the sampling rays in world coords.
+ rays_directions_world: A tensor of shape `(minibatch, ..., 3)`
+ containing the direction vectors of sampling rays in world coords.
+ rays_lengths: A tensor of shape `(minibatch, ..., num_points_per_ray)`
+ containing the lengths at which the rays are sampled.
+
+ Returns:
+ rays_densities: A tensor of shape
+ `(minibatch, ..., num_points_per_ray, opacity_dim)` containing the
+ density vectors sampled from the volume at the locations of
+ the ray points.
+ rays_features: A tensor of shape
+ `(minibatch, ..., num_points_per_ray, feature_dim)` containing the
+ feature vectors sampled from the volume at the locations of
+ the ray points.
+ """
+
+ # take out the interesting parts of ray_bundle
+ rays_origins_world = ray_bundle.origins
+ rays_directions_world = ray_bundle.directions
+ rays_lengths = ray_bundle.lengths
+
+ # validate the inputs
+ _validate_ray_bundle_variables(
+ rays_origins_world, rays_directions_world, rays_lengths
+ )
+ if self._volumes.densities().shape[0] != rays_origins_world.shape[0]:
+ raise ValueError("Input volumes have to have the same batch size as rays.")
+
+ #########################################################
+ # 1) convert the origins/directions to the local coords #
+ #########################################################
+
+ # origins are mapped with the world_to_local transform of the volumes
+ rays_origins_local = self._volumes.world_to_local_coords(rays_origins_world)
+
+ # obtain the Transform3d object that transforms ray directions to local coords
+ directions_transform = self._get_ray_directions_transform()
+
+ # transform the directions to the local coords
+ rays_directions_local = directions_transform.transform_points(
+ rays_directions_world.view(rays_lengths.shape[0], -1, 3)
+ ).view(rays_directions_world.shape)
+
+ ############################
+ # 2) obtain the ray points #
+ ############################
+
+ # this op produces a fairly big tensor (minibatch, ..., n_samples_per_ray, 3)
+ rays_points_local = ray_bundle_variables_to_ray_points(
+ rays_origins_local, rays_directions_local, rays_lengths
+ )
+
+ ########################
+ # 3) sample the volume #
+ ########################
+
+ # generate the tensor for sampling
+ volumes_densities = self._volumes.densities()
+ dim_density = volumes_densities.shape[1]
+ volumes_features = self._volumes.features()
+
+ # reshape to a size which grid_sample likes
+ rays_points_local_flat = rays_points_local.view(
+ rays_points_local.shape[0], -1, 1, 1, 3
+ )
+
+ # run the grid sampler on the volumes densities
+ rays_densities = torch.nn.functional.grid_sample(
+ volumes_densities,
+ rays_points_local_flat,
+ mode=self._sample_mode,
+ padding_mode=self._padding_mode,
+ align_corners=self._volumes.get_align_corners(),
+ )
+
+ # permute the dimensions & reshape densities after sampling
+ rays_densities = rays_densities.permute(0, 2, 3, 4, 1).view(
+ *rays_points_local.shape[:-1], volumes_densities.shape[1]
+ )
+
+ # if features exist, run grid sampler again on the features densities
+ if volumes_features is None:
+ dim_feature = 0
+ _, rays_features = rays_densities.split([dim_density, dim_feature], dim=-1)
+ else:
+ rays_features = torch.nn.functional.grid_sample(
+ volumes_features,
+ rays_points_local_flat,
+ mode=self._sample_mode,
+ padding_mode=self._padding_mode,
+ align_corners=self._volumes.get_align_corners(),
+ )
+
+ # permute the dimensions & reshape features after sampling
+ rays_features = rays_features.permute(0, 2, 3, 4, 1).view(
+ *rays_points_local.shape[:-1], volumes_features.shape[1]
+ )
+
+ return rays_densities, rays_features
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..388a300907c62c84ff92e7aeba162ded76dbe9f9
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/__init__.py
@@ -0,0 +1,40 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+
+# If we can access EGL, import MeshRasterizerOpenGL.
+def _can_import_egl_and_pycuda():
+ import os
+ import warnings
+
+ try:
+ os.environ["PYOPENGL_PLATFORM"] = "egl"
+ import OpenGL.EGL
+ except (AttributeError, ImportError, ModuleNotFoundError):
+ warnings.warn(
+ "Can't import EGL, not importing MeshRasterizerOpenGL. This might happen if"
+ " your Python application imported OpenGL with a non-EGL backend before"
+ " importing PyTorch3D, or if you don't have pyopengl installed as part"
+ " of your Python distribution."
+ )
+ return False
+
+ try:
+ import pycuda.gl
+ except (ImportError, ImportError, ModuleNotFoundError):
+ warnings.warn("Can't import pycuda.gl, not importing MeshRasterizerOpenGL.")
+ return False
+
+ return True
+
+
+if _can_import_egl_and_pycuda():
+ from .opengl_utils import EGLContext, global_device_context_store
+ from .rasterizer_opengl import MeshRasterizerOpenGL
+
+__all__ = [k for k in globals().keys() if not k.startswith("_")]
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/opengl_utils.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/opengl_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8201b3076482def0c63eb0f48386614cf44f1a1e
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/opengl_utils.py
@@ -0,0 +1,450 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+# Utilities useful for OpenGL rendering.
+#
+# NOTE: This module MUST be imported before any other OpenGL modules in this Python
+# session, unless you set PYOPENGL_PLATFORM to egl *before* importing other modules.
+# Otherwise, the imports below will throw an error.
+#
+# This module (as well as rasterizer_opengl) will not be imported into pytorch3d if
+# you do not have pycuda.gl and pyopengl installed.
+
+import contextlib
+import ctypes
+import os
+import threading
+from typing import Any, Dict
+
+
+os.environ["PYOPENGL_PLATFORM"] = "egl"
+import OpenGL.EGL as egl # noqa
+
+import pycuda.driver as cuda # noqa
+from OpenGL._opaque import opaque_pointer_cls # noqa
+from OpenGL.raw.EGL._errors import EGLError # noqa
+
+# A few constants necessary to use EGL extensions, see links for details.
+
+# https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_platform_device.txt
+EGL_PLATFORM_DEVICE_EXT = 0x313F
+# https://www.khronos.org/registry/EGL/extensions/NV/EGL_NV_device_cuda.txt
+EGL_CUDA_DEVICE_NV = 0x323A
+
+
+# To use EGL extensions, we need to tell OpenGL about them. For details, see
+# https://developer.nvidia.com/blog/egl-eye-opengl-visualization-without-x-server/.
+# To avoid garbage collection of the protos, we'll store them in a module-global list.
+def _define_egl_extension(name: str, type):
+ if hasattr(egl, name):
+ return
+ addr = egl.eglGetProcAddress(name)
+ if addr is None:
+ raise RuntimeError(f"Cannot find EGL extension {name}.")
+ else:
+ proto = ctypes.CFUNCTYPE(type)
+ func = proto(addr)
+ setattr(egl, name, func)
+ return proto
+
+
+_protos = []
+_protos.append(_define_egl_extension("eglGetPlatformDisplayEXT", egl.EGLDisplay))
+_protos.append(_define_egl_extension("eglQueryDevicesEXT", egl.EGLBoolean))
+_protos.append(_define_egl_extension("eglQueryDeviceAttribEXT", egl.EGLBoolean))
+_protos.append(_define_egl_extension("eglQueryDisplayAttribEXT", egl.EGLBoolean))
+_protos.append(_define_egl_extension("eglQueryDeviceStringEXT", ctypes.c_char_p))
+
+if not hasattr(egl, "EGLDeviceEXT"):
+ egl.EGLDeviceEXT = opaque_pointer_cls("EGLDeviceEXT")
+
+
+def _egl_convert_to_int_array(egl_attributes):
+ """
+ Convert a Python dict of EGL attributes into an array of ints (some of which are
+ special EGL ints.
+
+ Args:
+ egl_attributes: A dict where keys are EGL attributes, and values are their vals.
+
+ Returns:
+ A c-list of length 2 * len(egl_attributes) + 1, of the form [key1, val1, ...,
+ keyN, valN, EGL_NONE]
+ """
+ attributes_list = sum(([k, v] for k, v in egl_attributes.items()), []) + [
+ egl.EGL_NONE
+ ]
+ return (egl.EGLint * len(attributes_list))(*attributes_list)
+
+
+def _get_cuda_device(requested_device_id: int):
+ """
+ Find an EGL device with a given CUDA device ID.
+
+ Args:
+ requested_device_id: The desired CUDA device ID, e.g. "1" for "cuda:1".
+
+ Returns:
+ EGL device with the desired CUDA ID.
+ """
+ num_devices = egl.EGLint()
+ if (
+ # pyre-ignore Undefined attribute [16]
+ not egl.eglQueryDevicesEXT(0, None, ctypes.pointer(num_devices))
+ or num_devices.value < 1
+ ):
+ raise RuntimeError("EGL requires a system that supports at least one device.")
+ devices = (egl.EGLDeviceEXT * num_devices.value)() # array of size num_devices
+ if (
+ # pyre-ignore Undefined attribute [16]
+ not egl.eglQueryDevicesEXT(
+ num_devices.value, devices, ctypes.pointer(num_devices)
+ )
+ or num_devices.value < 1
+ ):
+ raise RuntimeError("EGL sees no available devices.")
+ if len(devices) < requested_device_id + 1:
+ raise ValueError(
+ f"Device {requested_device_id} not available. Found only {len(devices)} devices."
+ )
+
+ # Iterate over all the EGL devices, and check if their CUDA ID matches the request.
+ for device in devices:
+ available_device_id = egl.EGLAttrib(ctypes.c_int(-1))
+ # pyre-ignore Undefined attribute [16]
+ egl.eglQueryDeviceAttribEXT(device, EGL_CUDA_DEVICE_NV, available_device_id)
+ if available_device_id.contents.value == requested_device_id:
+ return device
+ raise ValueError(
+ f"Found {len(devices)} CUDA devices, but none with CUDA id {requested_device_id}."
+ )
+
+
+def _get_egl_config(egl_dpy, surface_type):
+ """
+ Get an EGL config with reasonable settings (for use with MeshRasterizerOpenGL).
+
+ Args:
+ egl_dpy: An EGL display constant (int).
+ surface_type: An EGL surface_type int.
+
+ Returns:
+ An EGL config object.
+
+ Throws:
+ ValueError if the desired config is not available or invalid.
+ """
+ egl_config_dict = {
+ egl.EGL_RED_SIZE: 8,
+ egl.EGL_GREEN_SIZE: 8,
+ egl.EGL_BLUE_SIZE: 8,
+ egl.EGL_ALPHA_SIZE: 8,
+ egl.EGL_DEPTH_SIZE: 24,
+ egl.EGL_STENCIL_SIZE: egl.EGL_DONT_CARE,
+ egl.EGL_RENDERABLE_TYPE: egl.EGL_OPENGL_BIT,
+ egl.EGL_SURFACE_TYPE: surface_type,
+ }
+ egl_config_array = _egl_convert_to_int_array(egl_config_dict)
+ egl_config = egl.EGLConfig()
+ num_configs = egl.EGLint()
+ if (
+ not egl.eglChooseConfig(
+ egl_dpy,
+ egl_config_array,
+ ctypes.pointer(egl_config),
+ 1,
+ ctypes.pointer(num_configs),
+ )
+ or num_configs.value == 0
+ ):
+ raise ValueError("Invalid EGL config.")
+ return egl_config
+
+
+class EGLContext:
+ """
+ A class representing an EGL context. In short, EGL allows us to render OpenGL con-
+ tent in a headless mode, that is without an actual display to render to. This capa-
+ bility enables MeshRasterizerOpenGL to render on the GPU and then transfer the re-
+ sults to PyTorch3D.
+ """
+
+ def __init__(self, width: int, height: int, cuda_device_id: int = 0) -> None:
+ """
+ Args:
+ width: Width of the "display" to render to.
+ height: Height of the "display" to render to.
+ cuda_device_id: Device ID to render to, in the CUDA convention (note that
+ this might be different than EGL's device numbering).
+ """
+ # Lock used to prevent multiple threads from rendering on the same device
+ # at the same time, creating/destroying contexts at the same time, etc.
+ self.lock = threading.Lock()
+ self.cuda_device_id = cuda_device_id
+ self.device = _get_cuda_device(self.cuda_device_id)
+ self.width = width
+ self.height = height
+ self.dpy = egl.eglGetPlatformDisplayEXT(
+ EGL_PLATFORM_DEVICE_EXT, self.device, None
+ )
+ major, minor = egl.EGLint(), egl.EGLint()
+
+ # Initialize EGL components: the display, surface, and context
+ egl.eglInitialize(self.dpy, ctypes.pointer(major), ctypes.pointer(minor))
+
+ config = _get_egl_config(self.dpy, egl.EGL_PBUFFER_BIT)
+ pb_surf_attribs = _egl_convert_to_int_array(
+ {
+ egl.EGL_WIDTH: width,
+ egl.EGL_HEIGHT: height,
+ }
+ )
+ self.surface = egl.eglCreatePbufferSurface(self.dpy, config, pb_surf_attribs)
+ if self.surface == egl.EGL_NO_SURFACE:
+ raise RuntimeError("Failed to create an EGL surface.")
+
+ if not egl.eglBindAPI(egl.EGL_OPENGL_API):
+ raise RuntimeError("Failed to bind EGL to the OpenGL API.")
+ self.context = egl.eglCreateContext(self.dpy, config, egl.EGL_NO_CONTEXT, None)
+ if self.context == egl.EGL_NO_CONTEXT:
+ raise RuntimeError("Failed to create an EGL context.")
+
+ @contextlib.contextmanager
+ def active_and_locked(self):
+ """
+ A context manager used to make sure a given EGL context is only current in
+ a single thread at a single time. It is recommended to ALWAYS use EGL within
+ a `with context.active_and_locked():` context.
+
+ Throws:
+ EGLError when the context cannot be made current or make non-current.
+ """
+ self.lock.acquire()
+ egl.eglMakeCurrent(self.dpy, self.surface, self.surface, self.context)
+ try:
+ yield
+ finally:
+ egl.eglMakeCurrent(
+ self.dpy, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT
+ )
+ self.lock.release()
+
+ def get_context_info(self) -> Dict[str, Any]:
+ """
+ Return context info. Useful for debugging.
+
+ Returns:
+ A dict of keys and ints, representing the context's display, surface,
+ the context itself, and the current thread.
+ """
+ return {
+ "dpy": self.dpy,
+ "surface": self.surface,
+ "context": self.context,
+ "thread": threading.get_ident(),
+ }
+
+ def release(self):
+ """
+ Release the context's resources.
+ """
+ self.lock.acquire()
+ try:
+ if self.surface:
+ egl.eglDestroySurface(self.dpy, self.surface)
+ if self.context and self.dpy:
+ egl.eglDestroyContext(self.dpy, self.context)
+ egl.eglMakeCurrent(
+ self.dpy, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT
+ )
+ if self.dpy:
+ egl.eglTerminate(self.dpy)
+ except EGLError as err:
+ print(
+ f"EGL could not release context on device cuda:{self.cuda_device_id}."
+ " This can happen if you created two contexts on the same device."
+ " Instead, you can use DeviceContextStore to use a single context"
+ " per device, and EGLContext.make_(in)active_in_current_thread to"
+ " (in)activate the context as needed."
+ )
+ raise err
+
+ egl.eglReleaseThread()
+ self.lock.release()
+
+
+class _DeviceContextStore:
+ """
+ DeviceContextStore provides thread-safe storage for EGL and pycuda contexts. It
+ should not be used directly. opengl_utils instantiates a module-global variable
+ called opengl_utils.global_device_context_store. MeshRasterizerOpenGL uses this
+ store to avoid unnecessary context creation and destruction.
+
+ The EGL/CUDA contexts are not meant to be created and destroyed all the time,
+ and having multiple on a single device can be troublesome. Intended use is entirely
+ transparent to the user::
+
+ rasterizer1 = MeshRasterizerOpenGL(...some args...)
+ mesh1 = load_mesh_on_cuda_0()
+
+ # Now rasterizer1 will request EGL/CUDA contexts from
+ # global_device_context_store on cuda:0, and since there aren't any, the
+ # store will create new ones.
+ rasterizer1.rasterize(mesh1)
+
+ # rasterizer2 also needs EGL & CUDA contexts. But global_context_store
+ # already has them for cuda:0. Instead of creating new contexts, the store
+ # will tell rasterizer2 to use them.
+ rasterizer2 = MeshRasterizerOpenGL(dcs)
+ rasterize2.rasterize(mesh1)
+
+ # When rasterizer1 needs to render on cuda:1, the store will create new contexts.
+ mesh2 = load_mesh_on_cuda_1()
+ rasterizer1.rasterize(mesh2)
+
+ """
+
+ def __init__(self):
+ cuda.init()
+ # pycuda contexts, at most one per device.
+ self._cuda_contexts = {}
+ # EGL contexts, at most one per device.
+ self._egl_contexts = {}
+ # Any extra per-device data (e.g. precompiled GL objects).
+ self._context_data = {}
+ # Lock for DeviceContextStore used in multithreaded multidevice scenarios.
+ self._lock = threading.Lock()
+ # All EGL contexts created by this store will have this resolution.
+ self.max_egl_width = 2048
+ self.max_egl_height = 2048
+
+ def get_cuda_context(self, device):
+ """
+ Return a pycuda's CUDA context on a given CUDA device. If we have not created
+ such a context yet, create a new one and store it in a dict. The context is
+ popped (you need to call context.push() to start using it). This function
+ is thread-safe.
+
+ Args:
+ device: A torch.device.
+
+ Returns: A pycuda context corresponding to the given device.
+ """
+ cuda_device_id = device.index
+ with self._lock:
+ if cuda_device_id not in self._cuda_contexts:
+ self._cuda_contexts[cuda_device_id] = _init_cuda_context(cuda_device_id)
+ self._cuda_contexts[cuda_device_id].pop()
+ return self._cuda_contexts[cuda_device_id]
+
+ def get_egl_context(self, device):
+ """
+ Return an EGL context on a given CUDA device. If we have not created such a
+ context yet, create a new one and store it in a dict. The context if not current
+ (you should use the `with egl_context.active_and_locked:` context manager when
+ you need it to be current). This function is thread-safe.
+
+ Args:
+ device: A torch.device.
+
+ Returns: An EGLContext on the requested device. The context will have size
+ self.max_egl_width and self.max_egl_height.
+ """
+ cuda_device_id = device.index
+ with self._lock:
+ egl_context = self._egl_contexts.get(cuda_device_id, None)
+ if egl_context is None:
+ self._egl_contexts[cuda_device_id] = EGLContext(
+ self.max_egl_width, self.max_egl_height, cuda_device_id
+ )
+ return self._egl_contexts[cuda_device_id]
+
+ def set_context_data(self, device, value):
+ """
+ Set arbitrary data in a per-device dict.
+
+ This function is intended for storing precompiled OpenGL objects separately for
+ EGL contexts on different devices. Each such context needs a separate compiled
+ OpenGL program, but (in case e.g. of MeshRasterizerOpenGL) there's no need to
+ re-compile it each time we move the rasterizer to the same device repeatedly,
+ as it happens when using DataParallel.
+
+ Args:
+ device: A torch.device
+ value: An arbitrary Python object.
+ """
+
+ cuda_device_id = device.index
+ self._context_data[cuda_device_id] = value
+
+ def get_context_data(self, device):
+ """
+ Get arbitrary data in a per-device dict. See set_context_data for more detail.
+
+ Args:
+ device: A torch.device
+
+ Returns:
+ The most recent object stored using set_context_data.
+ """
+ cuda_device_id = device.index
+ return self._context_data.get(cuda_device_id, None)
+
+ def release(self):
+ """
+ Release all CUDA and EGL contexts.
+ """
+ for context in self._cuda_contexts.values():
+ context.detach()
+
+ for context in self._egl_contexts.values():
+ context.release()
+
+
+def _init_cuda_context(device_id: int = 0):
+ """
+ Initialize a pycuda context on a chosen device.
+
+ Args:
+ device_id: int, specifies which GPU to use.
+
+ Returns:
+ A pycuda Context.
+ """
+ # pyre-ignore Undefined attribute [16]
+ device = cuda.Device(device_id)
+ cuda_context = device.make_context()
+ return cuda_context
+
+
+def _torch_to_opengl(torch_tensor, cuda_context, cuda_buffer):
+ # CUDA access to the OpenGL buffer is only allowed within a map-unmap block.
+ cuda_context.push()
+ mapping_obj = cuda_buffer.map()
+
+ # data_ptr points to the OpenGL shader storage buffer memory.
+ data_ptr, sz = mapping_obj.device_ptr_and_size()
+
+ # Copy the torch tensor to the OpenGL buffer directly on device.
+ cuda_copy = cuda.Memcpy2D()
+ cuda_copy.set_src_device(torch_tensor.data_ptr())
+ cuda_copy.set_dst_device(data_ptr)
+ cuda_copy.width_in_bytes = cuda_copy.src_pitch = cuda_copy.dst_ptch = (
+ torch_tensor.shape[1] * 4
+ )
+ cuda_copy.height = torch_tensor.shape[0]
+ cuda_copy(False)
+
+ # Unmap and pop the cuda context to make sure OpenGL won't interfere with
+ # PyTorch ops down the line.
+ mapping_obj.unmap()
+ cuda_context.pop()
+
+
+# Initialize a global _DeviceContextStore. Almost always we will only need a single one.
+global_device_context_store = _DeviceContextStore()
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/rasterizer_opengl.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/rasterizer_opengl.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd1dce0defdb3c64454437ac726b10e910dc461c
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/opengl/rasterizer_opengl.py
@@ -0,0 +1,723 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+# NOTE: This module (as well as rasterizer_opengl) will not be imported into pytorch3d
+# if you do not have pycuda.gl and pyopengl installed. In addition, please make sure
+# your Python application *does not* import OpenGL before importing PyTorch3D, unless
+# you are using the EGL backend.
+import warnings
+from typing import Optional, Tuple, Union
+
+import numpy as np
+import OpenGL.GL as gl
+import pycuda.gl
+import torch
+
+import torch.nn as nn
+
+from pytorch3d.structures.meshes import Meshes
+
+from ..cameras import FoVOrthographicCameras, FoVPerspectiveCameras
+from ..mesh.rasterizer import Fragments, RasterizationSettings
+from ..utils import parse_image_size
+
+from .opengl_utils import _torch_to_opengl, global_device_context_store
+
+# Shader strings, used below to compile an OpenGL program.
+vertex_shader = """
+// The vertex shader does nothing.
+#version 430
+
+void main() { }
+"""
+
+geometry_shader = """
+#version 430
+
+layout (points) in;
+layout (triangle_strip, max_vertices = 3) out;
+
+out layout (location = 0) vec2 bary_coords;
+out layout (location = 1) float depth;
+out layout (location = 2) float p2f;
+
+layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; };
+
+uniform mat4 perspective_projection;
+
+vec3 get_vertex_position(int vertex_index) {
+ int offset = gl_PrimitiveIDIn * 9 + vertex_index * 3;
+ return vec3(
+ mesh_buffer[offset],
+ mesh_buffer[offset + 1],
+ mesh_buffer[offset + 2]
+ );
+}
+
+void main() {
+ vec3 positions[3] = {
+ get_vertex_position(0),
+ get_vertex_position(1),
+ get_vertex_position(2)
+ };
+ vec4 projected_vertices[3] = {
+ perspective_projection * vec4(positions[0], 1.0),
+ perspective_projection * vec4(positions[1], 1.0),
+ perspective_projection * vec4(positions[2], 1.0)
+ };
+
+ for (int i = 0; i < 3; ++i) {
+ gl_Position = projected_vertices[i];
+ bary_coords = vec2(i==0 ? 1.0 : 0.0, i==1 ? 1.0 : 0.0);
+ // At the moment, we output depth as the distance from the image plane in
+ // view coordinates -- NOT distance along the camera ray.
+ depth = positions[i][2];
+ p2f = gl_PrimitiveIDIn;
+ EmitVertex();
+ }
+ EndPrimitive();
+}
+"""
+
+fragment_shader = """
+#version 430
+
+in layout(location = 0) vec2 bary_coords;
+in layout(location = 1) float depth;
+in layout(location = 2) float p2f;
+
+
+out vec4 bary_depth_p2f;
+
+void main() {
+ bary_depth_p2f = vec4(bary_coords, depth, round(p2f));
+}
+"""
+
+
+def _parse_and_verify_image_size(
+ image_size: Union[Tuple[int, int], int],
+) -> Tuple[int, int]:
+ """
+ Parse image_size as a tuple of ints. Throw ValueError if the size is incompatible
+ with the maximum renderable size as set in global_device_context_store.
+ """
+ height, width = parse_image_size(image_size)
+ max_h = global_device_context_store.max_egl_height
+ max_w = global_device_context_store.max_egl_width
+ if height > max_h or width > max_w:
+ raise ValueError(
+ f"Max rasterization size is height={max_h}, width={max_w}. "
+ f"Cannot raster an image of size {height}, {width}. You can change max "
+ "allowed rasterization size by modifying the MAX_EGL_HEIGHT and "
+ "MAX_EGL_WIDTH environment variables."
+ )
+ return height, width
+
+
+class MeshRasterizerOpenGL(nn.Module):
+ """
+ EXPERIMENTAL, USE WITH CAUTION
+
+ This class implements methods for rasterizing a batch of heterogeneous
+ Meshes using OpenGL. This rasterizer, as opposed to MeshRasterizer, is
+ *not differentiable* and needs to be used with shading methods such as
+ SplatterPhongShader, which do not require differentiable rasterizerization.
+ It is, however, faster: on a 2M-faced mesh, about 20x so.
+
+ Fragments output by MeshRasterizerOpenGL and MeshRasterizer should have near
+ identical pix_to_face, bary_coords and zbuf. However, MeshRasterizerOpenGL does not
+ return Fragments.dists which is only relevant to SoftPhongShader and
+ SoftSilhouetteShader. These do not work with MeshRasterizerOpenGL (because it is
+ not differentiable).
+ """
+
+ def __init__(
+ self,
+ cameras: Optional[Union[FoVOrthographicCameras, FoVPerspectiveCameras]] = None,
+ raster_settings=None,
+ ) -> None:
+ """
+ Args:
+ cameras: A cameras object which has a `transform_points` method
+ which returns the transformed points after applying the
+ world-to-view and view-to-ndc transformations. Currently, only FoV
+ cameras are supported.
+ raster_settings: the parameters for rasterization. This should be a
+ named tuple.
+ """
+ super().__init__()
+ if raster_settings is None:
+ raster_settings = RasterizationSettings()
+ self.raster_settings = raster_settings
+ _check_raster_settings(self.raster_settings)
+ self.cameras = cameras
+ self.image_size = _parse_and_verify_image_size(self.raster_settings.image_size)
+
+ self.opengl_machinery = _OpenGLMachinery(
+ max_faces=self.raster_settings.max_faces_opengl,
+ )
+
+ def forward(self, meshes_world: Meshes, **kwargs) -> Fragments:
+ """
+ Args:
+ meshes_world: a Meshes object representing a batch of meshes with
+ coordinates in world space. The batch must live on a GPU.
+
+ Returns:
+ Fragments: Rasterization outputs as a named tuple. These are different than
+ Fragments returned by MeshRasterizer in two ways. First, we return no
+ `dist` which is only relevant to SoftPhongShader which doesn't work
+ with MeshRasterizerOpenGL (because it is not differentiable). Second,
+ the zbuf uses the opengl zbuf convention, where the z-vals are between 0
+ (at projection plane) and 1 (at clipping distance), and are a non-linear
+ function of the depth values of the camera ray intersections. In
+ contrast, MeshRasterizer's zbuf values are simply the distance of each
+ ray intersection from the camera.
+
+ Throws:
+ ValueError if meshes_world lives on the CPU.
+ """
+ if meshes_world.device == torch.device("cpu"):
+ raise ValueError("MeshRasterizerOpenGL works only on CUDA devices.")
+
+ raster_settings = kwargs.get("raster_settings", self.raster_settings)
+ _check_raster_settings(raster_settings)
+
+ image_size = (
+ _parse_and_verify_image_size(raster_settings.image_size) or self.image_size
+ )
+
+ # OpenGL needs vertices in NDC coordinates with un-flipped xy directions.
+ cameras_unpacked = kwargs.get("cameras", self.cameras)
+ _check_cameras(cameras_unpacked)
+ meshes_gl_ndc = _convert_meshes_to_gl_ndc(
+ meshes_world, image_size, cameras_unpacked, **kwargs
+ )
+
+ # Perspective projection will happen within the OpenGL rasterizer.
+ projection_matrix = cameras_unpacked.get_projection_transform(**kwargs)._matrix
+
+ # Run OpenGL rasterization machinery.
+ pix_to_face, bary_coords, zbuf = self.opengl_machinery(
+ meshes_gl_ndc, projection_matrix, image_size
+ )
+
+ # Return the Fragments and detach, because gradients don't go through OpenGL.
+ return Fragments(
+ pix_to_face=pix_to_face,
+ zbuf=zbuf,
+ bary_coords=bary_coords,
+ dists=None,
+ ).detach()
+
+ def to(self, device):
+ # Manually move to device cameras as it is not a subclass of nn.Module
+ if self.cameras is not None:
+ self.cameras = self.cameras.to(device)
+
+ # Create a new OpenGLMachinery, as its member variables can be tied to a GPU.
+ self.opengl_machinery = _OpenGLMachinery(
+ max_faces=self.raster_settings.max_faces_opengl,
+ )
+
+
+class _OpenGLMachinery:
+ """
+ A class holding OpenGL machinery used by MeshRasterizerOpenGL.
+ """
+
+ def __init__(
+ self,
+ max_faces: int = 10_000_000,
+ ) -> None:
+ self.max_faces = max_faces
+ self.program = None
+
+ # These will be created on an appropriate GPU each time we render a new mesh on
+ # that GPU for the first time.
+ self.egl_context = None
+ self.cuda_context = None
+ self.perspective_projection_uniform = None
+ self.mesh_buffer_object = None
+ self.vao = None
+ self.fbo = None
+ self.cuda_buffer = None
+
+ def __call__(
+ self,
+ meshes_gl_ndc: Meshes,
+ projection_matrix: torch.Tensor,
+ image_size: Tuple[int, int],
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Rasterize a batch of meshes, using a given batch of projection matrices and
+ image size.
+
+ Args:
+ meshes_gl_ndc: A Meshes object, with vertices in the OpenGL NDC convention.
+ projection_matrix: A 3x3 camera projection matrix, or a tensor of projection
+ matrices equal in length to the number of meshes in meshes_gl_ndc.
+ image_size: Image size to rasterize. Must be smaller than the max height and
+ width stored in global_device_context_store.
+
+ Returns:
+ pix_to_faces: A BHW1 tensor of ints, filled with -1 where no face projects
+ to a given pixel.
+ bary_coords: A BHW3 float tensor, filled with -1 where no face projects to
+ a given pixel.
+ zbuf: A BHW1 float tensor, filled with 1 where no face projects to a given
+ pixel. NOTE: this zbuf uses the opengl zbuf convention, where the z-vals
+ are between 0 (at projection plane) and 1 (at clipping distance), and
+ are a non-linear function of the depth values of the camera ray inter-
+ sections.
+ """
+
+ self.initialize_device_data(meshes_gl_ndc.device)
+ with self.egl_context.active_and_locked():
+ # Perspective projection happens in OpenGL. Move the matrix over if there's only
+ # a single camera shared by all the meshes.
+ if projection_matrix.shape[0] == 1:
+ self._projection_matrix_to_opengl(projection_matrix)
+
+ pix_to_faces = []
+ bary_coords = []
+ zbufs = []
+
+ # pyre-ignore Incompatible parameter type [6]
+ for mesh_id, mesh in enumerate(meshes_gl_ndc):
+ pix_to_face, bary_coord, zbuf = self._rasterize_mesh(
+ mesh,
+ image_size,
+ projection_matrix=(
+ projection_matrix[mesh_id]
+ if projection_matrix.shape[0] > 1
+ else None
+ ),
+ )
+ pix_to_faces.append(pix_to_face)
+ bary_coords.append(bary_coord)
+ zbufs.append(zbuf)
+
+ return (
+ torch.cat(pix_to_faces, dim=0),
+ torch.cat(bary_coords, dim=0),
+ torch.cat(zbufs, dim=0),
+ )
+
+ def initialize_device_data(self, device) -> None:
+ """
+ Initialize data specific to a GPU device: the EGL and CUDA contexts, the OpenGL
+ program, as well as various buffer and array objects used to communicate with
+ OpenGL.
+
+ Args:
+ device: A torch.device.
+ """
+ self.egl_context = global_device_context_store.get_egl_context(device)
+ self.cuda_context = global_device_context_store.get_cuda_context(device)
+
+ # self.program represents the OpenGL program we use for rasterization.
+ if global_device_context_store.get_context_data(device) is None:
+ with self.egl_context.active_and_locked():
+ self.program = self._compile_and_link_gl_program()
+ self._set_up_gl_program_properties(self.program)
+
+ # Create objects used to transfer data into and out of the program.
+ (
+ self.perspective_projection_uniform,
+ self.mesh_buffer_object,
+ self.vao,
+ self.fbo,
+ ) = self._prepare_persistent_opengl_objects(
+ self.program,
+ self.max_faces,
+ )
+
+ # Register the input buffer with pycuda, to transfer data directly into it.
+ self.cuda_context.push()
+ self.cuda_buffer = pycuda.gl.RegisteredBuffer(
+ int(self.mesh_buffer_object),
+ pycuda.gl.graphics_map_flags.WRITE_DISCARD,
+ )
+ self.cuda_context.pop()
+
+ global_device_context_store.set_context_data(
+ device,
+ (
+ self.program,
+ self.perspective_projection_uniform,
+ self.mesh_buffer_object,
+ self.vao,
+ self.fbo,
+ self.cuda_buffer,
+ ),
+ )
+ (
+ self.program,
+ self.perspective_projection_uniform,
+ self.mesh_buffer_object,
+ self.vao,
+ self.fbo,
+ self.cuda_buffer,
+ ) = global_device_context_store.get_context_data(device)
+
+ def release(self) -> None:
+ """
+ Release CUDA and OpenGL resources.
+ """
+ # Finish all current operations.
+ torch.cuda.synchronize()
+ self.cuda_context.synchronize()
+
+ # Free pycuda resources.
+ self.cuda_context.push()
+ self.cuda_buffer.unregister()
+ self.cuda_context.pop()
+
+ # Free GL resources.
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo)
+ # pyre-fixme[16]: Module `GL_3_0` has no attribute `glDeleteFramebuffers`.
+ gl.glDeleteFramebuffers(1, [self.fbo])
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
+ del self.fbo
+
+ gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 0, self.mesh_buffer_object)
+ # pyre-fixme[16]: Module `GL_1_5` has no attribute `glDeleteBuffers`.
+ gl.glDeleteBuffers(1, [self.mesh_buffer_object])
+ gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 0, 0)
+ del self.mesh_buffer_object
+
+ gl.glDeleteProgram(self.program)
+ self.egl_context.release()
+
+ def _projection_matrix_to_opengl(self, projection_matrix: torch.Tensor) -> None:
+ """
+ Transfer a torch projection matrix to OpenGL.
+
+ Args:
+ projection matrix: A 3x3 float tensor.
+ """
+ gl.glUseProgram(self.program)
+ # pyre-fixme[16]: Module `GL_2_0` has no attribute `glUniformMatrix4fv`.
+ gl.glUniformMatrix4fv(
+ self.perspective_projection_uniform,
+ 1,
+ gl.GL_FALSE,
+ projection_matrix.detach().flatten().cpu().numpy().astype(np.float32),
+ )
+ gl.glUseProgram(0)
+
+ def _rasterize_mesh(
+ self,
+ mesh: Meshes,
+ image_size: Tuple[int, int],
+ projection_matrix: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Rasterize a single mesh using OpenGL.
+
+ Args:
+ mesh: A Meshes object, containing a single mesh only.
+ projection_matrix: A 3x3 camera projection matrix, or a tensor of projection
+ matrices equal in length to the number of meshes in meshes_gl_ndc.
+ image_size: Image size to rasterize. Must be smaller than the max height and
+ width stored in global_device_context_store.
+
+ Returns:
+ pix_to_faces: A 1HW1 tensor of ints, filled with -1 where no face projects
+ to a given pixel.
+ bary_coords: A 1HW3 float tensor, filled with -1 where no face projects to
+ a given pixel.
+ zbuf: A 1HW1 float tensor, filled with 1 where no face projects to a given
+ pixel. NOTE: this zbuf uses the opengl zbuf convention, where the z-vals
+ are between 0 (at projection plane) and 1 (at clipping distance), and
+ are a non-linear function of the depth values of the camera ray inter-
+ sections.
+ """
+ height, width = image_size
+ # Extract face_verts and move them to OpenGL as well. We use pycuda to
+ # directly move the vertices on the GPU, to avoid a costly torch/GPU -> CPU
+ # -> openGL/GPU trip.
+ verts_packed = mesh.verts_packed().detach()
+ faces_packed = mesh.faces_packed().detach()
+ face_verts = verts_packed[faces_packed].reshape(-1, 9)
+ _torch_to_opengl(face_verts, self.cuda_context, self.cuda_buffer)
+
+ if projection_matrix is not None:
+ self._projection_matrix_to_opengl(projection_matrix)
+
+ # Start OpenGL operations.
+ gl.glUseProgram(self.program)
+
+ # Render an image of size (width, height).
+ gl.glViewport(0, 0, width, height)
+
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo)
+ # Clear the output framebuffer. The "background" value for both pix_to_face
+ # as well as bary_coords is -1 (background = pixels which the rasterizer
+ # projected no triangle to).
+ gl.glClearColor(-1.0, -1.0, -1.0, -1.0)
+ gl.glClearDepth(1.0)
+ # pyre-ignore Unsupported operand [58]
+ gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
+
+ # Run the actual rendering. The face_verts were transported to the OpenGL
+ # program into a shader storage buffer which is used directly in the geometry
+ # shader. Here, we only pass the number of these vertices to the vertex shader
+ # (which doesn't do anything and passes directly to the geometry shader).
+ gl.glBindVertexArray(self.vao)
+ gl.glDrawArrays(gl.GL_POINTS, 0, len(face_verts))
+ gl.glBindVertexArray(0)
+
+ # Read out the result. We ignore the depth buffer. The RGBA color buffer stores
+ # barycentrics in the RGB component and pix_to_face in the A component.
+ bary_depth_p2f_gl = gl.glReadPixels(
+ 0,
+ 0,
+ width,
+ height,
+ gl.GL_RGBA,
+ gl.GL_FLOAT,
+ )
+
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
+ gl.glUseProgram(0)
+
+ # Create torch tensors containing the results.
+ bary_depth_p2f = (
+ torch.frombuffer(bary_depth_p2f_gl, dtype=torch.float)
+ .reshape(1, height, width, 1, -1)
+ .to(verts_packed.device)
+ )
+
+ # Read out barycentrics. GL only outputs the first two, so we need to compute
+ # the third one and make sure we still leave no-intersection pixels with -1.
+ barycentric_coords = torch.cat(
+ [
+ bary_depth_p2f[..., :2],
+ 1.0 - bary_depth_p2f[..., 0:1] - bary_depth_p2f[..., 1:2],
+ ],
+ dim=-1,
+ )
+ barycentric_coords = torch.where(
+ barycentric_coords == 3, -1, barycentric_coords
+ )
+ depth = bary_depth_p2f[..., 2:3].squeeze(-1)
+ pix_to_face = bary_depth_p2f[..., -1].long()
+
+ return pix_to_face, barycentric_coords, depth
+
+ @staticmethod
+ def _compile_and_link_gl_program():
+ """
+ Compile the vertex, geometry, and fragment shaders and link them into an OpenGL
+ program. The shader sources are strongly inspired by https://github.com/tensorflow/
+ graphics/blob/master/tensorflow_graphics/rendering/opengl/rasterization_backend.py.
+
+ Returns:
+ An OpenGL program for mesh rasterization.
+ """
+ program = gl.glCreateProgram()
+ shader_objects = []
+
+ for shader_string, shader_type in zip(
+ [vertex_shader, geometry_shader, fragment_shader],
+ [gl.GL_VERTEX_SHADER, gl.GL_GEOMETRY_SHADER, gl.GL_FRAGMENT_SHADER],
+ ):
+ shader_objects.append(gl.glCreateShader(shader_type))
+ gl.glShaderSource(shader_objects[-1], shader_string)
+
+ gl.glCompileShader(shader_objects[-1])
+ status = gl.glGetShaderiv(shader_objects[-1], gl.GL_COMPILE_STATUS)
+ if status == gl.GL_FALSE:
+ gl.glDeleteShader(shader_objects[-1])
+ gl.glDeleteProgram(program)
+ error_msg = gl.glGetShaderInfoLog(shader_objects[-1]).decode("utf-8")
+ raise RuntimeError(f"Compilation failure:\n {error_msg}")
+
+ gl.glAttachShader(program, shader_objects[-1])
+ gl.glDeleteShader(shader_objects[-1])
+
+ gl.glLinkProgram(program)
+ status = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
+
+ if status == gl.GL_FALSE:
+ gl.glDeleteProgram(program)
+ error_msg = gl.glGetProgramInfoLog(program)
+ raise RuntimeError(f"Link failure:\n {error_msg}")
+
+ return program
+
+ @staticmethod
+ def _set_up_gl_program_properties(program) -> None:
+ """
+ Set basic OpenGL program properties: disable blending, enable depth testing,
+ and disable face culling.
+ """
+ gl.glUseProgram(program)
+ gl.glDisable(gl.GL_BLEND)
+ gl.glEnable(gl.GL_DEPTH_TEST)
+ gl.glDisable(gl.GL_CULL_FACE)
+ gl.glUseProgram(0)
+
+ @staticmethod
+ def _prepare_persistent_opengl_objects(program, max_faces: int):
+ """
+ Prepare OpenGL objects that we want to persist between rasterizations.
+
+ Args:
+ program: The OpenGL program the resources will be tied to.
+ max_faces: Max number of faces of any mesh we will rasterize.
+
+ Returns:
+ perspective_projection_uniform: An OpenGL object pointing to a location of
+ the perspective projection matrix in OpenGL memory.
+ mesh_buffer_object: An OpenGL object pointing to the location of the mesh
+ buffer object in OpenGL memory.
+ vao: The OpenGL input array object.
+ fbo: The OpenGL output framebuffer.
+
+ """
+ gl.glUseProgram(program)
+ # Get location of the "uniform" (that is, an internal OpenGL variable available
+ # to the shaders) that we'll load the projection matrices to.
+ perspective_projection_uniform = gl.glGetUniformLocation(
+ program, "perspective_projection"
+ )
+
+ # Mesh buffer object -- our main input point. We'll copy the mesh here
+ # from pytorch/cuda. The buffer needs enough space to store the three vertices
+ # of each face, that is its size in bytes is
+ # max_faces * 3 (vertices) * 3 (coordinates) * 4 (bytes)
+ # pyre-fixme[16]: Module `GL_1_5` has no attribute `glGenBuffers`.
+ mesh_buffer_object = gl.glGenBuffers(1)
+ gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 0, mesh_buffer_object)
+
+ gl.glBufferData(
+ gl.GL_SHADER_STORAGE_BUFFER,
+ max_faces * 9 * 4,
+ np.zeros((max_faces, 9), dtype=np.float32),
+ gl.GL_DYNAMIC_COPY,
+ )
+
+ # Input vertex array object. We will only use it implicitly for indexing the
+ # vertices, but the actual input data is passed in the shader storage buffer.
+ # pyre-fixme[16]: Module `GL_3_0` has no attribute `glGenVertexArrays`.
+ vao = gl.glGenVertexArrays(1)
+
+ # Create the framebuffer object (fbo) where we'll store output data.
+ MAX_EGL_WIDTH = global_device_context_store.max_egl_width
+ MAX_EGL_HEIGHT = global_device_context_store.max_egl_height
+ # pyre-fixme[16]: Module `GL_3_0` has no attribute `glGenRenderbuffers`.
+ color_buffer = gl.glGenRenderbuffers(1)
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, color_buffer)
+ gl.glRenderbufferStorage(
+ gl.GL_RENDERBUFFER, gl.GL_RGBA32F, MAX_EGL_WIDTH, MAX_EGL_HEIGHT
+ )
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)
+
+ # pyre-fixme[16]: Module `GL_3_0` has no attribute `glGenRenderbuffers`.
+ depth_buffer = gl.glGenRenderbuffers(1)
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, depth_buffer)
+ gl.glRenderbufferStorage(
+ gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, MAX_EGL_WIDTH, MAX_EGL_HEIGHT
+ )
+ gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)
+
+ # pyre-fixme[16]: Module `GL_3_0` has no attribute `glGenFramebuffers`.
+ fbo = gl.glGenFramebuffers(1)
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, fbo)
+ gl.glFramebufferRenderbuffer(
+ gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_RENDERBUFFER, color_buffer
+ )
+ gl.glFramebufferRenderbuffer(
+ gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, depth_buffer
+ )
+ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
+
+ gl.glUseProgram(0)
+ return perspective_projection_uniform, mesh_buffer_object, vao, fbo
+
+
+def _check_cameras(cameras) -> None:
+ # Check that the cameras are non-None and compatible with MeshRasterizerOpenGL.
+ if cameras is None:
+ msg = "Cameras must be specified either at initialization \
+ or in the forward pass of MeshRasterizer"
+ raise ValueError(msg)
+ if type(cameras).__name__ in {"PerspectiveCameras", "OrthographicCameras"}:
+ raise ValueError(
+ "MeshRasterizerOpenGL only works with FoVPerspectiveCameras and "
+ "FoVOrthographicCameras, which are OpenGL compatible."
+ )
+
+
+def _check_raster_settings(raster_settings) -> None:
+ # Check that the rasterizer's settings are compatible with MeshRasterizerOpenGL.
+ if raster_settings.faces_per_pixel > 1:
+ warnings.warn(
+ "MeshRasterizerOpenGL currently works only with one face per pixel."
+ )
+ if raster_settings.cull_backfaces:
+ warnings.warn(
+ "MeshRasterizerOpenGL cannot cull backfaces yet, rasterizing without culling."
+ )
+ if raster_settings.cull_to_frustum:
+ warnings.warn(
+ "MeshRasterizerOpenGL cannot cull to frustum yet, rasterizing without culling."
+ )
+ if raster_settings.z_clip_value is not None:
+ raise NotImplementedError("MeshRasterizerOpenGL cannot do z-clipping yet.")
+ if raster_settings.perspective_correct is False:
+ raise ValueError(
+ "MeshRasterizerOpenGL always uses perspective-correct interpolation."
+ )
+
+
+def _convert_meshes_to_gl_ndc(
+ meshes_world: Meshes, image_size: Tuple[int, int], camera, **kwargs
+) -> Meshes:
+ """
+ Convert a batch of world-coordinate meshes to GL NDC coordinates.
+
+ Args:
+ meshes_world: Meshes in the world coordinate system.
+ image_size: Image height and width, used to modify mesh coords for rendering in
+ non-rectangular images. OpenGL will expand anything within the [-1, 1] NDC
+ range to fit the width and height of the screen, so we will squeeze the NDCs
+ appropriately if rendering a rectangular image.
+ camera: FoV cameras.
+ kwargs['R'], kwargs['T']: If present, used to define the world-view transform.
+ """
+ height, width = image_size
+ verts_ndc = (
+ camera.get_world_to_view_transform(**kwargs)
+ .compose(camera.get_ndc_camera_transform(**kwargs))
+ .transform_points(meshes_world.verts_padded(), eps=None)
+ )
+ verts_ndc[..., 0] = -verts_ndc[..., 0]
+ verts_ndc[..., 1] = -verts_ndc[..., 1]
+
+ # In case of a non-square viewport, transform the vertices. OpenGL will expand
+ # the anything within the [-1, 1] NDC range to fit the width and height of the
+ # screen. So to work with PyTorch3D cameras, we need to squeeze the NDCs
+ # appropriately.
+ dtype, device = verts_ndc.dtype, verts_ndc.device
+ if height > width:
+ verts_ndc = verts_ndc * torch.tensor(
+ [1, width / height, 1], dtype=dtype, device=device
+ )
+ elif width > height:
+ verts_ndc = verts_ndc * torch.tensor(
+ [height / width, 1, 1], dtype=dtype, device=device
+ )
+
+ meshes_gl_ndc = meshes_world.update_padded(new_verts_padded=verts_ndc)
+
+ return meshes_gl_ndc
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/__init__.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce2529894bec700e4b103c783dd8baaddde77123
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/__init__.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/compositor.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/compositor.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..313d88696281534cf965085af4e381dffac0c4b9
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/compositor.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterize_points.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterize_points.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d303b3cddd7c5223418550a7d5b2e1f1d7fbe03
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterize_points.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterizer.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterizer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9305664ea06164ba862bb453e65e7e3adee544fd
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/rasterizer.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/renderer.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/renderer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef11b934c493a7a99174cca7ec5fa851349551c7
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/__pycache__/renderer.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__init__.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c843025a7bc67325f18a818425926bf82398f6e3
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+from .renderer import Renderer # noqa: F401
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/__init__.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d466f9a9c0aad51a2de7c8a1379b7513dccb57f0
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/__init__.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/renderer.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/renderer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c2f7faf7b634d87d15378c73faeedd59ee6fe70
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/renderer.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/unified.cpython-310.pyc b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/unified.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cfbc66e91f2220ab73889b9b0c12968037742cb
Binary files /dev/null and b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/__pycache__/unified.cpython-310.pyc differ
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/renderer.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/renderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5aceda6fc700fb784d263ea123dbf0f89887c23b
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/renderer.py
@@ -0,0 +1,666 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+"""pulsar renderer PyTorch integration.
+
+Proper Python support for pytorch requires creating a torch.autograd.function
+(independent of whether this is being done within the C++ module). This is done
+here and a torch.nn.Module is exposed for the use in more complex models.
+"""
+import logging
+import warnings
+from typing import Optional, Tuple, Union
+
+import torch
+from pytorch3d import _C
+from pytorch3d.transforms import axis_angle_to_matrix, rotation_6d_to_matrix
+
+
+LOGGER = logging.getLogger(__name__)
+GAMMA_WARNING_EMITTED = False
+AXANGLE_WARNING_EMITTED = False
+
+
+class _Render(torch.autograd.Function):
+ """
+ Differentiable rendering function for the Pulsar renderer.
+
+ Usually this will be used through the `Renderer` module, which takes care of
+ setting up the buffers and putting them on the correct device. If you use
+ the function directly, you will have to do this manually.
+
+ The steps for this are two-fold: first, you need to create a native Renderer
+ object to provide the required buffers. This is the `native_renderer` parameter
+ for this function. You can create it by creating a `pytorch3d._C.PulsarRenderer`
+ object (with parameters for width, height and maximum number of balls it should
+ be able to render). This object by default resides on the CPU. If you want to
+ shift the buffers to a different device, just assign an empty tensor on the target
+ device to its property `device_tracker`.
+
+ To convert camera parameters from a more convenient representation to the
+ required vectors as in this function, you can use the static
+ function `pytorch3d.renderer.points.pulsar.Renderer._transform_cam_params`.
+
+ Args:
+ * ctx: Pytorch context.
+ * vert_pos: vertex positions. [Bx]Nx3 tensor of positions in 3D space.
+ * vert_col: vertex colors. [Bx]NxK tensor of channels.
+ * vert_rad: vertex radii. [Bx]N tensor of radiuses, >0.
+ * cam_pos: camera position(s). [Bx]3 tensor in 3D coordinates.
+ * pixel_0_0_center: [Bx]3 tensor center(s) of the upper left pixel(s) in
+ world coordinates.
+ * pixel_vec_x: [Bx]3 tensor from one pixel center to the next in image x
+ direction in world coordinates.
+ * pixel_vec_y: [Bx]3 tensor from one pixel center to the next in image y
+ direction in world coordinates.
+ * focal_length: [Bx]1 tensor of focal lengths in world coordinates.
+ * principal_point_offsets: [Bx]2 tensor of principal point offsets in pixels.
+ * gamma: sphere transparency in [1.,1E-5], with 1 being mostly transparent.
+ [Bx]1.
+ * max_depth: maximum depth for spheres to render. Set this as tighly
+ as possible to have good numerical accuracy for gradients.
+ * native_renderer: a `pytorch3d._C.PulsarRenderer` object.
+ * min_depth: a float with the minimum depth a sphere must have to be renderer.
+ Must be 0. or > max(focal_length).
+ * bg_col: K tensor with a background color to use or None (uses all ones).
+ * opacity: [Bx]N tensor of opacity values in [0., 1.] or None (uses all ones).
+ * percent_allowed_difference: a float in [0., 1.[ with the maximum allowed
+ difference in color space. This is used to speed up the
+ computation. Default: 0.01.
+ * max_n_hits: a hard limit on the number of hits per ray. Default: max int.
+ * mode: render mode in {0, 1}. 0: render an image; 1: render the hit map.
+ * return_forward_info: whether to return a second map. This second map contains
+ 13 channels: first channel contains sm_m (the maximum exponent factor
+ observed), the second sm_d (the normalization denominator, the sum of all
+ coefficients), the third the maximum closest possible intersection for a
+ hit. The following channels alternate with the float encoded integer index
+ of a sphere and its weight. They are the five spheres with the highest
+ color contribution to this pixel color, ordered descending.
+
+ Returns:
+ * image: [Bx]HxWxK float tensor with the resulting image.
+ * forw_info: [Bx]HxWx13 float forward information as described above,
+ if enabled.
+ """
+
+ @staticmethod
+ # pyre-fixme[14]: `forward` overrides method defined in `Function` inconsistently.
+ def forward(
+ ctx,
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_pos,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ gamma,
+ max_depth,
+ native_renderer,
+ min_depth=0.0,
+ bg_col=None,
+ opacity=None,
+ percent_allowed_difference=0.01,
+ # pyre-fixme[16]: Module `_C` has no attribute `MAX_UINT`.
+ max_n_hits=_C.MAX_UINT,
+ mode=0,
+ return_forward_info=False,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ if mode != 0:
+ assert not return_forward_info, (
+ "You are using a non-standard rendering mode. This does "
+ "not provide gradients, and also no `forward_info`. Please "
+ "set `return_forward_info` to `False`."
+ )
+ ctx.gamma = gamma
+ ctx.max_depth = max_depth
+ ctx.min_depth = min_depth
+ ctx.percent_allowed_difference = percent_allowed_difference
+ ctx.max_n_hits = max_n_hits
+ ctx.mode = mode
+ ctx.native_renderer = native_renderer
+ image, info = ctx.native_renderer.forward(
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_pos,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ gamma,
+ max_depth,
+ min_depth,
+ bg_col,
+ opacity,
+ percent_allowed_difference,
+ max_n_hits,
+ mode,
+ )
+ if mode != 0:
+ # Backprop not possible!
+ info = None
+ # Prepare for backprop.
+ ctx.save_for_backward(
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_pos,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ bg_col,
+ opacity,
+ image,
+ info,
+ )
+ if return_forward_info:
+ return image, info
+ else:
+ return image
+
+ @staticmethod
+ def backward(ctx, grad_im, *args):
+ global GAMMA_WARNING_EMITTED
+ (
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_pos,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ bg_col,
+ opacity,
+ image,
+ info,
+ ) = ctx.saved_tensors
+ if (
+ (
+ ctx.needs_input_grad[0]
+ or ctx.needs_input_grad[2]
+ or ctx.needs_input_grad[3]
+ or ctx.needs_input_grad[4]
+ or ctx.needs_input_grad[5]
+ or ctx.needs_input_grad[6]
+ or ctx.needs_input_grad[7]
+ )
+ and ctx.gamma < 1e-3
+ and not GAMMA_WARNING_EMITTED
+ ):
+ warnings.warn(
+ "Optimizing for non-color parameters and having a gamma value < 1E-3! "
+ "This is probably not going to produce usable gradients."
+ )
+ GAMMA_WARNING_EMITTED = True
+ if ctx.mode == 0:
+ (
+ grad_pos,
+ grad_col,
+ grad_rad,
+ grad_cam_pos,
+ grad_pixel_0_0_center,
+ grad_pixel_vec_x,
+ grad_pixel_vec_y,
+ grad_opacity,
+ ) = ctx.native_renderer.backward(
+ grad_im,
+ image,
+ info,
+ vert_pos,
+ vert_col,
+ vert_rad,
+ cam_pos,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ ctx.gamma,
+ ctx.max_depth,
+ ctx.min_depth,
+ bg_col,
+ opacity,
+ ctx.percent_allowed_difference,
+ ctx.max_n_hits,
+ ctx.mode,
+ ctx.needs_input_grad[0],
+ ctx.needs_input_grad[1],
+ ctx.needs_input_grad[2],
+ ctx.needs_input_grad[3]
+ or ctx.needs_input_grad[4]
+ or ctx.needs_input_grad[5]
+ or ctx.needs_input_grad[6]
+ or ctx.needs_input_grad[7],
+ ctx.needs_input_grad[14],
+ None, # No debug information provided.
+ )
+ else:
+ raise ValueError(
+ "Performing a backward pass for a "
+ "rendering with `mode != 0`! This is not possible."
+ )
+ return (
+ grad_pos,
+ grad_col,
+ grad_rad,
+ grad_cam_pos,
+ grad_pixel_0_0_center,
+ grad_pixel_vec_x,
+ grad_pixel_vec_y,
+ None, # focal_length
+ None, # principal_point_offsets
+ None, # gamma
+ None, # max_depth
+ None, # native_renderer
+ None, # min_depth
+ None, # bg_col
+ grad_opacity,
+ None, # percent_allowed_difference
+ None, # max_n_hits
+ None, # mode
+ None, # return_forward_info
+ )
+
+
+class Renderer(torch.nn.Module):
+ """
+ Differentiable rendering module for the Pulsar renderer.
+
+ Set the maximum number of balls to a reasonable value. It is used to determine
+ several buffer sizes. It is no problem to render less balls than this number,
+ but never more.
+
+ When optimizing for sphere positions, sphere radiuses or camera parameters you
+ have to use higher gamma values (closer to one) and larger sphere sizes: spheres
+ can only 'move' to areas that they cover, and only with higher gamma values exists
+ a gradient w.r.t. their color depending on their position.
+
+ Args:
+ * width: result image width in pixels.
+ * height: result image height in pixels.
+ * max_num_balls: the maximum number of balls this renderer will handle.
+ * orthogonal_projection: use an orthogonal instead of perspective projection.
+ Default: False.
+ * right_handed_system: use a right-handed instead of a left-handed coordinate
+ system. This is relevant for compatibility with other drawing or scanning
+ systems. Pulsar by default assumes a left-handed world and camera coordinate
+ system as known from mathematics with x-axis to the right, y axis up and z
+ axis for increasing depth along the optical axis. In the image coordinate
+ system, only the y axis is pointing down, leading still to a left-handed
+ system. If you set this to True, it is assuming a right-handed world and
+ camera coordinate system with x axis to the right, y axis to the top and
+ z axis decreasing along the optical axis. Again, the image coordinate
+ system has a flipped y axis, remaining a right-handed system.
+ Default: False.
+ * background_normalized_depth: the normalized depth the background is placed
+ at.
+ This is on a scale from 0. to 1. between the specified min and max depth
+ (see the forward function). The value 0. is the most furthest depth whereas
+ 1. is the closest. Be careful when setting the background too far front - it
+ may hide elements in your scene. Default: EPS.
+ * n_channels: the number of image content channels to use. This is usually three
+ for regular color representations, but can be a higher or lower number.
+ Default: 3.
+ * n_track: the number of spheres to track for gradient calculation per pixel.
+ Only the closest n_track spheres will receive gradients. Default: 5.
+ """
+
+ def __init__(
+ self,
+ width: int,
+ height: int,
+ max_num_balls: int,
+ orthogonal_projection: bool = False,
+ right_handed_system: bool = False,
+ # pyre-fixme[16]: Module `_C` has no attribute `EPS`.
+ background_normalized_depth: float = _C.EPS,
+ n_channels: int = 3,
+ n_track: int = 5,
+ ) -> None:
+ super(Renderer, self).__init__()
+ # pyre-fixme[16]: Module `pytorch3d` has no attribute `_C`.
+ self._renderer = _C.PulsarRenderer(
+ width,
+ height,
+ max_num_balls,
+ orthogonal_projection,
+ right_handed_system,
+ background_normalized_depth,
+ n_channels,
+ n_track,
+ )
+ self.register_buffer("device_tracker", torch.zeros(1))
+
+ @staticmethod
+ def sphere_ids_from_result_info_nograd(result_info: torch.Tensor) -> torch.Tensor:
+ """
+ Get the sphere IDs from a result info tensor.
+ """
+ if result_info.ndim == 3:
+ return Renderer.sphere_ids_from_result_info_nograd(result_info[None, ...])
+ # pyre-fixme[16]: Module `pytorch3d` has no attribute `_C`.
+ return _C.pulsar_sphere_ids_from_result_info_nograd(result_info)
+
+ @staticmethod
+ def depth_map_from_result_info_nograd(result_info: torch.Tensor) -> torch.Tensor:
+ """
+ Get the depth map from a result info tensor.
+
+ This returns a map of the same size as the image with just one channel
+ containing the closest intersection value at that position. Gradients
+ are not available for this tensor, but do note that you can use
+ `sphere_ids_from_result_info_nograd` to get the IDs of the spheres at
+ each position and directly create a loss on their depth if required.
+
+ The depth map contains -1. at positions where no intersection has
+ been detected.
+ """
+ return result_info[..., 4]
+
+ @staticmethod
+ def _transform_cam_params(
+ cam_params: torch.Tensor,
+ width: int,
+ height: int,
+ orthogonal: bool,
+ right_handed: bool,
+ first_R_then_T: bool = False,
+ ) -> Tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ ]:
+ """
+ Transform 8 component camera parameter vector(s) to the internal camera
+ representation.
+
+ The input vectors consists of:
+ * 3 components for camera position,
+ * 3 components for camera rotation (three rotation angles) or
+ 6 components as described in "On the Continuity of Rotation
+ Representations in Neural Networks" (Zhou et al.),
+ * focal length,
+ * the sensor width in world coordinates,
+ * [optional] the principal point offset in x and y.
+
+ The sensor height is inferred by pixel size and sensor width to obtain
+ quadratic pixels.
+
+ Args:
+ * cam_params: [Bx]{8, 10, 11, 13}, input tensors as described above.
+ * width: number of pixels in x direction.
+ * height: number of pixels in y direction.
+ * orthogonal: bool, whether an orthogonal projection is used
+ (does not use focal length).
+ * right_handed: bool, whether to use a right handed system
+ (negative z in camera direction).
+ * first_R_then_T: bool, whether to first rotate, then translate
+ the camera (PyTorch3D convention).
+
+ Returns:
+ * pos_vec: the position vector in 3D,
+ * pixel_0_0_center: the center of the upper left pixel in world coordinates,
+ * pixel_vec_x: the step to move one pixel on the image x axis
+ in world coordinates,
+ * pixel_vec_y: the step to move one pixel on the image y axis
+ in world coordinates,
+ * focal_length: the focal lengths,
+ * principal_point_offsets: the principal point offsets in x, y.
+ """
+ global AXANGLE_WARNING_EMITTED
+ # Set up all direction vectors, i.e., the sensor direction of all axes.
+ assert width > 0
+ assert height > 0
+ batch_processing = True
+ if cam_params.ndimension() == 1:
+ batch_processing = False
+ cam_params = cam_params[None, :]
+ batch_size = cam_params.size(0)
+ continuous_rep = True
+ if cam_params.shape[1] in [8, 10]:
+ if cam_params.requires_grad and not AXANGLE_WARNING_EMITTED:
+ warnings.warn(
+ "Using an axis angle representation for camera rotations. "
+ "This has discontinuities and should not be used for optimization. "
+ "Alternatively, use a six-component representation as described in "
+ "'On the Continuity of Rotation Representations in Neural Networks'"
+ " (Zhou et al.). "
+ "The `pytorch3d.transforms` module provides "
+ "facilities for using this representation."
+ )
+ AXANGLE_WARNING_EMITTED = True
+ continuous_rep = False
+ else:
+ assert cam_params.shape[1] in [11, 13]
+ pos_vec: torch.Tensor = cam_params[:, :3]
+ principal_point_offsets: torch.Tensor = torch.zeros(
+ (cam_params.shape[0], 2), dtype=torch.int32, device=cam_params.device
+ )
+ if continuous_rep:
+ rot_vec = cam_params[:, 3:9]
+ focal_length: torch.Tensor = cam_params[:, 9:10]
+ sensor_size_x = cam_params[:, 10:11]
+ if cam_params.shape[1] == 13:
+ principal_point_offsets: torch.Tensor = cam_params[:, 11:13].to(
+ torch.int32
+ )
+ else:
+ rot_vec = cam_params[:, 3:6]
+ focal_length: torch.Tensor = cam_params[:, 6:7]
+ sensor_size_x = cam_params[:, 7:8]
+ if cam_params.shape[1] == 10:
+ principal_point_offsets: torch.Tensor = cam_params[:, 8:10].to(
+ torch.int32
+ )
+ # Always get quadratic pixels.
+ pixel_size_x = sensor_size_x / float(width)
+ sensor_size_y = height * pixel_size_x
+ if continuous_rep:
+ rot_mat = rotation_6d_to_matrix(rot_vec)
+ else:
+ rot_mat = axis_angle_to_matrix(rot_vec)
+ if first_R_then_T:
+ pos_vec = torch.matmul(rot_mat, pos_vec[..., None])[:, :, 0]
+ sensor_dir_x = torch.matmul(
+ rot_mat,
+ torch.tensor(
+ [1.0, 0.0, 0.0], dtype=torch.float32, device=rot_mat.device
+ ).repeat(batch_size, 1)[:, :, None],
+ )[:, :, 0]
+ sensor_dir_y = torch.matmul(
+ rot_mat,
+ torch.tensor(
+ [0.0, -1.0, 0.0], dtype=torch.float32, device=rot_mat.device
+ ).repeat(batch_size, 1)[:, :, None],
+ )[:, :, 0]
+ sensor_dir_z = torch.matmul(
+ rot_mat,
+ torch.tensor(
+ [0.0, 0.0, 1.0], dtype=torch.float32, device=rot_mat.device
+ ).repeat(batch_size, 1)[:, :, None],
+ )[:, :, 0]
+ if right_handed:
+ sensor_dir_z *= -1
+ if orthogonal:
+ sensor_center = pos_vec
+ else:
+ sensor_center = pos_vec + focal_length * sensor_dir_z
+ sensor_luc = ( # Sensor left upper corner.
+ sensor_center
+ - sensor_dir_x * (sensor_size_x / 2.0)
+ - sensor_dir_y * (sensor_size_y / 2.0)
+ )
+ pixel_size_x = sensor_size_x / float(width)
+ pixel_size_y = sensor_size_y / float(height)
+ pixel_vec_x: torch.Tensor = sensor_dir_x * pixel_size_x
+ pixel_vec_y: torch.Tensor = sensor_dir_y * pixel_size_y
+ pixel_0_0_center = sensor_luc + 0.5 * pixel_vec_x + 0.5 * pixel_vec_y
+ # Reduce dimension.
+ focal_length: torch.Tensor = focal_length[:, 0]
+ if batch_processing:
+ return (
+ pos_vec,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_length,
+ principal_point_offsets,
+ )
+ else:
+ return (
+ pos_vec[0],
+ pixel_0_0_center[0],
+ pixel_vec_x[0],
+ pixel_vec_y[0],
+ focal_length[0],
+ principal_point_offsets[0],
+ )
+
+ def forward(
+ self,
+ vert_pos: torch.Tensor,
+ vert_col: torch.Tensor,
+ vert_rad: torch.Tensor,
+ cam_params: torch.Tensor,
+ gamma: float,
+ max_depth: float,
+ min_depth: float = 0.0,
+ bg_col: Optional[torch.Tensor] = None,
+ opacity: Optional[torch.Tensor] = None,
+ percent_allowed_difference: float = 0.01,
+ # pyre-fixme[16]: Module `_C` has no attribute `MAX_UINT`.
+ max_n_hits: int = _C.MAX_UINT,
+ mode: int = 0,
+ return_forward_info: bool = False,
+ first_R_then_T: bool = False,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, Optional[torch.Tensor]]]:
+ """
+ Rendering pass to create an image from the provided spheres and camera
+ parameters.
+
+ Args:
+ * vert_pos: vertex positions. [Bx]Nx3 tensor of positions in 3D space.
+ * vert_col: vertex colors. [Bx]NxK tensor of channels.
+ * vert_rad: vertex radii. [Bx]N tensor of radiuses, >0.
+ * cam_params: camera parameter(s). [Bx]8 tensor, consisting of:
+ - 3 components for camera position,
+ - 3 components for camera rotation (axis angle representation) or
+ 6 components as described in "On the Continuity of Rotation
+ Representations in Neural Networks" (Zhou et al.),
+ - focal length,
+ - the sensor width in world coordinates,
+ - [optional] an offset for the principal point in x, y (no gradients).
+ * gamma: sphere transparency in [1.,1E-5], with 1 being mostly transparent.
+ [Bx]1.
+ * max_depth: maximum depth for spheres to render. Set this as tightly
+ as possible to have good numerical accuracy for gradients.
+ float > min_depth + eps.
+ * min_depth: a float with the minimum depth a sphere must have to be
+ rendered. Must be 0. or > max(focal_length) + eps.
+ * bg_col: K tensor with a background color to use or None (uses all ones).
+ * opacity: [Bx]N tensor of opacity values in [0., 1.] or None (uses all
+ ones).
+ * percent_allowed_difference: a float in [0., 1.[ with the maximum allowed
+ difference in color space. This is used to speed up the
+ computation. Default: 0.01.
+ * max_n_hits: a hard limit on the number of hits per ray. Default: max int.
+ * mode: render mode in {0, 1}. 0: render an image; 1: render the hit map.
+ * return_forward_info: whether to return a second map. This second map
+ contains 13 channels: first channel contains sm_m (the maximum
+ exponent factor observed), the second sm_d (the normalization
+ denominator, the sum of all coefficients), the third the maximum closest
+ possible intersection for a hit. The following channels alternate with
+ the float encoded integer index of a sphere and its weight. They are the
+ five spheres with the highest color contribution to this pixel color,
+ ordered descending. Default: False.
+ * first_R_then_T: bool, whether to first apply rotation to the camera,
+ then translation (PyTorch3D convention). Default: False.
+
+ Returns:
+ * image: [Bx]HxWx3 float tensor with the resulting image.
+ * forw_info: [Bx]HxWx13 float forward information as described above, if
+ enabled.
+ """
+ # The device tracker is registered as buffer.
+ self._renderer.device_tracker = self.device_tracker
+ (
+ pos_vec,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ focal_lengths,
+ principal_point_offsets,
+ ) = Renderer._transform_cam_params(
+ cam_params,
+ self._renderer.width,
+ self._renderer.height,
+ self._renderer.orthogonal,
+ self._renderer.right_handed,
+ first_R_then_T=first_R_then_T,
+ )
+ if (
+ focal_lengths.min().item() > 0.0
+ and max_depth > 10_000.0 * focal_lengths.min().item()
+ ):
+ warnings.warn(
+ (
+ "Extreme ratio of `max_depth` vs. focal length detected "
+ "(%f vs. %f, ratio: %f). This will likely lead to "
+ "artifacts due to numerical instabilities."
+ )
+ % (
+ max_depth,
+ focal_lengths.min().item(),
+ max_depth / focal_lengths.min().item(),
+ )
+ )
+ ret_res = _Render.apply(
+ vert_pos,
+ vert_col,
+ vert_rad,
+ pos_vec,
+ pixel_0_0_center,
+ pixel_vec_x,
+ pixel_vec_y,
+ # Focal length and sensor size don't need gradients other than through
+ # `pixel_vec_x` and `pixel_vec_y`. The focal length is only used in the
+ # renderer to determine the projection areas of the balls.
+ focal_lengths,
+ # principal_point_offsets does not receive gradients.
+ principal_point_offsets,
+ gamma,
+ max_depth,
+ self._renderer,
+ min_depth,
+ bg_col,
+ opacity,
+ percent_allowed_difference,
+ max_n_hits,
+ mode,
+ (mode == 0) and return_forward_info,
+ )
+ if return_forward_info and mode != 0:
+ return ret_res, None
+ return ret_res
+
+ def extra_repr(self) -> str:
+ """Extra information to print in pytorch graphs."""
+ return "width={}, height={}, max_num_balls={}".format(
+ self._renderer.width, self._renderer.height, self._renderer.max_num_balls
+ )
diff --git a/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/unified.py b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/unified.py
new file mode 100644
index 0000000000000000000000000000000000000000..13664d4deb55212ee1d8e0974bed4ede5db02523
--- /dev/null
+++ b/project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/pytorch3d/renderer/points/pulsar/unified.py
@@ -0,0 +1,556 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# pyre-unsafe
+
+import math
+import warnings
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from ...camera_conversions import _pulsar_from_cameras_projection
+from ...cameras import (
+ FoVOrthographicCameras,
+ FoVPerspectiveCameras,
+ OrthographicCameras,
+ PerspectiveCameras,
+)
+from ..compositor import AlphaCompositor, NormWeightedCompositor
+from ..rasterizer import PointsRasterizer
+from .renderer import Renderer as PulsarRenderer
+
+
+def _ensure_float_tensor(val_in, device):
+ """Make sure that the value provided is wrapped a PyTorch float tensor."""
+ if not isinstance(val_in, torch.Tensor):
+ val_out = torch.tensor(val_in, dtype=torch.float32, device=device).reshape((1,))
+ else:
+ val_out = val_in.to(torch.float32).to(device).reshape((1,))
+ return val_out
+
+
+class PulsarPointsRenderer(nn.Module):
+ """
+ This renderer is a PyTorch3D interface wrapper around the pulsar renderer.
+
+ It provides an interface consistent with PyTorch3D Pointcloud rendering.
+ It will extract all necessary information from the rasterizer and compositor
+ objects and convert them to the pulsar required format, then invoke rendering
+ in the pulsar renderer. All gradients are handled appropriately through the
+ wrapper and the wrapper should provide equivalent results to using the pulsar
+ renderer directly.
+ """
+
+ def __init__(
+ self,
+ rasterizer: PointsRasterizer,
+ compositor: Optional[Union[NormWeightedCompositor, AlphaCompositor]] = None,
+ n_channels: int = 3,
+ max_num_spheres: int = int(1e6), # noqa: B008
+ **kwargs,
+ ) -> None:
+ """
+ rasterizer (PointsRasterizer): An object encapsulating rasterization parameters.
+ compositor (ignored): Only keeping this for interface consistency. Default: None.
+ n_channels (int): The number of channels of the resulting image. Default: 3.
+ max_num_spheres (int): The maximum number of spheres intended to render with
+ this renderer. Default: 1e6.
+ kwargs (Any): kwargs to pass on to the pulsar renderer.
+ See `pytorch3d.renderer.points.pulsar.renderer.Renderer` for all options.
+ """
+ super().__init__()
+ self.rasterizer = rasterizer
+ if compositor is not None:
+ warnings.warn(
+ "Creating a `PulsarPointsRenderer` with a compositor object! "
+ "This object is ignored and just allowed as an argument for interface "
+ "compatibility."
+ )
+ # Initialize the pulsar renderers.
+ if not isinstance(
+ rasterizer.cameras,
+ (
+ FoVOrthographicCameras,
+ FoVPerspectiveCameras,
+ PerspectiveCameras,
+ OrthographicCameras,
+ ),
+ ):
+ raise ValueError(
+ "Only FoVPerspectiveCameras, PerspectiveCameras, "
+ "FoVOrthographicCameras and OrthographicCameras are supported "
+ "by the pulsar backend."
+ )
+ if isinstance(rasterizer.raster_settings.image_size, tuple):
+ height, width = rasterizer.raster_settings.image_size
+ else:
+ width = rasterizer.raster_settings.image_size
+ height = rasterizer.raster_settings.image_size
+ # Making sure about integer types.
+ width = int(width)
+ height = int(height)
+ max_num_spheres = int(max_num_spheres)
+ orthogonal_projection = isinstance(
+ rasterizer.cameras, (FoVOrthographicCameras, OrthographicCameras)
+ )
+ n_channels = int(n_channels)
+ self.renderer = PulsarRenderer(
+ width=width,
+ height=height,
+ max_num_balls=max_num_spheres,
+ orthogonal_projection=orthogonal_projection,
+ right_handed_system=False,
+ n_channels=n_channels,
+ **kwargs,
+ )
+
+ def _conf_check(self, point_clouds, kwargs: Dict[str, Any]) -> bool:
+ """
+ Verify internal configuration state with kwargs and pointclouds.
+
+ This method will raise ValueError's for any inconsistencies found. It
+ returns whether an orthogonal projection will be used.
+ """
+ if "gamma" not in kwargs.keys():
+ raise ValueError(
+ "gamma is a required keyword argument for the PulsarPointsRenderer!"
+ )
+ if (
+ len(point_clouds) != len(self.rasterizer.cameras)
+ and len(self.rasterizer.cameras) != 1
+ ):
+ raise ValueError(
+ (
+ "The len(point_clouds) must either be equal to len(rasterizer.cameras) or "
+ "only one camera must be used. len(point_clouds): %d, "
+ "len(rasterizer.cameras): %d."
+ )
+ % (
+ len(point_clouds),
+ len(self.rasterizer.cameras),
+ )
+ )
+ # Make sure the rasterizer and cameras objects have no
+ # changes that can't be matched.
+ orthogonal_projection = isinstance(
+ self.rasterizer.cameras, (FoVOrthographicCameras, OrthographicCameras)
+ )
+ if orthogonal_projection != self.renderer._renderer.orthogonal:
+ raise ValueError(
+ "The camera type can not be changed after renderer initialization! "
+ "Current camera orthogonal: %r. Original orthogonal: %r."
+ ) % (orthogonal_projection, self.renderer._renderer.orthogonal)
+ image_size = self.rasterizer.raster_settings.image_size
+ if isinstance(image_size, tuple):
+ expected_height, expected_width = image_size
+ else:
+ expected_height = expected_width = image_size
+ if expected_width != self.renderer._renderer.width:
+ raise ValueError(
+ (
+ "The rasterizer width can not be changed after renderer "
+ "initialization! Current width: %s. Original width: %d."
+ )
+ % (
+ expected_width,
+ self.renderer._renderer.width,
+ )
+ )
+ if expected_height != self.renderer._renderer.height:
+ raise ValueError(
+ (
+ "The rasterizer height can not be changed after renderer "
+ "initialization! Current height: %s. Original height: %d."
+ )
+ % (
+ expected_height,
+ self.renderer._renderer.height,
+ )
+ )
+ return orthogonal_projection
+
+ def _extract_intrinsics( # noqa: C901
+ self, orthogonal_projection, kwargs, cloud_idx, device
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, float, float]:
+ """
+ Translate the camera intrinsics from PyTorch3D format to pulsar format.
+ """
+ # Shorthand:
+ cameras = self.rasterizer.cameras
+ if orthogonal_projection:
+ focal_length = torch.zeros((1,), dtype=torch.float32)
+ if isinstance(cameras, FoVOrthographicCameras):
+ znear = kwargs.get("znear", cameras.znear)[cloud_idx]
+ zfar = kwargs.get("zfar", cameras.zfar)[cloud_idx]
+ max_y = kwargs.get("max_y", cameras.max_y)[cloud_idx]
+ min_y = kwargs.get("min_y", cameras.min_y)[cloud_idx]
+ max_x = kwargs.get("max_x", cameras.max_x)[cloud_idx]
+ min_x = kwargs.get("min_x", cameras.min_x)[cloud_idx]
+ if max_y != -min_y:
+ raise ValueError(
+ "The orthographic camera must be centered around 0. "
+ f"Max is {max_y} and min is {min_y}."
+ )
+ if max_x != -min_x:
+ raise ValueError(
+ "The orthographic camera must be centered around 0. "
+ f"Max is {max_x} and min is {min_x}."
+ )
+ if not torch.all(
+ kwargs.get("scale_xyz", cameras.scale_xyz)[cloud_idx] == 1.0
+ ):
+ raise ValueError(
+ "The orthographic camera scale must be ((1.0, 1.0, 1.0),). "
+ f"{kwargs.get('scale_xyz', cameras.scale_xyz)[cloud_idx]}."
+ )
+ sensor_width = max_x - min_x
+ if not sensor_width > 0.0:
+ raise ValueError(
+ f"The orthographic camera must have positive size! Is: {sensor_width}." # noqa: B950
+ )
+ principal_point_x, principal_point_y = (
+ torch.zeros((1,), dtype=torch.float32),
+ torch.zeros((1,), dtype=torch.float32),
+ )
+ else:
+ # Currently, this means it must be an 'OrthographicCameras' object.
+ focal_length_conf = kwargs.get("focal_length", cameras.focal_length)[
+ cloud_idx
+ ]
+ if (
+ focal_length_conf.numel() == 2
+ and focal_length_conf[0] * self.renderer._renderer.width
+ - focal_length_conf[1] * self.renderer._renderer.height
+ > 1e-5
+ ):
+ raise ValueError(
+ "Pulsar only supports a single focal length! "
+ "Provided: %s." % (str(focal_length_conf))
+ )
+ if focal_length_conf.numel() == 2:
+ sensor_width = 2.0 / focal_length_conf[0]
+ else:
+ if focal_length_conf.numel() != 1:
+ raise ValueError(
+ "Focal length not parsable: %s." % (str(focal_length_conf))
+ )
+ sensor_width = 2.0 / focal_length_conf
+ if "znear" not in kwargs.keys() or "zfar" not in kwargs.keys():
+ raise ValueError(
+ "pulsar needs znear and zfar values for "
+ "the OrthographicCameras. Please provide them as keyword "
+ "argument to the forward method."
+ )
+ znear = kwargs["znear"][cloud_idx]
+ zfar = kwargs["zfar"][cloud_idx]
+ principal_point_x = (
+ kwargs.get("principal_point", cameras.principal_point)[cloud_idx][0]
+ * 0.5
+ * self.renderer._renderer.width
+ )
+ principal_point_y = (
+ kwargs.get("principal_point", cameras.principal_point)[cloud_idx][1]
+ * 0.5
+ * self.renderer._renderer.height
+ )
+ else:
+ if not isinstance(cameras, PerspectiveCameras):
+ # Create a virtual focal length that is closer than znear.
+ znear = kwargs.get("znear", cameras.znear)[cloud_idx]
+ zfar = kwargs.get("zfar", cameras.zfar)[cloud_idx]
+ focal_length = znear - 1e-6
+ # Create a sensor size that matches the expected fov assuming this f.
+ afov = kwargs.get("fov", cameras.fov)[cloud_idx]
+ if kwargs.get("degrees", cameras.degrees):
+ afov *= math.pi / 180.0
+ sensor_width = math.tan(afov / 2.0) * 2.0 * focal_length
+ if not (
+ kwargs.get("aspect_ratio", cameras.aspect_ratio)[cloud_idx]
+ - self.renderer._renderer.width / self.renderer._renderer.height
+ < 1e-6
+ ):
+ raise ValueError(
+ "The aspect ratio ("
+ f"{kwargs.get('aspect_ratio', cameras.aspect_ratio)[cloud_idx]}) "
+ "must agree with the resolution width / height ("
+ f"{self.renderer._renderer.width / self.renderer._renderer.height})." # noqa: B950
+ )
+ principal_point_x, principal_point_y = (
+ torch.zeros((1,), dtype=torch.float32),
+ torch.zeros((1,), dtype=torch.float32),
+ )
+ else:
+ focal_length_conf = kwargs.get("focal_length", cameras.focal_length)[
+ cloud_idx
+ ]
+ if (
+ focal_length_conf.numel() == 2
+ and focal_length_conf[0] * self.renderer._renderer.width
+ - focal_length_conf[1] * self.renderer._renderer.height
+ > 1e-5
+ ):
+ raise ValueError(
+ "Pulsar only supports a single focal length! "
+ "Provided: %s." % (str(focal_length_conf))
+ )
+ if "znear" not in kwargs.keys() or "zfar" not in kwargs.keys():
+ raise ValueError(
+ "pulsar needs znear and zfar values for "
+ "the PerspectiveCameras. Please provide them as keyword "
+ "argument to the forward method."
+ )
+ znear = kwargs["znear"][cloud_idx]
+ zfar = kwargs["zfar"][cloud_idx]
+ if focal_length_conf.numel() == 2:
+ focal_length_px = focal_length_conf[0]
+ else:
+ if focal_length_conf.numel() != 1:
+ raise ValueError(
+ "Focal length not parsable: %s." % (str(focal_length_conf))
+ )
+ focal_length_px = focal_length_conf
+ focal_length = torch.tensor(
+ [
+ znear - 1e-6,
+ ],
+ dtype=torch.float32,
+ device=focal_length_px.device,
+ )
+ sensor_width = focal_length / focal_length_px * 2.0
+ principal_point_x = (
+ kwargs.get("principal_point", cameras.principal_point)[cloud_idx][0]
+ * 0.5
+ * self.renderer._renderer.width
+ )
+ principal_point_y = (
+ kwargs.get("principal_point", cameras.principal_point)[cloud_idx][1]
+ * 0.5
+ * self.renderer._renderer.height
+ )
+ focal_length = _ensure_float_tensor(focal_length, device)
+ sensor_width = _ensure_float_tensor(sensor_width, device)
+ principal_point_x = _ensure_float_tensor(principal_point_x, device)
+ principal_point_y = _ensure_float_tensor(principal_point_y, device)
+ znear = _ensure_float_tensor(znear, device)
+ zfar = _ensure_float_tensor(zfar, device)
+ return (
+ focal_length,
+ sensor_width,
+ principal_point_x,
+ principal_point_y,
+ znear,
+ zfar,
+ )
+
+ def _extract_extrinsics(
+ self, kwargs, cloud_idx
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Extract the extrinsic information from the kwargs for a specific point cloud.
+
+ Instead of implementing a direct translation from the PyTorch3D to the Pulsar
+ camera model, we chain the two conversions of PyTorch3D->OpenCV and
+ OpenCV->Pulsar for better maintainability (PyTorch3D->OpenCV is maintained and
+ tested by the core PyTorch3D team, whereas OpenCV->Pulsar is maintained and
+ tested by the Pulsar team).
+ """
+ # Shorthand:
+ cameras = self.rasterizer.cameras
+ R = kwargs.get("R", cameras.R)[cloud_idx]
+ T = kwargs.get("T", cameras.T)[cloud_idx]
+ tmp_cams = PerspectiveCameras(
+ R=R.unsqueeze(0), T=T.unsqueeze(0), device=R.device
+ )
+ size_tensor = torch.tensor(
+ [[self.renderer._renderer.height, self.renderer._renderer.width]]
+ )
+ pulsar_cam = _pulsar_from_cameras_projection(tmp_cams, size_tensor)
+ cam_pos = pulsar_cam[0, :3]
+ cam_rot = pulsar_cam[0, 3:9]
+ return cam_pos, cam_rot
+
+ def _get_vert_rad(
+ self, vert_pos, cam_pos, orthogonal_projection, focal_length, kwargs, cloud_idx
+ ) -> torch.Tensor:
+ """
+ Get point radiuses.
+
+ These can be depending on the camera position in case of a perspective
+ transform.
+ """
+ # Normalize point radiuses.
+ # `self.rasterizer.raster_settings.radius` can either be a float
+ # or itself a tensor.
+ raster_rad = self.rasterizer.raster_settings.radius
+ if kwargs.get("radius_world", False):
+ return raster_rad
+ if (
+ isinstance(raster_rad, torch.Tensor)
+ and raster_rad.numel() > 1
+ and raster_rad.ndim > 1
+ ):
+ # In this case it must be a batched torch tensor.
+ raster_rad = raster_rad[cloud_idx]
+ if orthogonal_projection:
+ vert_rad = (
+ torch.ones(
+ (vert_pos.shape[0],), dtype=torch.float32, device=vert_pos.device
+ )
+ * raster_rad
+ )
+ else:
+ point_dists = torch.norm((vert_pos - cam_pos), p=2, dim=1, keepdim=False)
+ vert_rad = raster_rad / focal_length.to(vert_pos.device) * point_dists
+ if isinstance(self.rasterizer.cameras, PerspectiveCameras):
+ # NDC normalization happens through adjusted focal length.
+ pass
+ else:
+ vert_rad = vert_rad / 2.0 # NDC normalization.
+ return vert_rad
+
+ # point_clouds is not typed to avoid a cyclic dependency.
+ def forward(self, point_clouds, **kwargs) -> torch.Tensor:
+ """
+ Get the rendering of the provided `Pointclouds`.
+
+ The number of point clouds in the `Pointclouds` object determines the
+ number of resulting images. The provided cameras can be either 1 or equal
+ to the number of pointclouds (in the first case, the same camera will be
+ used for all clouds, in the latter case each point cloud will be rendered
+ with the corresponding camera).
+
+ The following kwargs are support from PyTorch3D (depending on the selected
+ camera model potentially overriding camera parameters):
+ radius_world (bool): use the provided radiuses from the raster_settings
+ plain as radiuses in world space. Default: False.
+ znear (Iterable[float]): near geometry cutoff. Is required for
+ OrthographicCameras and PerspectiveCameras.
+ zfar (Iterable[float]): far geometry cutoff. Is required for
+ OrthographicCameras and PerspectiveCameras.
+ R (torch.Tensor): [Bx3x3] camera rotation matrices.
+ T (torch.Tensor): [Bx3] camera translation vectors.
+ principal_point (torch.Tensor): [Bx2] camera intrinsic principal
+ point offset vectors.
+ focal_length (torch.Tensor): [Bx1] camera intrinsic focal lengths.
+ aspect_ratio (Iterable[float]): camera aspect ratios.
+ fov (Iterable[float]): camera FOVs.
+ degrees (bool): whether FOVs are specified in degrees or
+ radians.
+ min_x (Iterable[float]): minimum x for the FoVOrthographicCameras.
+ max_x (Iterable[float]): maximum x for the FoVOrthographicCameras.
+ min_y (Iterable[float]): minimum y for the FoVOrthographicCameras.
+ max_y (Iterable[float]): maximum y for the FoVOrthographicCameras.
+
+ The following kwargs are supported from pulsar:
+ gamma (float): The gamma value to use. This defines the transparency for
+ differentiability (see pulsar paper for details). Must be in [1., 1e-5]
+ with 1.0 being mostly transparent. This keyword argument is *required*!
+ bg_col (torch.Tensor): The background color. Must be a tensor on the same
+ device as the point clouds, with as many channels as features (no batch
+ dimension - it is the same for all images in the batch).
+ Default: 0.0 for all channels.
+ percent_allowed_difference (float): a value in [0., 1.[ with the maximum
+ allowed difference in channel space. This is used to speed up the
+ computation. Default: 0.01.
+ max_n_hits (int): a hard limit on the number of sphere hits per ray.
+ Default: max int.
+ mode (int): render mode in {0, 1}. 0: render image; 1: render hit map.
+ """
+ orthogonal_projection: bool = self._conf_check(point_clouds, kwargs)
+ # Get access to inputs. We're using the list accessor and process
+ # them sequentially.
+ position_list = point_clouds.points_list()
+ features_list = point_clouds.features_list()
+ # Result list.
+ images = []
+ for cloud_idx, (vert_pos, vert_col) in enumerate(
+ zip(position_list, features_list)
+ ):
+ # Get extrinsics.
+ cam_pos, cam_rot = self._extract_extrinsics(kwargs, cloud_idx)
+ # Get intrinsics.
+ (
+ focal_length,
+ sensor_width,
+ principal_point_x,
+ principal_point_y,
+ znear,
+ zfar,
+ ) = self._extract_intrinsics(
+ orthogonal_projection, kwargs, cloud_idx, cam_pos.device
+ )
+ # Put everything together.
+ cam_params = torch.cat(
+ (
+ cam_pos,
+ cam_rot.to(cam_pos.device),
+ torch.cat(
+ [
+ focal_length,
+ sensor_width,
+ principal_point_x,
+ principal_point_y,
+ ],
+ ),
+ )
+ )
+ # Get point radiuses (can depend on camera position).
+ vert_rad = self._get_vert_rad(
+ vert_pos,
+ cam_pos,
+ orthogonal_projection,
+ focal_length,
+ kwargs,
+ cloud_idx,
+ )
+ # Clean kwargs for passing on.
+ gamma = kwargs["gamma"][cloud_idx]
+ if "first_R_then_T" in kwargs.keys():
+ raise ValueError("`first_R_then_T` is not supported in this interface.")
+ otherargs = {
+ argn: argv
+ for argn, argv in kwargs.items()
+ if argn
+ not in [
+ "radius_world",
+ "gamma",
+ "znear",
+ "zfar",
+ "R",
+ "T",
+ "principal_point",
+ "focal_length",
+ "aspect_ratio",
+ "fov",
+ "degrees",
+ "min_x",
+ "max_x",
+ "min_y",
+ "max_y",
+ ]
+ }
+ # background color
+ if "bg_col" not in otherargs:
+ bg_col = torch.zeros(
+ vert_col.shape[1], device=cam_params.device, dtype=torch.float32
+ )
+ otherargs["bg_col"] = bg_col
+ # Go!
+ images.append(
+ self.renderer(
+ vert_pos=vert_pos,
+ vert_col=vert_col,
+ vert_rad=vert_rad,
+ cam_params=cam_params,
+ gamma=gamma,
+ max_depth=zfar,
+ min_depth=znear,
+ **otherargs,
+ ).flip(dims=[0])
+ )
+ return torch.stack(images, dim=0)