diff --git a/src/misc/LocalLogger.py b/src/misc/LocalLogger.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5c95606f287328cfda17b78896e3431f02ea28 --- /dev/null +++ b/src/misc/LocalLogger.py @@ -0,0 +1,48 @@ +import os +from pathlib import Path +from typing import Any, Optional + +from lightning.pytorch.loggers.logger import Logger +from lightning.pytorch.utilities import rank_zero_only +from PIL import Image + +LOG_PATH = Path("outputs/local") + + +class LocalLogger(Logger): + def __init__(self) -> None: + super().__init__() + self.experiment = None + os.system(f"rm -r {LOG_PATH}") + + @property + def name(self): + return "LocalLogger" + + @property + def version(self): + return 0 + + @rank_zero_only + def log_hyperparams(self, params): + pass + + @rank_zero_only + def log_metrics(self, metrics, step): + pass + + @rank_zero_only + def log_image( + self, + key: str, + images: list[Any], + step: Optional[int] = None, + **kwargs, + ): + # The function signature is the same as the wandb logger's, but the step is + # actually required. + assert step is not None + for index, image in enumerate(images): + path = LOG_PATH / f"{key}/{index:0>2}_{step:0>6}.jpg" + path.parent.mkdir(exist_ok=True, parents=True) + Image.fromarray(image).save(path) diff --git a/src/misc/image_io.py b/src/misc/image_io.py new file mode 100644 index 0000000000000000000000000000000000000000..e16b05b7112170eed69d026d31f953e2319e06d1 --- /dev/null +++ b/src/misc/image_io.py @@ -0,0 +1,211 @@ +import io +import os +from pathlib import Path +from typing import Union + +import cv2 +import numpy as np +import skvideo +import torch +import torchvision.transforms as tf +from einops import rearrange, repeat +from jaxtyping import Float, UInt8 + +from matplotlib import pyplot as plt +from matplotlib.figure import Figure +from PIL import Image +from torch import Tensor + +FloatImage = Union[ + Float[Tensor, "height width"], + Float[Tensor, "channel height width"], + Float[Tensor, "batch channel height width"], +] + + +def fig_to_image( + fig: Figure, + dpi: int = 100, + device: torch.device = torch.device("cpu"), +) -> Float[Tensor, "3 height width"]: + buffer = io.BytesIO() + fig.savefig(buffer, format="raw", dpi=dpi) + buffer.seek(0) + data = np.frombuffer(buffer.getvalue(), dtype=np.uint8) + h = int(fig.bbox.bounds[3]) + w = int(fig.bbox.bounds[2]) + data = rearrange(data, "(h w c) -> c h w", h=h, w=w, c=4) + buffer.close() + return (torch.tensor(data, device=device, dtype=torch.float32) / 255)[:3] + + +def prep_image(image: FloatImage) -> UInt8[np.ndarray, "height width channel"]: + # Handle batched images. + if image.ndim == 4: + image = rearrange(image, "b c h w -> c h (b w)") + + # Handle single-channel images. + if image.ndim == 2: + image = rearrange(image, "h w -> () h w") + + # Ensure that there are 3 or 4 channels. + channel, _, _ = image.shape + if channel == 1: + image = repeat(image, "() h w -> c h w", c=3) + assert image.shape[0] in (3, 4) + + image = (image.detach().clip(min=0, max=1) * 255).type(torch.uint8) + return rearrange(image, "c h w -> h w c").cpu().numpy() + + +def save_image( + image: FloatImage, + path: Union[Path, str], +) -> None: + """Save an image. Assumed to be in range 0-1.""" + + # Create the parent directory if it doesn't already exist. + path = Path(path) + path.parent.mkdir(exist_ok=True, parents=True) + + # Save the image. + Image.fromarray(prep_image(image)).save(path) + + +def load_image( + path: Union[Path, str], +) -> Float[Tensor, "3 height width"]: + return tf.ToTensor()(Image.open(path))[:3] + + +def save_video(tensor, save_path, fps=10): + """ + Save a tensor of shape (N, C, H, W) as a video file using imageio. + Args: + tensor: Tensor of shape (N, C, H, W) in range [0, 1] + save_path: Path to save the video file + fps: Frames per second for the video + """ + # Convert tensor to numpy array and adjust dimensions + video = tensor.cpu().detach().numpy() # (N, C, H, W) + video = np.transpose(video, (0, 2, 3, 1)) # (N, H, W, C) + + # Scale to [0, 255] and convert to uint8 + video = (video * 255).astype(np.uint8) + + # Ensure the directory exists + import os + + os.makedirs(os.path.dirname(save_path), exist_ok=True) + + # Use imageio to write video (handles codec compatibility automatically) + import imageio + + writer = imageio.get_writer(save_path, fps=fps) + + for frame in video: + writer.append_data(frame) + + writer.close() + + +def save_interpolated_video( + pred_extrinsics, pred_intrinsics, b, h, w, gaussians, save_path, decoder_func, t=10 +): + # Interpolate between neighboring frames + # t: Number of extra views to interpolate between each pair + interpolated_extrinsics = [] + interpolated_intrinsics = [] + + # For each pair of neighboring frame + for i in range(pred_extrinsics.shape[1] - 1): + # Add the current frame + interpolated_extrinsics.append(pred_extrinsics[:, i : i + 1]) + interpolated_intrinsics.append(pred_intrinsics[:, i : i + 1]) + + # Interpolate between current and next frame + for j in range(1, t + 1): + alpha = j / (t + 1) + + # Interpolate extrinsics + start_extrinsic = pred_extrinsics[:, i] + end_extrinsic = pred_extrinsics[:, i + 1] + + # Separate rotation and translation + start_rot = start_extrinsic[:, :3, :3] + end_rot = end_extrinsic[:, :3, :3] + start_trans = start_extrinsic[:, :3, 3] + end_trans = end_extrinsic[:, :3, 3] + + # Interpolate translation (linear) + interp_trans = (1 - alpha) * start_trans + alpha * end_trans + + # Interpolate rotation (spherical) + start_rot_flat = start_rot.reshape(b, 9) + end_rot_flat = end_rot.reshape(b, 9) + interp_rot_flat = (1 - alpha) * start_rot_flat + alpha * end_rot_flat + interp_rot = interp_rot_flat.reshape(b, 3, 3) + + # Normalize rotation matrix to ensure it's orthogonal + u, _, v = torch.svd(interp_rot) + interp_rot = torch.bmm(u, v.transpose(1, 2)) + + # Combine interpolated rotation and translation + interp_extrinsic = ( + torch.eye(4, device=pred_extrinsics.device).unsqueeze(0).repeat(b, 1, 1) + ) + interp_extrinsic[:, :3, :3] = interp_rot + interp_extrinsic[:, :3, 3] = interp_trans + + # Interpolate intrinsics (linear) + start_intrinsic = pred_intrinsics[:, i] + end_intrinsic = pred_intrinsics[:, i + 1] + interp_intrinsic = (1 - alpha) * start_intrinsic + alpha * end_intrinsic + + # Add interpolated frame + interpolated_extrinsics.append(interp_extrinsic.unsqueeze(1)) + interpolated_intrinsics.append(interp_intrinsic.unsqueeze(1)) + + # Concatenate all frames + pred_all_extrinsic = torch.cat(interpolated_extrinsics, dim=1) + pred_all_intrinsic = torch.cat(interpolated_intrinsics, dim=1) + + # Add the last frame + interpolated_extrinsics.append(pred_all_extrinsic[:, -1:]) + interpolated_intrinsics.append(pred_all_intrinsic[:, -1:]) + + # Update K to reflect the new number of frames + num_frames = pred_all_extrinsic.shape[1] + + # Render interpolated views + interpolated_output = decoder_func.forward( + gaussians, + pred_all_extrinsic, + pred_all_intrinsic.float(), + torch.ones(1, num_frames, device=pred_all_extrinsic.device) * 0.1, + torch.ones(1, num_frames, device=pred_all_extrinsic.device) * 100, + (h, w), + ) + + # Convert to video format + video = interpolated_output.color[0].clip(min=0, max=1) + depth = interpolated_output.depth[0] + + # Normalize depth for visualization + # to avoid `quantile() input tensor is too large` + num_views = pred_extrinsics.shape[1] + depth_norm = (depth - depth[::num_views].quantile(0.01)) / ( + depth[::num_views].quantile(0.99) - depth[::num_views].quantile(0.01) + ) + depth_norm = plt.cm.turbo(depth_norm.cpu().numpy()) + depth_colored = ( + torch.from_numpy(depth_norm[..., :3]).permute(0, 3, 1, 2).to(depth.device) + ) + depth_colored = depth_colored.clip(min=0, max=1) + + # Save depth video + save_video(depth_colored, os.path.join(save_path, f"depth.mp4")) + # Save video + save_video(video, os.path.join(save_path, f"rgb.mp4")) + + return os.path.join(save_path, f"rgb.mp4"), os.path.join(save_path, f"depth.mp4") diff --git a/src/misc/nn_module_tools.py b/src/misc/nn_module_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a4a41b95b45cf1cd2f2c0b4d2b8ad36937dce0 --- /dev/null +++ b/src/misc/nn_module_tools.py @@ -0,0 +1,16 @@ +from torch import nn + + +def convert_to_buffer(module: nn.Module, persistent: bool = True): + # Recurse over child modules. + for name, child in list(module.named_children()): + convert_to_buffer(child, persistent) + + # Also re-save buffers to change persistence. + for name, parameter_or_buffer in ( + *module.named_parameters(recurse=False), + *module.named_buffers(recurse=False), + ): + value = parameter_or_buffer.detach().clone() + delattr(module, name) + module.register_buffer(name, value, persistent=persistent) diff --git a/src/misc/sh_rotation.py b/src/misc/sh_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..c22ce73b102414e5da49ebd96dfca18cd3015c65 --- /dev/null +++ b/src/misc/sh_rotation.py @@ -0,0 +1,111 @@ +from math import isqrt + +import torch +from e3nn.o3 import matrix_to_angles, wigner_D +from einops import einsum +from jaxtyping import Float +from torch import Tensor + + +def rotate_sh( + sh_coefficients: Float[Tensor, "*#batch n"], + rotations: Float[Tensor, "*#batch 3 3"], +) -> Float[Tensor, "*batch n"]: + device = sh_coefficients.device + dtype = sh_coefficients.dtype + + # change the basis from YZX -> XYZ to fit the convention of e3nn + P = torch.tensor([[0, 0, 1], [1, 0, 0], [0, 1, 0]], + dtype=sh_coefficients.dtype, device=sh_coefficients.device) + inversed_P = torch.tensor([[0, 1, 0], [0, 0, 1], [1, 0, 0], ], + dtype=sh_coefficients.dtype, device=sh_coefficients.device) + permuted_rotation_matrix = inversed_P @ rotations @ P + + *_, n = sh_coefficients.shape + alpha, beta, gamma = matrix_to_angles(permuted_rotation_matrix) + result = [] + for degree in range(isqrt(n)): + with torch.device(device): + sh_rotations = wigner_D(degree, alpha, -beta, gamma).type(dtype) + sh_rotated = einsum( + sh_rotations, + sh_coefficients[..., degree**2 : (degree + 1) ** 2], + "... i j, ... j -> ... i", + ) + result.append(sh_rotated) + + return torch.cat(result, dim=-1) + + +# def rotate_sh( +# sh_coefficients: Float[Tensor, "*#batch n"], +# rotations: Float[Tensor, "*#batch 3 3"], +# ) -> Float[Tensor, "*batch n"]: +# device = sh_coefficients.device +# dtype = sh_coefficients.dtype +# +# *_, n = sh_coefficients.shape +# alpha, beta, gamma = matrix_to_angles(rotations) +# result = [] +# for degree in range(isqrt(n)): +# with torch.device(device): +# sh_rotations = wigner_D(degree, alpha, beta, gamma).type(dtype) +# sh_rotated = einsum( +# sh_rotations, +# sh_coefficients[..., degree**2 : (degree + 1) ** 2], +# "... i j, ... j -> ... i", +# ) +# result.append(sh_rotated) +# +# return torch.cat(result, dim=-1) + + +if __name__ == "__main__": + from pathlib import Path + + import matplotlib.pyplot as plt + from e3nn.o3 import spherical_harmonics + from matplotlib import cm + from scipy.spatial.transform.rotation import Rotation as R + + device = torch.device("cuda") + + # Generate random spherical harmonics coefficients. + degree = 4 + coefficients = torch.rand((degree + 1) ** 2, dtype=torch.float32, device=device) + + def plot_sh(sh_coefficients, path: Path) -> None: + phi = torch.linspace(0, torch.pi, 100, device=device) + theta = torch.linspace(0, 2 * torch.pi, 100, device=device) + phi, theta = torch.meshgrid(phi, theta, indexing="xy") + x = torch.sin(phi) * torch.cos(theta) + y = torch.sin(phi) * torch.sin(theta) + z = torch.cos(phi) + xyz = torch.stack([x, y, z], dim=-1) + sh = spherical_harmonics(list(range(degree + 1)), xyz, True) + result = einsum(sh, sh_coefficients, "... n, n -> ...") + result = (result - result.min()) / (result.max() - result.min()) + + # Set the aspect ratio to 1 so our sphere looks spherical + fig = plt.figure(figsize=plt.figaspect(1.0)) + ax = fig.add_subplot(111, projection="3d") + ax.plot_surface( + x.cpu().numpy(), + y.cpu().numpy(), + z.cpu().numpy(), + rstride=1, + cstride=1, + facecolors=cm.seismic(result.cpu().numpy()), + ) + # Turn off the axis planes + ax.set_axis_off() + path.parent.mkdir(exist_ok=True, parents=True) + plt.savefig(path) + + for i, angle in enumerate(torch.linspace(0, 2 * torch.pi, 30)): + rotation = torch.tensor( + R.from_euler("x", angle.item()).as_matrix(), device=device + ) + plot_sh(rotate_sh(coefficients, rotation), Path(f"sh_rotation/{i:0>3}.png")) + + print("Done!") diff --git a/src/misc/sht.py b/src/misc/sht.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf8cf266cdc473e0d8a3e09de998cb845e3373d --- /dev/null +++ b/src/misc/sht.py @@ -0,0 +1,1637 @@ +"""Real spherical harmonics in Cartesian form for PyTorch. + +This is an autogenerated file. See +https://github.com/cheind/torch-spherical-harmonics +for more information. +""" + +import torch + + +def rsh_cart_0(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 0. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,1) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + ], + -1, + ) + + +def rsh_cart_1(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 1. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,4) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + ], + -1, + ) + + +def rsh_cart_2(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 2. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,9) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + ], + -1, + ) + + +def rsh_cart_3(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 3. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,16) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + ], + -1, + ) + + +def rsh_cart_4(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 4. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,25) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + ], + -1, + ) + + +def rsh_cart_5(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 5. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,36) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + ], + -1, + ) + + +def rsh_cart_6(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 6. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,49) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + ], + -1, + ) + + +def rsh_cart_7(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 7. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,64) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + z4 = z2**2 + + return torch.stack( + [ + xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + -0.707162732524596 + * y + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 9.98394571852353e-5 + * y + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00239614697244565 + * xy + * (x2 - y2) + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z), + 0.00397356022507413 + * y + * (3.0 * x2 - y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.0561946276120613 + * xy + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.206472245902897 + * y + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 1.24862677781952 * z * (1.5 * z2 - 0.5) + - 1.68564615005635 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 2.02901851395672 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.499450711127808 * z, + 0.206472245902897 + * x + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 0.0280973138060306 + * (x2 - y2) + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.00397356022507413 + * x + * (x2 - 3.0 * y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.000599036743111412 + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + * (-6.0 * x2 * y2 + x4 + y4), + 9.98394571852353e-5 + * x + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -0.707162732524596 + * x + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + ], + -1, + ) + + +# @torch.jit.script +def rsh_cart_8(xyz: torch.Tensor): + """Computes all real spherical harmonics up to degree 8. + + This is an autogenerated method. See + https://github.com/cheind/torch-spherical-harmonics + for more information. + + Params: + xyz: (N,...,3) tensor of points on the unit sphere + + Returns: + rsh: (N,...,81) real spherical harmonics + projections of input. Ynm is found at index + `n*(n+1) + m`, with `0 <= n <= degree` and + `-n <= m <= n`. + """ + x = xyz[..., 0] + y = xyz[..., 1] + z = xyz[..., 2] + + x2 = x**2 + y2 = y**2 + z2 = z**2 + xy = x * y + xz = x * z + yz = y * z + x4 = x2**2 + y4 = y2**2 + # z4 = z2**2 + return torch.stack( + [ + 0.282094791773878 * torch.ones(1, device=xyz.device).expand(xyz.shape[:-1]), + -0.48860251190292 * y, + 0.48860251190292 * z, + -0.48860251190292 * x, + 1.09254843059208 * xy, + -1.09254843059208 * yz, + 0.94617469575756 * z2 - 0.31539156525252, + -1.09254843059208 * xz, + 0.54627421529604 * x2 - 0.54627421529604 * y2, + -0.590043589926644 * y * (3.0 * x2 - y2), + 2.89061144264055 * xy * z, + 0.304697199642977 * y * (1.5 - 7.5 * z2), + 1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z, + 0.304697199642977 * x * (1.5 - 7.5 * z2), + 1.44530572132028 * z * (x2 - y2), + -0.590043589926644 * x * (x2 - 3.0 * y2), + 2.5033429417967 * xy * (x2 - y2), + -1.77013076977993 * yz * (3.0 * x2 - y2), + 0.126156626101008 * xy * (52.5 * z2 - 7.5), + 0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 1.48099765681286 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 0.952069922236839 * z2 + + 0.317356640745613, + 0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z), + 0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5), + -1.77013076977993 * xz * (x2 - 3.0 * y2), + -3.75501441269506 * x2 * y2 + + 0.625835735449176 * x4 + + 0.625835735449176 * y4, + -0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 8.30264925952416 * xy * z * (x2 - y2), + 0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2), + 0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.241571547304372 + * y + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + -1.24747010616985 * z * (1.5 * z2 - 0.5) + + 1.6840846433293 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.498988042467941 * z, + 0.241571547304372 + * x + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ), + 0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z), + 0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2), + 2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4), + -0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 4.09910463115149 * x**4 * xy + - 13.6636821038383 * xy**3 + + 4.09910463115149 * xy * y**4, + -2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5), + 0.00584892228263444 + * y + * (3.0 * x2 - y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0701870673916132 + * xy + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.221950995245231 + * y + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + -1.48328138624466 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.86469659985043 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.953538034014426 * z2 + - 0.317846011338142, + 0.221950995245231 + * x + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ), + 0.0350935336958066 + * (x2 - y2) + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ), + 0.00584892228263444 + * x + * (x2 - 3.0 * y2) + * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z), + 0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4), + -2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 0.683184105191914 * x2**3 + + 10.2477615778787 * x2 * y4 + - 10.2477615778787 * x4 * y2 + - 0.683184105191914 * y2**3, + -0.707162732524596 + * y + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 9.98394571852353e-5 + * y + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00239614697244565 + * xy + * (x2 - y2) + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z), + 0.00397356022507413 + * y + * (3.0 * x2 - y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.0561946276120613 + * xy + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.206472245902897 + * y + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 1.24862677781952 * z * (1.5 * z2 - 0.5) + - 1.68564615005635 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 2.02901851395672 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.499450711127808 * z, + 0.206472245902897 + * x + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ), + 0.0280973138060306 + * (x2 - y2) + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ), + 0.00397356022507413 + * x + * (x2 - 3.0 * y2) + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ), + 0.000599036743111412 + * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + * (-6.0 * x2 * y2 + x4 + y4), + 9.98394571852353e-5 + * x + * (5197.5 - 67567.5 * z2) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -0.707162732524596 + * x + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + 5.83141328139864 * xy * (x2**3 + 7.0 * x2 * y4 - 7.0 * x4 * y2 - y2**3), + -2.91570664069932 + * yz + * (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3), + 7.87853281621404e-6 + * (1013512.5 * z2 - 67567.5) + * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4), + 5.10587282657803e-5 + * y + * (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z) + * (-10.0 * x2 * y2 + 5.0 * x4 + y4), + 0.00147275890257803 + * xy + * (x2 - y2) + * ( + 3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + - 14293.125 * z2 + + 1299.375 + ), + 0.0028519853513317 + * y + * (3.0 * x2 - y2) + * ( + -7.33333333333333 * z * (52.5 - 472.5 * z2) + + 3.0 + * z + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ) + - 560.0 * z + ), + 0.0463392770473559 + * xy + * ( + -4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + + 2.5 + * z + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ) + + 137.8125 * z2 + - 19.6875 + ), + 0.193851103820053 + * y + * ( + 3.2 * z * (1.5 - 7.5 * z2) + - 2.51428571428571 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + + 2.14285714285714 + * z + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 + * z + * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ) + + 5.48571428571429 * z + ), + 1.48417251362228 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.86581687426801 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 2.1808249179756 + * z + * ( + 1.14285714285714 * z * (1.5 * z2 - 0.5) + - 1.54285714285714 + * z + * ( + 1.75 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + - 1.125 * z2 + + 0.375 + ) + + 1.85714285714286 + * z + * ( + -1.45833333333333 + * z + * (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z) + + 1.83333333333333 + * z + * ( + -1.33333333333333 * z * (1.5 * z2 - 0.5) + + 1.8 + * z + * ( + 1.75 + * z + * ( + 1.66666666666667 * z * (1.5 * z2 - 0.5) + - 0.666666666666667 * z + ) + - 1.125 * z2 + + 0.375 + ) + + 0.533333333333333 * z + ) + + 0.9375 * z2 + - 0.3125 + ) + - 0.457142857142857 * z + ) + - 0.954110901614325 * z2 + + 0.318036967204775, + 0.193851103820053 + * x + * ( + 3.2 * z * (1.5 - 7.5 * z2) + - 2.51428571428571 + * z + * ( + 2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + + 2.14285714285714 + * z + * ( + -2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 2.16666666666667 + * z + * ( + -2.8 * z * (1.5 - 7.5 * z2) + + 2.2 + * z + * ( + 2.25 + * z + * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z) + + 9.375 * z2 + - 1.875 + ) + - 4.8 * z + ) + - 10.9375 * z2 + + 2.1875 + ) + + 5.48571428571429 * z + ), + 0.0231696385236779 + * (x2 - y2) + * ( + -4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + + 2.5 + * z + * ( + -4.8 * z * (52.5 * z2 - 7.5) + + 2.6 + * z + * ( + 2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z) + - 91.875 * z2 + + 13.125 + ) + + 48.0 * z + ) + + 137.8125 * z2 + - 19.6875 + ), + 0.0028519853513317 + * x + * (x2 - 3.0 * y2) + * ( + -7.33333333333333 * z * (52.5 - 472.5 * z2) + + 3.0 + * z + * ( + 3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z) + + 1063.125 * z2 + - 118.125 + ) + - 560.0 * z + ), + 0.000368189725644507 + * (-6.0 * x2 * y2 + x4 + y4) + * ( + 3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z) + - 14293.125 * z2 + + 1299.375 + ), + 5.10587282657803e-5 + * x + * (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z) + * (-10.0 * x2 * y2 + x4 + 5.0 * y4), + 7.87853281621404e-6 + * (1013512.5 * z2 - 67567.5) + * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3), + -2.91570664069932 + * xz + * (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3), + -20.4099464848952 * x2**3 * y2 + - 20.4099464848952 * x2 * y2**3 + + 0.72892666017483 * x4**2 + + 51.0248662122381 * x4 * y4 + + 0.72892666017483 * y4**2, + ], + -1, + ) + + +__all__ = [ + "rsh_cart_0", + "rsh_cart_1", + "rsh_cart_2", + "rsh_cart_3", + "rsh_cart_4", + "rsh_cart_5", + "rsh_cart_6", + "rsh_cart_7", + "rsh_cart_8", +] + + +from typing import Optional +import torch + + +class SphHarm(torch.nn.Module): + def __init__(self, m, n, dtype=torch.float32) -> None: + super().__init__() + self.dtype = dtype + m = torch.tensor(list(range(-m + 1, m))) + n = torch.tensor(list(range(n))) + self.is_normalized = False + vals = torch.cartesian_prod(m, n).T + vals = vals[:, vals[0] <= vals[1]] + m, n = vals.unbind(0) + + self.register_buffer("m", tensor=m) + self.register_buffer("n", tensor=n) + self.register_buffer("l_max", tensor=torch.max(self.n)) + + f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d = self._init_legendre() + self.register_buffer("f_a", tensor=f_a) + self.register_buffer("f_b", tensor=f_b) + self.register_buffer("d0_mask_3d", tensor=d0_mask_3d) + self.register_buffer("d1_mask_3d", tensor=d1_mask_3d) + self.register_buffer("initial_value", tensor=initial_value) + + @property + def device(self): + return next(self.buffers()).device + + def forward(self, points: torch.Tensor) -> torch.Tensor: + """Computes the spherical harmonics.""" + # Y_l^m = (-1) ^ m c_l^m P_l^m(cos(theta)) exp(i m phi) + B, N, D = points.shape + dtype = points.dtype + theta, phi = points.view(-1, D).to(self.dtype).unbind(-1) + cos_colatitude = torch.cos(phi) + legendre = self._gen_associated_legendre(cos_colatitude) + vals = torch.stack([self.m.abs(), self.n], dim=0) + vals = torch.cat( + [ + vals.repeat(1, theta.shape[0]), + torch.arange(theta.shape[0], device=theta.device) + .unsqueeze(0) + .repeat_interleave(vals.shape[1], dim=1), + ], + dim=0, + ) + legendre_vals = legendre[vals[0], vals[1], vals[2]] + legendre_vals = legendre_vals.reshape(-1, theta.shape[0]) + angle = torch.outer(self.m.abs(), theta) + vandermonde = torch.complex(torch.cos(angle), torch.sin(angle)) + harmonics = torch.complex( + legendre_vals * torch.real(vandermonde), + legendre_vals * torch.imag(vandermonde), + ) + + # Negative order. + m = self.m.unsqueeze(-1) + harmonics = torch.where( + m < 0, (-1.0) ** m.abs() * torch.conj(harmonics), harmonics + ) + harmonics = harmonics.permute(1, 0).reshape(B, N, -1).to(dtype) + return harmonics + + def _gen_recurrence_mask(self) -> tuple[torch.Tensor, torch.Tensor]: + """Generates mask for recurrence relation on the remaining entries. + + The remaining entries are with respect to the diagonal and offdiagonal + entries. + + Args: + l_max: see `gen_normalized_legendre`. + Returns: + torch.Tensors representing the mask used by the recurrence relations. + """ + + # Computes all coefficients. + m_mat, l_mat = torch.meshgrid( + torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype), + torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype), + indexing="ij", + ) + if self.is_normalized: + c0 = l_mat * l_mat + c1 = m_mat * m_mat + c2 = 2.0 * l_mat + c3 = (l_mat - 1.0) * (l_mat - 1.0) + d0 = torch.sqrt((4.0 * c0 - 1.0) / (c0 - c1)) + d1 = torch.sqrt(((c2 + 1.0) * (c3 - c1)) / ((c2 - 3.0) * (c0 - c1))) + else: + d0 = (2.0 * l_mat - 1.0) / (l_mat - m_mat) + d1 = (l_mat + m_mat - 1.0) / (l_mat - m_mat) + + d0_mask_indices = torch.triu_indices(self.l_max + 1, 1) + d1_mask_indices = torch.triu_indices(self.l_max + 1, 2) + + d_zeros = torch.zeros( + (self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device + ) + d_zeros[d0_mask_indices] = d0[d0_mask_indices] + d0_mask = d_zeros + + d_zeros = torch.zeros( + (self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device + ) + d_zeros[d1_mask_indices] = d1[d1_mask_indices] + d1_mask = d_zeros + + # Creates a 3D mask that contains 1s on the diagonal plane and 0s elsewhere. + i = torch.arange(self.l_max + 1, device=self.device)[:, None, None] + j = torch.arange(self.l_max + 1, device=self.device)[None, :, None] + k = torch.arange(self.l_max + 1, device=self.device)[None, None, :] + mask = (i + j - k == 0).to(self.dtype) + d0_mask_3d = torch.einsum("jk,ijk->ijk", d0_mask, mask) + d1_mask_3d = torch.einsum("jk,ijk->ijk", d1_mask, mask) + return (d0_mask_3d, d1_mask_3d) + + def _recursive(self, i: int, p_val: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + coeff_0 = self.d0_mask_3d[i] + coeff_1 = self.d1_mask_3d[i] + h = torch.einsum( + "ij,ijk->ijk", + coeff_0, + torch.einsum("ijk,k->ijk", torch.roll(p_val, shifts=1, dims=1), x), + ) - torch.einsum("ij,ijk->ijk", coeff_1, torch.roll(p_val, shifts=2, dims=1)) + p_val = p_val + h + return p_val + + def _init_legendre(self): + a_idx = torch.arange(1, self.l_max + 1, dtype=self.dtype, device=self.device) + b_idx = torch.arange(self.l_max, dtype=self.dtype, device=self.device) + if self.is_normalized: + # The initial value p(0,0). + initial_value: torch.Tensor = torch.tensor( + 0.5 / (torch.pi**0.5), device=self.device + ) + f_a = torch.cumprod(-1 * torch.sqrt(1.0 + 0.5 / a_idx), dim=0) + f_b = torch.sqrt(2.0 * b_idx + 3.0) + else: + # The initial value p(0,0). + initial_value = torch.tensor(1.0, device=self.device) + f_a = torch.cumprod(1.0 - 2.0 * a_idx, dim=0) + f_b = 2.0 * b_idx + 1.0 + + d0_mask_3d, d1_mask_3d = self._gen_recurrence_mask() + return f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d + + def _gen_associated_legendre(self, x: torch.Tensor) -> torch.Tensor: + r"""Computes associated Legendre functions (ALFs) of the first kind. + + The ALFs of the first kind are used in spherical harmonics. The spherical + harmonic of degree `l` and order `m` can be written as + `Y_l^m(θ, φ) = N_l^m * P_l^m(cos(θ)) * exp(i m φ)`, where `N_l^m` is the + normalization factor and θ and φ are the colatitude and longitude, + repectively. `N_l^m` is chosen in the way that the spherical harmonics form + a set of orthonormal basis function of L^2(S^2). For the computational + efficiency of spherical harmonics transform, the normalization factor is + used in the computation of the ALFs. In addition, normalizing `P_l^m` + avoids overflow/underflow and achieves better numerical stability. Three + recurrence relations are used in the computation. + + Args: + l_max: The maximum degree of the associated Legendre function. Both the + degrees and orders are `[0, 1, 2, ..., l_max]`. + x: A vector of type `float32`, `float64` containing the sampled points in + spherical coordinates, at which the ALFs are computed; `x` is essentially + `cos(θ)`. For the numerical integration used by the spherical harmonics + transforms, `x` contains the quadrature points in the interval of + `[-1, 1]`. There are several approaches to provide the quadrature points: + Gauss-Legendre method (`scipy.special.roots_legendre`), Gauss-Chebyshev + method (`scipy.special.roots_chebyu`), and Driscoll & Healy + method (Driscoll, James R., and Dennis M. Healy. "Computing Fourier + transforms and convolutions on the 2-sphere." Advances in applied + mathematics 15, no. 2 (1994): 202-250.). The Gauss-Legendre quadrature + points are nearly equal-spaced along θ and provide exact discrete + orthogonality, (P^m)^T W P_m = I, where `T` represents the transpose + operation, `W` is a diagonal matrix containing the quadrature weights, + and `I` is the identity matrix. The Gauss-Chebyshev points are equally + spaced, which only provide approximate discrete orthogonality. The + Driscoll & Healy qudarture points are equally spaced and provide the + exact discrete orthogonality. The number of sampling points is required to + be twice as the number of frequency points (modes) in the Driscoll & Healy + approach, which enables FFT and achieves a fast spherical harmonics + transform. + is_normalized: True if the associated Legendre functions are normalized. + With normalization, `N_l^m` is applied such that the spherical harmonics + form a set of orthonormal basis functions of L^2(S^2). + + Returns: + The 3D array of shape `(l_max + 1, l_max + 1, len(x))` containing the values + of the ALFs at `x`; the dimensions in the sequence of order, degree, and + evalution points. + """ + p = torch.zeros( + (self.l_max + 1, self.l_max + 1, x.shape[0]), dtype=x.dtype, device=x.device + ) + p[0, 0] = self.initial_value + + # Compute the diagonal entries p(l,l) with recurrence. + y = torch.cumprod( + torch.broadcast_to(torch.sqrt(1.0 - x * x), (self.l_max, x.shape[0])), dim=0 + ) + p_diag = self.initial_value * torch.einsum("i,ij->ij", self.f_a, y) + # torch.diag_indices(l_max + 1) + diag_indices = torch.stack( + [torch.arange(0, self.l_max + 1, device=x.device)] * 2, dim=0 + ) + p[(diag_indices[0][1:], diag_indices[1][1:])] = p_diag + + diag_indices = torch.stack( + [torch.arange(0, self.l_max, device=x.device)] * 2, dim=0 + ) + + # Compute the off-diagonal entries with recurrence. + p_offdiag = torch.einsum( + "ij,ij->ij", + torch.einsum("i,j->ij", self.f_b, x), + p[(diag_indices[0], diag_indices[1])], + ) # p[torch.diag_indices(l_max)]) + p[(diag_indices[0][: self.l_max], diag_indices[1][: self.l_max] + 1)] = ( + p_offdiag + ) + + # Compute the remaining entries with recurrence. + if self.l_max > 1: + for i in range(2, self.l_max + 1): + p = self._recursive(i, p, x) + return p diff --git a/src/misc/step_tracker.py b/src/misc/step_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..519c03a10c8880c74bec60a2c3696ae37521176a --- /dev/null +++ b/src/misc/step_tracker.py @@ -0,0 +1,23 @@ +from multiprocessing import RLock + +import torch +from jaxtyping import Int64 +from torch import Tensor +from torch.multiprocessing import Manager + + +class StepTracker: + lock: RLock + step: Int64[Tensor, ""] + + def __init__(self): + self.lock = Manager().RLock() + self.step = torch.tensor(0, dtype=torch.int64).share_memory_() + + def set_step(self, step: int) -> None: + with self.lock: + self.step.fill_(step) + + def get_step(self) -> int: + with self.lock: + return self.step.item() diff --git a/src/misc/utils.py b/src/misc/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..baefebaf7c3ccadb5effbebdb444478252d74f0c --- /dev/null +++ b/src/misc/utils.py @@ -0,0 +1,73 @@ +import torch + +from src.visualization.color_map import apply_color_map_to_image +import torch.distributed as dist + +def inverse_normalize(tensor, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)): + mean = torch.as_tensor(mean, dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1) + std = torch.as_tensor(std, dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1) + return tensor.mul(std).add(mean) + + +# Color-map the result. +def vis_depth_map(result, near=None, far=None): + if near is None and far is None: + far = result.view(-1)[:16_000_000].quantile(0.99).log() + try: + near = result[result > 0][:16_000_000].quantile(0.01).log() + except: + print("No valid depth values found.") + near = torch.zeros_like(far) + else: + near = near.log() + far = far.log() + + result = result.log() + result = 1 - (result - near) / (far - near) + return apply_color_map_to_image(result, "turbo") + + +def confidence_map(result): + # far = result.view(-1)[:16_000_000].quantile(0.99).log() + # try: + # near = result[result > 0][:16_000_000].quantile(0.01).log() + # except: + # print("No valid depth values found.") + # near = torch.zeros_like(far) + # result = result.log() + # result = 1 - (result - near) / (far - near) + result = result / result.view(-1).max() + return apply_color_map_to_image(result, "magma") + + +def get_overlap_tag(overlap): + if 0.05 <= overlap <= 0.3: + overlap_tag = "small" + elif overlap <= 0.55: + overlap_tag = "medium" + elif overlap <= 0.8: + overlap_tag = "large" + else: + overlap_tag = "ignore" + + return overlap_tag + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() \ No newline at end of file diff --git a/src/misc/wandb_tools.py b/src/misc/wandb_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..80b38c934987fb76aa0867b0672cb61ed138cb80 --- /dev/null +++ b/src/misc/wandb_tools.py @@ -0,0 +1,62 @@ +from pathlib import Path + +import wandb + + +def version_to_int(artifact) -> int: + """Convert versions of the form vX to X. For example, v12 to 12.""" + return int(artifact.version[1:]) + + +def download_checkpoint( + run_id: str, + download_dir: Path, + version: str | None, +) -> Path: + api = wandb.Api() + run = api.run(run_id) + + # Find the latest saved model checkpoint. + chosen = None + for artifact in run.logged_artifacts(): + if artifact.type != "model" or artifact.state != "COMMITTED": + continue + + # If no version is specified, use the latest. + if version is None: + if chosen is None or version_to_int(artifact) > version_to_int(chosen): + chosen = artifact + + # If a specific verison is specified, look for it. + elif version == artifact.version: + chosen = artifact + break + + # Download the checkpoint. + download_dir.mkdir(exist_ok=True, parents=True) + root = download_dir / run_id + chosen.download(root=root) + return root / "model.ckpt" + + +def update_checkpoint_path(path: str | None, wandb_cfg: dict) -> Path | None: + if path is None: + return None + + if not str(path).startswith("wandb://"): + return Path(path) + + run_id, *version = path[len("wandb://") :].split(":") + if len(version) == 0: + version = None + elif len(version) == 1: + version = version[0] + else: + raise ValueError("Invalid version specifier!") + + project = wandb_cfg["project"] + return download_checkpoint( + f"{project}/{run_id}", + Path("checkpoints"), + version, + ) diff --git a/src/misc/weight_modify.py b/src/misc/weight_modify.py new file mode 100644 index 0000000000000000000000000000000000000000..327fe3bd56557e420112f3b56bb1f4838ad19253 --- /dev/null +++ b/src/misc/weight_modify.py @@ -0,0 +1,197 @@ +import logging +from typing import List, Dict + +import math +import torch +from torch import nn as nn +import torch.nn.functional as F + + +_logger = logging.getLogger(__name__) + + +def resample_patch_embed( + patch_embed, + new_size: List[int], + interpolation: str = 'bicubic', + antialias: bool = True, + verbose: bool = False, +): + """Resample the weights of the patch embedding kernel to target resolution. + We resample the patch embedding kernel by approximately inverting the effect + of patch resizing. + + Code based on: + https://github.com/google-research/big_vision/blob/b00544b81f8694488d5f36295aeb7972f3755ffe/big_vision/models/proj/flexi/vit.py + + With this resizing, we can for example load a B/8 filter into a B/16 model + and, on 2x larger input image, the result will match. + + Args: + patch_embed: original parameter to be resized. + new_size (tuple(int, int): target shape (height, width)-only. + interpolation (str): interpolation for resize + antialias (bool): use anti-aliasing filter in resize + verbose (bool): log operation + Returns: + Resized patch embedding kernel. + """ + import numpy as np + try: + import functorch + vmap = functorch.vmap + except ImportError: + if hasattr(torch, 'vmap'): + vmap = torch.vmap + else: + assert False, "functorch or a version of torch with vmap is required for FlexiViT resizing." + + assert len(patch_embed.shape) == 4, "Four dimensions expected" + assert len(new_size) == 2, "New shape should only be hw" + old_size = patch_embed.shape[-2:] + if tuple(old_size) == tuple(new_size): + return patch_embed + + if verbose: + _logger.info(f"Resize patch embedding {patch_embed.shape} to {new_size}, w/ {interpolation} interpolation.") + + def resize(x_np, _new_size): + x_tf = torch.Tensor(x_np)[None, None, ...] + x_upsampled = F.interpolate( + x_tf, size=_new_size, mode=interpolation, antialias=antialias)[0, 0, ...].numpy() + return x_upsampled + + def get_resize_mat(_old_size, _new_size): + mat = [] + for i in range(np.prod(_old_size)): + basis_vec = np.zeros(_old_size) + basis_vec[np.unravel_index(i, _old_size)] = 1. + mat.append(resize(basis_vec, _new_size).reshape(-1)) + return np.stack(mat).T + + resize_mat = get_resize_mat(old_size, new_size) + resize_mat_pinv = torch.tensor(np.linalg.pinv(resize_mat.T), device=patch_embed.device) + + def resample_kernel(kernel): + resampled_kernel = resize_mat_pinv @ kernel.reshape(-1) + return resampled_kernel.reshape(new_size) + + v_resample_kernel = vmap(vmap(resample_kernel, 0, 0), 1, 1) + orig_dtype = patch_embed.dtype + patch_embed = patch_embed.float() + patch_embed = v_resample_kernel(patch_embed) + patch_embed = patch_embed.to(orig_dtype) + return patch_embed + + +def adapt_input_conv(in_chans, conv_weight): + conv_type = conv_weight.dtype + conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU + O, I, J, K = conv_weight.shape + if in_chans == 1: + if I > 3: + assert conv_weight.shape[1] % 3 == 0 + # For models with space2depth stems + conv_weight = conv_weight.reshape(O, I // 3, 3, J, K) + conv_weight = conv_weight.sum(dim=2, keepdim=False) + else: + conv_weight = conv_weight.sum(dim=1, keepdim=True) + elif in_chans != 3: + if I != 3: + raise NotImplementedError('Weight format not supported by conversion.') + else: + # NOTE this strategy should be better than random init, but there could be other combinations of + # the original RGB input layer weights that'd work better for specific cases. + repeat = int(math.ceil(in_chans / 3)) + conv_weight = conv_weight.repeat(1, repeat, 1, 1)[:, :in_chans, :, :] + conv_weight *= (3 / float(in_chans)) + + # instead of assigning the same weight to all channels, we can assign higher weight for original RGB channels + # conv_weight[:, :3, :, :] = conv_weight[:, :3, :, :] * 0.5 + # conv_weight[:, 3:, :, :] = conv_weight[:, 3:, :, :] * 0.5 * (3 / float(in_chans - 3)) + + conv_weight = conv_weight.to(conv_type) + return conv_weight + + +def adapt_head_conv(conv_weight): + conv_type = conv_weight.dtype + conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU + O, I, J, K = conv_weight.shape + + conv_weight_new = torch.chunk(conv_weight, 6, dim=1) + conv_weight_new = [conv_weight_new.mean(dim=1, keepdim=True) for conv_weight_new in conv_weight_new] + conv_weight_new = torch.cat(conv_weight_new, dim=1) * 0.5 + conv_weight = torch.cat([conv_weight, conv_weight_new], dim=1) + conv_weight = conv_weight.to(conv_type) + return conv_weight + + +def adapt_linear(conv_weight): + conv_type = conv_weight.dtype + conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU + O, I = conv_weight.shape + + conv_weight_new = torch.tensor_split(conv_weight, 81, dim=1) + conv_weight_new = [conv_weight_new.mean(dim=1, keepdim=True) for conv_weight_new in conv_weight_new] + conv_weight_new = torch.cat(conv_weight_new, dim=1) + # conv_weight = torch.cat([conv_weight, conv_weight_new], dim=1) + conv_weight = torch.cat([conv_weight * 0.5, conv_weight_new * 0.5], dim=1) + conv_weight = conv_weight.to(conv_type) + return conv_weight + + +def checkpoint_filter_fn( + state_dict: Dict[str, torch.Tensor], + model: nn.Module, + interpolation: str = 'bicubic', + antialias: bool = True, +) -> Dict[str, torch.Tensor]: + """ convert patch embedding weight from manual patchify + linear proj to conv""" + out_dict = {} + # state_dict = state_dict.get('model', state_dict) + # state_dict = state_dict.get('state_dict', state_dict) + prefix = '' + + if prefix: + # filter on & remove prefix string from keys + state_dict = {k[len(prefix):]: v for k, v in state_dict.items() if k.startswith(prefix)} + + for k, v in state_dict.items(): + if 'patch_embed.proj.weight' in k: + O, I, H, W = model.backbone.patch_embed.proj.weight.shape + if len(v.shape) < 4: + # For old models that I trained prior to conv based patchification + O, I, H, W = model.backbone.patch_embed.proj.weight.shape + v = v.reshape(O, -1, H, W) + if v.shape[-1] != W or v.shape[-2] != H: + v = resample_patch_embed( + v, + (H, W), + interpolation=interpolation, + antialias=antialias, + verbose=True, + ) + if v.shape[1] != I: + v = adapt_input_conv(I, v) + # elif 'downstream_head1.dpt.head.0.weight' in k or 'downstream_head2.dpt.head.0.weight' in k: + # v = adapt_head_conv(v) + + elif 'decoder_embed.weight' in k: + O, I = model.backbone.decoder_embed.weight.shape + if v.shape[1] != I: + v = adapt_linear(v) + + out_dict[k] = v + + # add prefix to make our model happy + prefix = 'backbone.' + out_dict = {prefix + k if 'downstream_head' not in k else k: v for k, v in out_dict.items()} + + # # remove the conf head weights + out_dict['downstream_head1.dpt.head.4.weight'] = out_dict['downstream_head1.dpt.head.4.weight'][0:3] + out_dict['downstream_head1.dpt.head.4.bias'] = out_dict['downstream_head1.dpt.head.4.bias'][0:3] + out_dict['downstream_head2.dpt.head.4.weight'] = out_dict['downstream_head2.dpt.head.4.weight'][0:3] + out_dict['downstream_head2.dpt.head.4.bias'] = out_dict['downstream_head2.dpt.head.4.bias'][0:3] + + return out_dict diff --git a/src/model/decoder/__init__.py b/src/model/decoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80604036a2a854c4ebaee0a1935e8fd1573e6f10 --- /dev/null +++ b/src/model/decoder/__init__.py @@ -0,0 +1,12 @@ +from .decoder import Decoder +from .decoder_splatting_cuda import DecoderSplattingCUDA, DecoderSplattingCUDACfg + +DECODERS = { + "splatting_cuda": DecoderSplattingCUDA, +} + +DecoderCfg = DecoderSplattingCUDACfg + + +def get_decoder(decoder_cfg: DecoderCfg) -> Decoder: + return DECODERS[decoder_cfg.name](decoder_cfg) diff --git a/src/model/decoder/cuda_splatting.py b/src/model/decoder/cuda_splatting.py new file mode 100644 index 0000000000000000000000000000000000000000..68f6d17045fc87ef51b2abeed2080a8d6344ab2b --- /dev/null +++ b/src/model/decoder/cuda_splatting.py @@ -0,0 +1,244 @@ +from math import isqrt +from typing import Literal + +import torch +from diff_gaussian_rasterization import ( + GaussianRasterizationSettings, + GaussianRasterizer, +) +from einops import einsum, rearrange, repeat +from jaxtyping import Float, Bool +from torch import Tensor + +from ...geometry.projection import get_fov, homogenize_points + + +def get_projection_matrix( + near: Float[Tensor, " batch"], + far: Float[Tensor, " batch"], + fov_x: Float[Tensor, " batch"], + fov_y: Float[Tensor, " batch"], +) -> Float[Tensor, "batch 4 4"]: + """Maps points in the viewing frustum to (-1, 1) on the X/Y axes and (0, 1) on the Z + axis. Differs from the OpenGL version in that Z doesn't have range (-1, 1) after + transformation and that Z is flipped. + """ + tan_fov_x = (0.5 * fov_x).tan() + tan_fov_y = (0.5 * fov_y).tan() + + top = tan_fov_y * near + bottom = -top + right = tan_fov_x * near + left = -right + + (b,) = near.shape + result = torch.zeros((b, 4, 4), dtype=torch.float32, device=near.device) + result[:, 0, 0] = 2 * near / (right - left) + result[:, 1, 1] = 2 * near / (top - bottom) + result[:, 0, 2] = (right + left) / (right - left) + result[:, 1, 2] = (top + bottom) / (top - bottom) + result[:, 3, 2] = 1 + result[:, 2, 2] = far / (far - near) + result[:, 2, 3] = -(far * near) / (far - near) + return result + + +def render_cuda( + extrinsics: Float[Tensor, "batch 4 4"], + intrinsics: Float[Tensor, "batch 3 3"], + near: Float[Tensor, " batch"], + far: Float[Tensor, " batch"], + image_shape: tuple[int, int], + background_color: Float[Tensor, "batch 3"], + gaussian_means: Float[Tensor, "batch gaussian 3"], + gaussian_covariances: Float[Tensor, "batch gaussian 3 3"], + gaussian_sh_coefficients: Float[Tensor, "batch gaussian 3 d_sh"], + gaussian_opacities: Float[Tensor, "batch gaussian"], + scale_invariant: bool = True, + use_sh: bool = True, + cam_rot_delta: Float[Tensor, "batch 3"] | None = None, + cam_trans_delta: Float[Tensor, "batch 3"] | None = None, + voxel_masks: Bool[Tensor, "batch gaussian"] | None = None, +) -> tuple[Float[Tensor, "batch 3 height width"], Float[Tensor, "batch height width"]]: + assert use_sh or gaussian_sh_coefficients.shape[-1] == 1 + + # Make sure everything is in a range where numerical issues don't appear. + if scale_invariant: + scale = 1 / near + extrinsics = extrinsics.clone() + extrinsics[..., :3, 3] = extrinsics[..., :3, 3] * scale[:, None] + gaussian_covariances = gaussian_covariances * (scale[:, None, None, None] ** 2) + gaussian_means = gaussian_means * scale[:, None, None] + near = near * scale + far = far * scale + + _, _, _, n = gaussian_sh_coefficients.shape + degree = isqrt(n) - 1 + shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous() + + b, _, _ = extrinsics.shape + h, w = image_shape + + fov_x, fov_y = get_fov(intrinsics).unbind(dim=-1) + tan_fov_x = (0.5 * fov_x).tan() + tan_fov_y = (0.5 * fov_y).tan() + + projection_matrix = get_projection_matrix(near, far, fov_x, fov_y) + projection_matrix = rearrange(projection_matrix, "b i j -> b j i") + view_matrix = rearrange(extrinsics.inverse(), "b i j -> b j i") + full_projection = view_matrix @ projection_matrix + + all_images = [] + all_radii = [] + all_depths = [] + for i in range(b): + # Set up a tensor for the gradients of the screen-space means. + mean_gradients = torch.zeros_like(gaussian_means[i], requires_grad=True) + try: + mean_gradients.retain_grad() + except Exception: + pass + + settings = GaussianRasterizationSettings( + image_height=h, + image_width=w, + tanfovx=tan_fov_x[i].item(), + tanfovy=tan_fov_y[i].item(), + bg=background_color[i], + scale_modifier=1.0, + viewmatrix=view_matrix[i], + projmatrix=full_projection[i], + projmatrix_raw=projection_matrix[i], + sh_degree=degree, + campos=extrinsics[i, :3, 3], + prefiltered=False, # This matches the original usage. + debug=False, + ) + rasterizer = GaussianRasterizer(settings) + + row, col = torch.triu_indices(3, 3) + + if voxel_masks is not None: + voxel_mask = voxel_masks[i] + image, radii, depth, opacity, n_touched = rasterizer( + means3D=gaussian_means[i][voxel_mask], + means2D=mean_gradients[voxel_mask], + shs=shs[i][voxel_mask] if use_sh else None, + colors_precomp=None if use_sh else shs[i, :, 0, :][voxel_mask], + opacities=gaussian_opacities[i][voxel_mask, ..., None], + cov3D_precomp=gaussian_covariances[i, :, row, col][voxel_mask], + theta=cam_rot_delta[i] if cam_rot_delta is not None else None, + rho=cam_trans_delta[i] if cam_trans_delta is not None else None, + ) + else: + image, radii, depth, opacity, n_touched = rasterizer( + means3D=gaussian_means[i], + means2D=mean_gradients, + shs=shs[i] if use_sh else None, + colors_precomp=None if use_sh else shs[i, :, 0, :], + opacities=gaussian_opacities[i, ..., None], + cov3D_precomp=gaussian_covariances[i, :, row, col], + theta=cam_rot_delta[i] if cam_rot_delta is not None else None, + rho=cam_trans_delta[i] if cam_trans_delta is not None else None, + ) + all_images.append(image) + all_radii.append(radii) + all_depths.append(depth.squeeze(0)) + return torch.stack(all_images), torch.stack(all_depths) + + +def render_cuda_orthographic( + extrinsics: Float[Tensor, "batch 4 4"], + width: Float[Tensor, " batch"], + height: Float[Tensor, " batch"], + near: Float[Tensor, " batch"], + far: Float[Tensor, " batch"], + image_shape: tuple[int, int], + background_color: Float[Tensor, "batch 3"], + gaussian_means: Float[Tensor, "batch gaussian 3"], + gaussian_covariances: Float[Tensor, "batch gaussian 3 3"], + gaussian_sh_coefficients: Float[Tensor, "batch gaussian 3 d_sh"], + gaussian_opacities: Float[Tensor, "batch gaussian"], + fov_degrees: float = 0.1, + use_sh: bool = True, + dump: dict | None = None, +) -> Float[Tensor, "batch 3 height width"]: + b, _, _ = extrinsics.shape + h, w = image_shape + assert use_sh or gaussian_sh_coefficients.shape[-1] == 1 + + _, _, _, n = gaussian_sh_coefficients.shape + degree = isqrt(n) - 1 + shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous() + + # Create fake "orthographic" projection by moving the camera back and picking a + # small field of view. + fov_x = torch.tensor(fov_degrees, device=extrinsics.device).deg2rad() + tan_fov_x = (0.5 * fov_x).tan() + distance_to_near = (0.5 * width) / tan_fov_x + tan_fov_y = 0.5 * height / distance_to_near + fov_y = (2 * tan_fov_y).atan() + near = near + distance_to_near + far = far + distance_to_near + move_back = torch.eye(4, dtype=torch.float32, device=extrinsics.device) + move_back[2, 3] = -distance_to_near + extrinsics = extrinsics @ move_back + + # Escape hatch for visualization/figures. + if dump is not None: + dump["extrinsics"] = extrinsics + dump["fov_x"] = fov_x + dump["fov_y"] = fov_y + dump["near"] = near + dump["far"] = far + + projection_matrix = get_projection_matrix( + near, far, repeat(fov_x, "-> b", b=b), fov_y + ) + projection_matrix = rearrange(projection_matrix, "b i j -> b j i") + view_matrix = rearrange(extrinsics.inverse(), "b i j -> b j i") + full_projection = view_matrix @ projection_matrix + + all_images = [] + all_radii = [] + for i in range(b): + # Set up a tensor for the gradients of the screen-space means. + mean_gradients = torch.zeros_like(gaussian_means[i], requires_grad=True) + try: + mean_gradients.retain_grad() + except Exception: + pass + + settings = GaussianRasterizationSettings( + image_height=h, + image_width=w, + tanfovx=tan_fov_x, + tanfovy=tan_fov_y, + bg=background_color[i], + scale_modifier=1.0, + viewmatrix=view_matrix[i], + projmatrix=full_projection[i], + projmatrix_raw=projection_matrix[i], + sh_degree=degree, + campos=extrinsics[i, :3, 3], + prefiltered=False, # This matches the original usage. + debug=False, + ) + rasterizer = GaussianRasterizer(settings) + + row, col = torch.triu_indices(3, 3) + + image, radii, depth, opacity, n_touched = rasterizer( + means3D=gaussian_means[i], + means2D=mean_gradients, + shs=shs[i] if use_sh else None, + colors_precomp=None if use_sh else shs[i, :, 0, :], + opacities=gaussian_opacities[i, ..., None], + cov3D_precomp=gaussian_covariances[i, :, row, col], + ) + all_images.append(image) + all_radii.append(radii) + return torch.stack(all_images) + + +DepthRenderingMode = Literal["depth", "disparity", "relative_disparity", "log"] diff --git a/src/model/decoder/decoder.py b/src/model/decoder/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..cc853282dd99503fd5e7e0e48fde0266a612b571 --- /dev/null +++ b/src/model/decoder/decoder.py @@ -0,0 +1,46 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Generic, Literal, TypeVar + +from jaxtyping import Float +from torch import Tensor, nn + +from ..types import Gaussians + +DepthRenderingMode = Literal[ + "depth", + "log", + "disparity", + "relative_disparity", +] + + +@dataclass +class DecoderOutput: + color: Float[Tensor, "batch view 3 height width"] + depth: Float[Tensor, "batch view height width"] | None + alpha: Float[Tensor, "batch view height width"] | None + lod_rendering: dict | None + +T = TypeVar("T") + + +class Decoder(nn.Module, ABC, Generic[T]): + cfg: T + + def __init__(self, cfg: T) -> None: + super().__init__() + self.cfg = cfg + + @abstractmethod + def forward( + self, + gaussians: Gaussians, + extrinsics: Float[Tensor, "batch view 4 4"], + intrinsics: Float[Tensor, "batch view 3 3"], + near: Float[Tensor, "batch view"], + far: Float[Tensor, "batch view"], + image_shape: tuple[int, int], + depth_mode: DepthRenderingMode | None = None, + ) -> DecoderOutput: + pass diff --git a/src/model/decoder/decoder_splatting_cuda.py b/src/model/decoder/decoder_splatting_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..542877e5eb46050bc279d61ed4c96a97456d8da2 --- /dev/null +++ b/src/model/decoder/decoder_splatting_cuda.py @@ -0,0 +1,111 @@ +from dataclasses import dataclass +from typing import Literal + +import torch +from einops import rearrange, repeat +from jaxtyping import Float +from torch import Tensor +import torchvision + +from ..types import Gaussians +# from .cuda_splatting import DepthRenderingMode, render_cuda +from .decoder import Decoder, DecoderOutput +from math import sqrt +from gsplat import rasterization + +from ...misc.utils import vis_depth_map + +DepthRenderingMode = Literal["depth", "disparity", "relative_disparity", "log"] + +@dataclass +class DecoderSplattingCUDACfg: + name: Literal["splatting_cuda"] + background_color: list[float] + make_scale_invariant: bool + + +class DecoderSplattingCUDA(Decoder[DecoderSplattingCUDACfg]): + background_color: Float[Tensor, "3"] + + def __init__( + self, + cfg: DecoderSplattingCUDACfg, + ) -> None: + super().__init__(cfg) + self.make_scale_invariant = cfg.make_scale_invariant + self.register_buffer( + "background_color", + torch.tensor(cfg.background_color, dtype=torch.float32), + persistent=False, + ) + + def rendering_fn( + self, + gaussians: Gaussians, + extrinsics: Float[Tensor, "batch view 4 4"], + intrinsics: Float[Tensor, "batch view 3 3"], + near: Float[Tensor, "batch view"], + far: Float[Tensor, "batch view"], + image_shape: tuple[int, int], + depth_mode: DepthRenderingMode | None = None, + cam_rot_delta: Float[Tensor, "batch view 3"] | None = None, + cam_trans_delta: Float[Tensor, "batch view 3"] | None = None, + ) -> DecoderOutput: + B, V, _, _ = intrinsics.shape + H, W = image_shape + rendered_imgs, rendered_depths, rendered_alphas = [], [], [] + xyzs, opacitys, rotations, scales, features = gaussians.means, gaussians.opacities, gaussians.rotations, gaussians.scales, gaussians.harmonics.permute(0, 1, 3, 2).contiguous() + covariances = gaussians.covariances + for i in range(B): + xyz_i = xyzs[i].float() + feature_i = features[i].float() + covar_i = covariances[i].float() + scale_i = scales[i].float() + rotation_i = rotations[i].float() + opacity_i = opacitys[i].squeeze().float() + test_w2c_i = extrinsics[i].float().inverse() # (V, 4, 4) + test_intr_i_normalized = intrinsics[i].float() + # Denormalize the intrinsics into standred format + test_intr_i = test_intr_i_normalized.clone() + test_intr_i[:, 0] = test_intr_i_normalized[:, 0] * W + test_intr_i[:, 1] = test_intr_i_normalized[:, 1] * H + sh_degree = (int(sqrt(feature_i.shape[-2])) - 1) + + rendering_list = [] + rendering_depth_list = [] + rendering_alpha_list = [] + for j in range(V): + rendering, alpha, _ = rasterization(xyz_i, rotation_i, scale_i, opacity_i, feature_i, + test_w2c_i[j:j+1], test_intr_i[j:j+1], W, H, sh_degree=sh_degree, + # near_plane=near[i].mean(), far_plane=far[i].mean(), + render_mode="RGB+D", packed=False, + near_plane=1e-10, + backgrounds=self.background_color.unsqueeze(0).repeat(1, 1), + radius_clip=0.1, + covars=covar_i, + rasterize_mode='classic') # (V, H, W, 3) + rendering_img, rendering_depth = torch.split(rendering, [3, 1], dim=-1) + rendering_img = rendering_img.clamp(0.0, 1.0) + rendering_list.append(rendering_img.permute(0, 3, 1, 2)) + rendering_depth_list.append(rendering_depth) + rendering_alpha_list.append(alpha) + rendered_depths.append(torch.cat(rendering_depth_list, dim=0).squeeze()) + rendered_imgs.append(torch.cat(rendering_list, dim=0)) + rendered_alphas.append(torch.cat(rendering_alpha_list, dim=0).squeeze()) + return DecoderOutput(torch.stack(rendered_imgs), torch.stack(rendered_depths), torch.stack(rendered_alphas), lod_rendering=None) + + def forward( + self, + gaussians: Gaussians, + extrinsics: Float[Tensor, "batch view 4 4"], + intrinsics: Float[Tensor, "batch view 3 3"], + near: Float[Tensor, "batch view"], + far: Float[Tensor, "batch view"], + image_shape: tuple[int, int], + depth_mode: DepthRenderingMode | None = None, + cam_rot_delta: Float[Tensor, "batch view 3"] | None = None, + cam_trans_delta: Float[Tensor, "batch view 3"] | None = None, + ) -> DecoderOutput: + + return self.rendering_fn(gaussians, extrinsics, intrinsics, near, far, image_shape, depth_mode, cam_rot_delta, cam_trans_delta) + diff --git a/src/model/encoder/__init__.py b/src/model/encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b14607a435afee06ef8881b9684b78a721d3aaf2 --- /dev/null +++ b/src/model/encoder/__init__.py @@ -0,0 +1,19 @@ +from typing import Optional, Union + +from .encoder import Encoder +from .visualization.encoder_visualizer import EncoderVisualizer +from .anysplat import EncoderAnySplat, EncoderAnySplatCfg + +ENCODERS = { + "anysplat": (EncoderAnySplat, None), +} + +EncoderCfg = Union[EncoderAnySplatCfg] + + +def get_encoder(cfg: EncoderCfg) -> tuple[Encoder, Optional[EncoderVisualizer]]: + encoder, visualizer = ENCODERS[cfg.name] + encoder = encoder(cfg) + if visualizer is not None: + visualizer = visualizer(cfg.visualizer, encoder) + return encoder, visualizer diff --git a/src/model/encoder/anysplat.py b/src/model/encoder/anysplat.py new file mode 100644 index 0000000000000000000000000000000000000000..2b89af25a39606ff054e56c65b84f3ec5b147d4a --- /dev/null +++ b/src/model/encoder/anysplat.py @@ -0,0 +1,590 @@ +import copy + +# VGGT parts +import os +import sys +from copy import deepcopy +from dataclasses import dataclass +from typing import List, Literal, Optional + +import torch +import torch.nn.functional as F +import torchvision +from einops import rearrange +from huggingface_hub import PyTorchModelHubMixin +from jaxtyping import Float +from src.dataset.shims.bounds_shim import apply_bounds_shim +from src.dataset.shims.normalize_shim import apply_normalize_shim +from src.dataset.shims.patch_shim import apply_patch_shim +from src.dataset.types import BatchedExample, DataShim +from src.geometry.projection import sample_image_grid + +from src.model.encoder.heads.vggt_dpt_gs_head import VGGT_DPT_GS_Head +from src.model.encoder.vggt.utils.geometry import ( + batchify_unproject_depth_map_to_point_map, + unproject_depth_map_to_point_map, +) +from src.model.encoder.vggt.utils.pose_enc import pose_encoding_to_extri_intri +from torch import nn, Tensor + +from ..types import Gaussians +from .backbone import Backbone, BackboneCfg, get_backbone + +from .backbone.croco.misc import transpose_to_landscape +from .common.gaussian_adapter import ( + GaussianAdapter, + GaussianAdapterCfg, + UnifiedGaussianAdapter, +) +from .encoder import Encoder, EncoderOutput +from .heads import head_factory +from .visualization.encoder_visualizer_epipolar_cfg import EncoderVisualizerEpipolarCfg + +root_path = os.path.abspath(".") +sys.path.append(root_path) +from src.model.encoder.heads.head_modules import TransformerBlockSelfAttn +from src.model.encoder.vggt.heads.dpt_head import DPTHead +from src.model.encoder.vggt.layers.mlp import Mlp +from src.model.encoder.vggt.models.vggt import VGGT + +inf = float("inf") + + +@dataclass +class OpacityMappingCfg: + initial: float + final: float + warm_up: int + + +@dataclass +class GSHeadParams: + dec_depth: int = 23 + patch_size: tuple[int, int] = (14, 14) + enc_embed_dim: int = 2048 + dec_embed_dim: int = 2048 + feature_dim: int = 256 + depth_mode = ("exp", -inf, inf) + conf_mode = True + + +@dataclass +class EncoderAnySplatCfg: + name: Literal["anysplat"] + anchor_feat_dim: int + voxel_size: float + n_offsets: int + d_feature: int + add_view: bool + num_monocular_samples: int + backbone: BackboneCfg + visualizer: EncoderVisualizerEpipolarCfg + gaussian_adapter: GaussianAdapterCfg + apply_bounds_shim: bool + opacity_mapping: OpacityMappingCfg + gaussians_per_pixel: int + num_surfaces: int + gs_params_head_type: str + input_mean: tuple[float, float, float] = (0.5, 0.5, 0.5) + input_std: tuple[float, float, float] = (0.5, 0.5, 0.5) + pretrained_weights: str = "" + pose_free: bool = True + pred_pose: bool = True + gt_pose_to_pts: bool = False + gs_prune: bool = False + opacity_threshold: float = 0.001 + gs_keep_ratio: float = 1.0 + pred_head_type: Literal["depth", "point"] = "point" + freeze_backbone: bool = False + freeze_module: Literal[ + "all", + "global", + "frame", + "patch_embed", + "patch_embed+frame", + "patch_embed+global", + "global+frame", + "None", + ] = "None" + distill: bool = False + render_conf: bool = False + opacity_conf: bool = False + conf_threshold: float = 0.1 + intermediate_layer_idx: Optional[List[int]] = None + voxelize: bool = False + + +def rearrange_head(feat, patch_size, H, W): + B = feat.shape[0] + feat = feat.transpose(-1, -2).view(B, -1, H // patch_size, W // patch_size) + feat = F.pixel_shuffle(feat, patch_size) # B,D,H,W + feat = rearrange(feat, "b d h w -> b (h w) d") + return feat + + +class EncoderAnySplat(Encoder[EncoderAnySplatCfg]): + backbone: nn.Module + gaussian_adapter: GaussianAdapter + + def __init__(self, cfg: EncoderAnySplatCfg) -> None: + super().__init__(cfg) + model_full = VGGT() + self.aggregator = model_full.aggregator.to(torch.bfloat16) + self.freeze_backbone = cfg.freeze_backbone + self.distill = cfg.distill + self.pred_pose = cfg.pred_pose + + self.camera_head = model_full.camera_head + if self.cfg.pred_head_type == "depth": + self.depth_head = model_full.depth_head + else: + self.point_head = model_full.point_head + + if self.distill: + self.distill_aggregator = copy.deepcopy(self.aggregator) + self.distill_camera_head = copy.deepcopy(self.camera_head) + self.distill_depth_head = copy.deepcopy(self.depth_head) + for module in [ + self.distill_aggregator, + self.distill_camera_head, + self.distill_depth_head, + ]: + for param in module.parameters(): + param.requires_grad = False + param.data = param.data.cpu() + + if self.freeze_backbone: + # Freeze backbone components + if self.cfg.pred_head_type == "depth": + for module in [self.aggregator, self.camera_head, self.depth_head]: + for param in module.parameters(): + param.requires_grad = False + else: + for module in [self.aggregator, self.camera_head, self.point_head]: + for param in module.parameters(): + param.requires_grad = False + else: + # aggregator freeze + freeze_module = self.cfg.freeze_module + if freeze_module == "None": + pass + + elif freeze_module == "all": + for param in self.aggregator.parameters(): + param.requires_grad = False + + else: + module_pairs = { + "patch_embed+frame": ["patch_embed", "frame"], + "patch_embed+global": ["patch_embed", "global"], + "global+frame": ["global", "frame"], + } + + if freeze_module in module_pairs: + for name, param in self.aggregator.named_parameters(): + if any(m in name for m in module_pairs[freeze_module]): + param.requires_grad = False + else: + for name, param in self.named_parameters(): + param.requires_grad = ( + freeze_module not in name and "distill" not in name + ) + + self.pose_free = cfg.pose_free + if self.pose_free: + self.gaussian_adapter = UnifiedGaussianAdapter(cfg.gaussian_adapter) + else: + self.gaussian_adapter = GaussianAdapter(cfg.gaussian_adapter) + + self.raw_gs_dim = 1 + self.gaussian_adapter.d_in # 1 for opacity + self.voxel_size = cfg.voxel_size + self.gs_params_head_type = cfg.gs_params_head_type + # fake backbone for head parameters + head_params = GSHeadParams() + self.gaussian_param_head = VGGT_DPT_GS_Head( + dim_in=2048, + patch_size=head_params.patch_size, + output_dim=self.raw_gs_dim + 1, + activation="norm_exp", + conf_activation="expp1", + features=head_params.feature_dim, + ) + + def map_pdf_to_opacity( + self, + pdf: Float[Tensor, " *batch"], + global_step: int, + ) -> Float[Tensor, " *batch"]: + # https://www.desmos.com/calculator/opvwti3ba9 + + # Figure out the exponent. + cfg = self.cfg.opacity_mapping + x = cfg.initial + min(global_step / cfg.warm_up, 1) * (cfg.final - cfg.initial) + exponent = 2**x + + # Map the probability density to an opacity. + return 0.5 * (1 - (1 - pdf) ** exponent + pdf ** (1 / exponent)) + + def normalize_pts3d(self, pts3ds, valid_masks, original_extrinsics=None): + # normalize pts_all + B = pts3ds.shape[0] + pts3d_norms = [] + scale_factors = [] + for bs in range(B): + pts3d, valid_mask = pts3ds[bs], valid_masks[bs] + if original_extrinsics is not None: + camera_c2w = original_extrinsics[bs] + first_camera_w2c = ( + camera_c2w[0].inverse().unsqueeze(0).repeat(pts3d.shape[0], 1, 1) + ) + + pts3d_homo = torch.cat( + [pts3d, torch.ones_like(pts3d[:, :, :, :1])], dim=-1 + ) + transformed_pts3d = torch.bmm( + first_camera_w2c, pts3d_homo.flatten(1, 2).transpose(1, 2) + ).transpose(1, 2)[..., :3] + scene_scale = torch.norm( + transformed_pts3d.flatten(0, 1)[valid_mask.flatten(0, 2).bool()], + dim=-1, + ).mean() + else: + transformed_pts3d = pts3d[valid_mask] + dis = transformed_pts3d.norm(dim=-1) + scene_scale = dis.mean().clip(min=1e-8) + # pts3d_norm[bs] = pts3d[bs] / scene_scale + pts3d_norms.append(pts3d / scene_scale) + scale_factors.append(scene_scale) + return torch.stack(pts3d_norms, dim=0), torch.stack(scale_factors, dim=0) + + def align_pts_all_with_pts3d( + self, pts_all, pts3d, valid_mask, original_extrinsics=None + ): + # align pts_all with pts3d + B = pts_all.shape[0] + + # follow vggt's normalization implementation + pts3d_norm, scale_factor = self.normalize_pts3d( + pts3d, valid_mask, original_extrinsics + ) # check if this is correct + pts_all = pts_all * scale_factor.view(B, 1, 1, 1, 1) + + return pts_all + + def pad_tensor_list(self, tensor_list, pad_shape, value=0.0): + padded = [] + for t in tensor_list: + pad_len = pad_shape[0] - t.shape[0] + if pad_len > 0: + padding = torch.full( + (pad_len, *t.shape[1:]), value, device=t.device, dtype=t.dtype + ) + t = torch.cat([t, padding], dim=0) + padded.append(t) + return torch.stack(padded) + + def voxelizaton_with_fusion(self, img_feat, pts3d, voxel_size, conf=None): + # img_feat: B*V, C, H, W + # pts3d: B*V, 3, H, W + V, C, H, W = img_feat.shape + pts3d_flatten = pts3d.permute(0, 2, 3, 1).flatten(0, 2) + + voxel_indices = (pts3d_flatten / voxel_size).round().int() # [B*V*N, 3] + unique_voxels, inverse_indices, counts = torch.unique( + voxel_indices, dim=0, return_inverse=True, return_counts=True + ) + + # Flatten confidence scores and features + conf_flat = conf.flatten() # [B*V*N] + anchor_feats_flat = img_feat.permute(0, 2, 3, 1).flatten(0, 2) # [B*V*N, ...] + + # Compute softmax weights per voxel + conf_voxel_max, _ = scatter_max(conf_flat, inverse_indices, dim=0) + conf_exp = torch.exp(conf_flat - conf_voxel_max[inverse_indices]) + voxel_weights = scatter_add( + conf_exp, inverse_indices, dim=0 + ) # [num_unique_voxels] + weights = (conf_exp / (voxel_weights[inverse_indices] + 1e-6)).unsqueeze( + -1 + ) # [B*V*N, 1] + + # Compute weighted average of positions and features + weighted_pts = pts3d_flatten * weights + weighted_feats = anchor_feats_flat.squeeze(1) * weights + + # Aggregate per voxel + voxel_pts = scatter_add( + weighted_pts, inverse_indices, dim=0 + ) # [num_unique_voxels, 3] + voxel_feats = scatter_add( + weighted_feats, inverse_indices, dim=0 + ) # [num_unique_voxels, feat_dim] + + return voxel_pts, voxel_feats + + def forward( + self, + image: torch.Tensor, + global_step: int = 0, + visualization_dump: Optional[dict] = None, + ) -> Gaussians: + device = image.device + b, v, _, h, w = image.shape + distill_infos = {} + if self.distill: + distill_image = image.clone().detach() + for module in [ + self.distill_aggregator, + self.distill_camera_head, + self.distill_depth_head, + ]: + for param in module.parameters(): + param.data = param.data.to(device, non_blocking=True) + + with torch.no_grad(): + # Process with bfloat16 precision + with torch.amp.autocast("cuda", enabled=True, dtype=torch.bfloat16): + distill_aggregated_tokens_list, distill_patch_start_idx = ( + self.distill_aggregator( + distill_image.to(torch.bfloat16), + intermediate_layer_idx=self.cfg.intermediate_layer_idx, + ) + ) + + # Process with default precision + with torch.amp.autocast("cuda", enabled=False): + # Get camera pose information + distill_pred_pose_enc_list = self.distill_camera_head( + distill_aggregated_tokens_list + ) + last_distill_pred_pose_enc = distill_pred_pose_enc_list[-1] + distill_extrinsic, distill_intrinsic = pose_encoding_to_extri_intri( + last_distill_pred_pose_enc, image.shape[-2:] + ) + + # Get depth information + distill_depth_map, distill_depth_conf = self.distill_depth_head( + distill_aggregated_tokens_list, + images=distill_image, + patch_start_idx=distill_patch_start_idx, + ) + + # Convert depth to 3D points + distill_pts_all = batchify_unproject_depth_map_to_point_map( + distill_depth_map, distill_extrinsic, distill_intrinsic + ) + # Store results + distill_infos["pred_pose_enc_list"] = distill_pred_pose_enc_list + distill_infos["pts_all"] = distill_pts_all + distill_infos["depth_map"] = distill_depth_map + + conf_threshold = torch.quantile( + distill_depth_conf.flatten(2, 3), 0.3, dim=-1, keepdim=True + ) # Get threshold for each view + conf_mask = distill_depth_conf > conf_threshold.unsqueeze(-1) + distill_infos["conf_mask"] = conf_mask + + for module in [ + self.distill_aggregator, + self.distill_camera_head, + self.distill_depth_head, + ]: + for param in module.parameters(): + param.data = param.data.cpu() + # Clean up to save memory + del distill_aggregated_tokens_list, distill_patch_start_idx + del distill_pred_pose_enc_list, last_distill_pred_pose_enc + del distill_extrinsic, distill_intrinsic + del distill_depth_map, distill_depth_conf + torch.cuda.empty_cache() + + with torch.amp.autocast("cuda", enabled=True, dtype=torch.bfloat16): + aggregated_tokens_list, patch_start_idx = self.aggregator( + image.to(torch.bfloat16), + intermediate_layer_idx=self.cfg.intermediate_layer_idx, + ) + + with torch.amp.autocast("cuda", enabled=False): + pred_pose_enc_list = self.camera_head(aggregated_tokens_list) + last_pred_pose_enc = pred_pose_enc_list[-1] + extrinsic, intrinsic = pose_encoding_to_extri_intri( + last_pred_pose_enc, image.shape[-2:] + ) # only for debug + + if self.cfg.pred_head_type == "point": + pts_all, pts_conf = self.point_head( + aggregated_tokens_list, + images=image, + patch_start_idx=patch_start_idx, + ) + elif self.cfg.pred_head_type == "depth": + depth_map, depth_conf = self.depth_head( + aggregated_tokens_list, + images=image, + patch_start_idx=patch_start_idx, + ) + pts_all = batchify_unproject_depth_map_to_point_map( + depth_map, extrinsic, intrinsic + ) + else: + raise ValueError(f"Invalid pred_head_type: {self.cfg.pred_head_type}") + + if self.cfg.render_conf: + conf_valid = torch.quantile( + depth_conf.flatten(0, 1), self.cfg.conf_threshold + ) + conf_valid_mask = depth_conf > conf_valid + else: + conf_valid_mask = torch.ones_like(depth_conf, dtype=torch.bool) + + # dpt style gs_head input format + out = self.gaussian_param_head( + aggregated_tokens_list, + pts_all.flatten(0, 1).permute(0, 3, 1, 2), + image, + patch_start_idx=patch_start_idx, + image_size=(h, w), + ) + + del aggregated_tokens_list, patch_start_idx + torch.cuda.empty_cache() + + pts_flat = pts_all.flatten(2, 3) + scene_scale = pts_flat.norm(dim=-1).mean().clip(min=1e-8) + + anchor_feats, conf = out[:, :, : self.raw_gs_dim], out[:, :, self.raw_gs_dim] + + neural_feats_list, neural_pts_list = [], [] + if self.cfg.voxelize: + for b_i in range(b): + neural_pts, neural_feats = self.voxelizaton_with_fusion( + anchor_feats[b_i], + pts_all[b_i].permute(0, 3, 1, 2).contiguous(), + self.voxel_size, + conf=conf[b_i], + ) + neural_feats_list.append(neural_feats) + neural_pts_list.append(neural_pts) + else: + for b_i in range(b): + neural_feats_list.append( + anchor_feats[b_i].permute(0, 2, 3, 1)[conf_valid_mask[b_i]] + ) + neural_pts_list.append(pts_all[b_i][conf_valid_mask[b_i]]) + + max_voxels = max(f.shape[0] for f in neural_feats_list) + neural_feats = self.pad_tensor_list( + neural_feats_list, (max_voxels,), value=-1e10 + ) + + neural_pts = self.pad_tensor_list( + neural_pts_list, (max_voxels,), -1e4 + ) # -1 == invalid voxel + + depths = neural_pts[..., -1].unsqueeze(-1) + densities = neural_feats[..., 0].sigmoid() + + assert len(densities.shape) == 2, "the shape of densities should be (B, N)" + assert neural_pts.shape[1] > 1, "the number of voxels should be greater than 1" + + opacity = self.map_pdf_to_opacity(densities, global_step).squeeze(-1) + if self.cfg.opacity_conf: + shift = torch.quantile(depth_conf, self.cfg.conf_threshold) + opacity = opacity * torch.sigmoid(depth_conf - shift)[ + conf_valid_mask + ].unsqueeze( + 0 + ) # little bit hacky + + # GS Prune, but only works when bs = 1 + # if want to support bs > 1, need to random prune gaussians based on the rank of opacity like LongLRM + # Note: we not prune gaussians here, but we will try it in the future + if self.cfg.gs_prune and b == 1: + opacity_threshold = self.cfg.opacity_threshold + gaussian_usage = opacity > opacity_threshold # (B, N) + + print( + f"based on opacity threshold {opacity_threshold}, pruned {gaussian_usage.shape[1] - neural_pts.shape[1]} gaussians out of {gaussian_usage.shape[1]}" + ) + + if (gaussian_usage.sum() / gaussian_usage.numel()) > self.cfg.gs_keep_ratio: + # rank by opacity + num_keep = int(gaussian_usage.shape[1] * self.cfg.gs_keep_ratio) + idx_sort = opacity.argsort(dim=1, descending=True) + keep_idx = idx_sort[:, :num_keep] + gaussian_usage = torch.zeros_like(gaussian_usage, dtype=torch.bool) + gaussian_usage.scatter_(1, keep_idx, True) + + neural_pts = neural_pts[gaussian_usage].view(b, -1, 3).contiguous() + depths = depths[gaussian_usage].view(b, -1, 1).contiguous() + neural_feats = ( + neural_feats[gaussian_usage].view(b, -1, self.raw_gs_dim).contiguous() + ) + opacity = opacity[gaussian_usage].view(b, -1).contiguous() + + print( + f"finally pruned {gaussian_usage.shape[1] - neural_pts.shape[1]} gaussians out of {gaussian_usage.shape[1]}" + ) + + gaussians = self.gaussian_adapter.forward( + neural_pts, + depths, + opacity, + neural_feats[..., 1:].squeeze(2), + ) + + if visualization_dump is not None: + visualization_dump["depth"] = rearrange( + pts_all[..., -1].flatten(2, 3).unsqueeze(-1).unsqueeze(-1), + "b v (h w) srf s -> b v h w srf s", + h=h, + w=w, + ) + + infos = {} + infos["scene_scale"] = scene_scale + infos["voxelize_ratio"] = densities.shape[1] / (h * w * v) + + print( + f"scene scale: {scene_scale:.3f}, pixel-wise num: {h*w*v}, after voxelize: {neural_pts.shape[1]}, voxelize ratio: {infos['voxelize_ratio']:.3f}" + ) + print( + f"Gaussians attributes: \n" + f"opacities: mean: {gaussians.opacities.mean()}, min: {gaussians.opacities.min()}, max: {gaussians.opacities.max()} \n" + f"scales: mean: {gaussians.scales.mean()}, min: {gaussians.scales.min()}, max: {gaussians.scales.max()}" + ) + + print("B:", b, "V:", v, "H:", h, "W:", w) + extrinsic_padding = ( + torch.tensor([0, 0, 0, 1], device=device, dtype=extrinsic.dtype) + .view(1, 1, 1, 4) + .repeat(b, v, 1, 1) + ) + intrinsic = intrinsic.clone() # Create a new tensor + intrinsic = torch.stack( + [intrinsic[:, :, 0] / w, intrinsic[:, :, 1] / h, intrinsic[:, :, 2]], dim=2 + ) + + return EncoderOutput( + gaussians=gaussians, + pred_pose_enc_list=pred_pose_enc_list, + pred_context_pose=dict( + extrinsic=torch.cat([extrinsic, extrinsic_padding], dim=2).inverse(), + intrinsic=intrinsic, + ), + depth_dict=dict(depth=depth_map, conf_valid_mask=conf_valid_mask), + infos=infos, + distill_infos=distill_infos, + ) + + def get_data_shim(self) -> DataShim: + def data_shim(batch: BatchedExample) -> BatchedExample: + batch = apply_normalize_shim( + batch, + self.cfg.input_mean, + self.cfg.input_std, + ) + + return batch + + return data_shim diff --git a/src/model/encoder/backbone/__init__.py b/src/model/encoder/backbone/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39d389d36657d845a0a0b67f41a9f50f7b6f0e2a --- /dev/null +++ b/src/model/encoder/backbone/__init__.py @@ -0,0 +1,21 @@ +from typing import Any +import torch.nn as nn + +from .backbone import Backbone +from .backbone_croco_multiview import AsymmetricCroCoMulti +from .backbone_dino import BackboneDino, BackboneDinoCfg +from .backbone_resnet import BackboneResnet, BackboneResnetCfg +from .backbone_croco import AsymmetricCroCo, BackboneCrocoCfg + +BACKBONES: dict[str, Backbone[Any]] = { + "resnet": BackboneResnet, + "dino": BackboneDino, + "croco": AsymmetricCroCo, + "croco_multi": AsymmetricCroCoMulti, +} + +BackboneCfg = BackboneResnetCfg | BackboneDinoCfg | BackboneCrocoCfg + + +def get_backbone(cfg: BackboneCfg, d_in: int = 3) -> nn.Module: + return BACKBONES[cfg.name](cfg, d_in) diff --git a/src/model/encoder/backbone/backbone.py b/src/model/encoder/backbone/backbone.py new file mode 100644 index 0000000000000000000000000000000000000000..ca973d6da00fb71eab13a9dc84de587b7df2fe90 --- /dev/null +++ b/src/model/encoder/backbone/backbone.py @@ -0,0 +1,29 @@ +from abc import ABC, abstractmethod +from typing import Generic, TypeVar + +from jaxtyping import Float +from torch import Tensor, nn + +from src.dataset.types import BatchedViews + +T = TypeVar("T") + + +class Backbone(nn.Module, ABC, Generic[T]): + cfg: T + + def __init__(self, cfg: T) -> None: + super().__init__() + self.cfg = cfg + + @abstractmethod + def forward( + self, + context: BatchedViews, + ) -> Float[Tensor, "batch view d_out height width"]: + pass + + @property + @abstractmethod + def d_out(self) -> int: + pass diff --git a/src/model/encoder/backbone/backbone_croco.py b/src/model/encoder/backbone/backbone_croco.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9d5f1dad16fa48cdc790e3bf446eb6029e173a --- /dev/null +++ b/src/model/encoder/backbone/backbone_croco.py @@ -0,0 +1,281 @@ +from copy import deepcopy +from dataclasses import dataclass +from typing import Literal + +import torch +from torch import nn + +from .croco.blocks import DecoderBlock +from .croco.croco import CroCoNet +from .croco.misc import fill_default_args, freeze_all_params, transpose_to_landscape, is_symmetrized, interleave, \ + make_batch_symmetric +from .croco.patch_embed import get_patch_embed +from .backbone import Backbone +from src.geometry.camera_emb import get_intrinsic_embedding + + +inf = float('inf') + + +croco_params = { + 'ViTLarge_BaseDecoder': { + 'enc_depth': 24, + 'dec_depth': 12, + 'enc_embed_dim': 1024, + 'dec_embed_dim': 768, + 'enc_num_heads': 16, + 'dec_num_heads': 12, + 'pos_embed': 'RoPE100', + 'img_size': (512, 512), + }, +} + +default_dust3r_params = { + 'enc_depth': 24, + 'dec_depth': 12, + 'enc_embed_dim': 1024, + 'dec_embed_dim': 768, + 'enc_num_heads': 16, + 'dec_num_heads': 12, + 'pos_embed': 'RoPE100', + 'patch_embed_cls': 'PatchEmbedDust3R', + 'img_size': (512, 512), + 'head_type': 'dpt', + 'output_mode': 'pts3d', + 'depth_mode': ('exp', -inf, inf), + 'conf_mode': ('exp', 1, inf) +} + + +@dataclass +class BackboneCrocoCfg: + name: Literal["croco", "croco_multi"] + model: Literal["ViTLarge_BaseDecoder", "ViTBase_SmallDecoder", "ViTBase_BaseDecoder"] # keep interface for the last two models, but they are not supported + patch_embed_cls: str = 'PatchEmbedDust3R' # PatchEmbedDust3R or ManyAR_PatchEmbed + asymmetry_decoder: bool = True + intrinsics_embed_loc: Literal["encoder", "decoder", "none"] = 'none' + intrinsics_embed_degree: int = 0 + intrinsics_embed_type: Literal["pixelwise", "linear", "token"] = 'token' # linear or dpt + + +class AsymmetricCroCo(CroCoNet): + """ Two siamese encoders, followed by two decoders. + The goal is to output 3d points directly, both images in view1's frame + (hence the asymmetry). + """ + + def __init__(self, cfg: BackboneCrocoCfg, d_in: int) -> None: + + self.intrinsics_embed_loc = cfg.intrinsics_embed_loc + self.intrinsics_embed_degree = cfg.intrinsics_embed_degree + self.intrinsics_embed_type = cfg.intrinsics_embed_type + self.intrinsics_embed_encoder_dim = 0 + self.intrinsics_embed_decoder_dim = 0 + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise': + self.intrinsics_embed_encoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3 + elif self.intrinsics_embed_loc == 'decoder' and self.intrinsics_embed_type == 'pixelwise': + self.intrinsics_embed_decoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3 + + self.patch_embed_cls = cfg.patch_embed_cls + self.croco_args = fill_default_args(croco_params[cfg.model], CroCoNet.__init__) + + super().__init__(**croco_params[cfg.model]) + + if cfg.asymmetry_decoder: + self.dec_blocks2 = deepcopy(self.dec_blocks) # This is used in DUSt3R and MASt3R + + if self.intrinsics_embed_type == 'linear' or self.intrinsics_embed_type == 'token': + self.intrinsic_encoder = nn.Linear(9, 1024) + + # self.set_freeze(freeze) + + def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768, in_chans=3): + in_chans = in_chans + self.intrinsics_embed_encoder_dim + self.patch_embed = get_patch_embed(self.patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans) + + def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec): + self.dec_depth = dec_depth + self.dec_embed_dim = dec_embed_dim + # transfer from encoder to decoder + enc_embed_dim = enc_embed_dim + self.intrinsics_embed_decoder_dim + self.decoder_embed = nn.Linear(enc_embed_dim, dec_embed_dim, bias=True) + # transformer for the decoder + self.dec_blocks = nn.ModuleList([ + DecoderBlock(dec_embed_dim, dec_num_heads, mlp_ratio=mlp_ratio, qkv_bias=True, norm_layer=norm_layer, norm_mem=norm_im2_in_dec, rope=self.rope) + for i in range(dec_depth)]) + # final norm layer + self.dec_norm = norm_layer(dec_embed_dim) + + def load_state_dict(self, ckpt, **kw): + # duplicate all weights for the second decoder if not present + new_ckpt = dict(ckpt) + if not any(k.startswith('dec_blocks2') for k in ckpt): + for key, value in ckpt.items(): + if key.startswith('dec_blocks'): + new_ckpt[key.replace('dec_blocks', 'dec_blocks2')] = value + return super().load_state_dict(new_ckpt, **kw) + + def set_freeze(self, freeze): # this is for use by downstream models + assert freeze in ['none', 'mask', 'encoder'], f"unexpected freeze={freeze}" + to_be_frozen = { + 'none': [], + 'mask': [self.mask_token], + 'encoder': [self.mask_token, self.patch_embed, self.enc_blocks], + 'encoder_decoder': [self.mask_token, self.patch_embed, self.enc_blocks, self.enc_norm, self.decoder_embed, self.dec_blocks, self.dec_blocks2, self.dec_norm], + } + freeze_all_params(to_be_frozen[freeze]) + + def _set_prediction_head(self, *args, **kwargs): + """ No prediction head """ + return + + def _encode_image(self, image, true_shape, intrinsics_embed=None): + # embed the image into patches (x has size B x Npatches x C) + x, pos = self.patch_embed(image, true_shape=true_shape) + + if intrinsics_embed is not None: + + if self.intrinsics_embed_type == 'linear': + x = x + intrinsics_embed + elif self.intrinsics_embed_type == 'token': + x = torch.cat((x, intrinsics_embed), dim=1) + add_pose = pos[:, 0:1, :].clone() + add_pose[:, :, 0] += (pos[:, -1, 0].unsqueeze(-1) + 1) + pos = torch.cat((pos, add_pose), dim=1) + + # add positional embedding without cls token + assert self.enc_pos_embed is None + + # now apply the transformer encoder and normalization + for blk in self.enc_blocks: + x = blk(x, pos) + + x = self.enc_norm(x) + return x, pos, None + + def _encode_image_pairs(self, img1, img2, true_shape1, true_shape2, intrinsics_embed1=None, intrinsics_embed2=None): + if img1.shape[-2:] == img2.shape[-2:]: + out, pos, _ = self._encode_image(torch.cat((img1, img2), dim=0), + torch.cat((true_shape1, true_shape2), dim=0), + torch.cat((intrinsics_embed1, intrinsics_embed2), dim=0) if intrinsics_embed1 is not None else None) + out, out2 = out.chunk(2, dim=0) + pos, pos2 = pos.chunk(2, dim=0) + else: + out, pos, _ = self._encode_image(img1, true_shape1, intrinsics_embed1) + out2, pos2, _ = self._encode_image(img2, true_shape2, intrinsics_embed2) + return out, out2, pos, pos2 + + def _encode_symmetrized(self, view1, view2, force_asym=False): + img1 = view1['img'] + img2 = view2['img'] + B = img1.shape[0] + # Recover true_shape when available, otherwise assume that the img shape is the true one + shape1 = view1.get('true_shape', torch.tensor(img1.shape[-2:])[None].repeat(B, 1)) + shape2 = view2.get('true_shape', torch.tensor(img2.shape[-2:])[None].repeat(B, 1)) + # warning! maybe the images have different portrait/landscape orientations + + intrinsics_embed1 = view1.get('intrinsics_embed', None) + intrinsics_embed2 = view2.get('intrinsics_embed', None) + + if force_asym or not is_symmetrized(view1, view2): + feat1, feat2, pos1, pos2 = self._encode_image_pairs(img1, img2, shape1, shape2, intrinsics_embed1, intrinsics_embed2) + else: + # computing half of forward pass!' + feat1, feat2, pos1, pos2 = self._encode_image_pairs(img1[::2], img2[::2], shape1[::2], shape2[::2]) + feat1, feat2 = interleave(feat1, feat2) + pos1, pos2 = interleave(pos1, pos2) + + return (shape1, shape2), (feat1, feat2), (pos1, pos2) + + def _decoder(self, f1, pos1, f2, pos2, extra_embed1=None, extra_embed2=None): + final_output = [(f1, f2)] # before projection + + if extra_embed1 is not None: + f1 = torch.cat((f1, extra_embed1), dim=-1) + if extra_embed2 is not None: + f2 = torch.cat((f2, extra_embed2), dim=-1) + + # project to decoder dim + f1 = self.decoder_embed(f1) + f2 = self.decoder_embed(f2) + + final_output.append((f1, f2)) + for blk1, blk2 in zip(self.dec_blocks, self.dec_blocks2): + # img1 side + f1, _ = blk1(*final_output[-1][::+1], pos1, pos2) + # img2 side + f2, _ = blk2(*final_output[-1][::-1], pos2, pos1) + # store the result + final_output.append((f1, f2)) + + # normalize last output + del final_output[1] # duplicate with final_output[0] + final_output[-1] = tuple(map(self.dec_norm, final_output[-1])) + return zip(*final_output) + + def _downstream_head(self, head_num, decout, img_shape): + B, S, D = decout[-1].shape + # img_shape = tuple(map(int, img_shape)) + head = getattr(self, f'head{head_num}') + return head(decout, img_shape) + + def forward(self, + context: dict, + symmetrize_batch=False, + return_views=False, + ): + b, v, _, h, w = context["image"].shape + device = context["image"].device + + view1, view2 = ({'img': context["image"][:, 0]}, + {'img': context["image"][:, 1]}) + + # camera embedding in the encoder + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise': + intrinsic_emb = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree) + view1['img'] = torch.cat((view1['img'], intrinsic_emb[:, 0]), dim=1) + view2['img'] = torch.cat((view2['img'], intrinsic_emb[:, 1]), dim=1) + + if self.intrinsics_embed_loc == 'encoder' and (self.intrinsics_embed_type == 'token' or self.intrinsics_embed_type == 'linear'): + intrinsic_embedding = self.intrinsic_encoder(context["intrinsics"].flatten(2)) + view1['intrinsics_embed'] = intrinsic_embedding[:, 0].unsqueeze(1) + view2['intrinsics_embed'] = intrinsic_embedding[:, 1].unsqueeze(1) + + if symmetrize_batch: + instance_list_view1, instance_list_view2 = [0 for _ in range(b)], [1 for _ in range(b)] + view1['instance'] = instance_list_view1 + view2['instance'] = instance_list_view2 + view1['idx'] = instance_list_view1 + view2['idx'] = instance_list_view2 + view1, view2 = make_batch_symmetric(view1, view2) + + # encode the two images --> B,S,D + (shape1, shape2), (feat1, feat2), (pos1, pos2) = self._encode_symmetrized(view1, view2, force_asym=False) + else: + # encode the two images --> B,S,D + (shape1, shape2), (feat1, feat2), (pos1, pos2) = self._encode_symmetrized(view1, view2, force_asym=True) + + if self.intrinsics_embed_loc == 'decoder': + # FIXME: downsample is hardcoded to 16 + intrinsic_emb = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree, downsample=16, merge_hw=True) + dec1, dec2 = self._decoder(feat1, pos1, feat2, pos2, intrinsic_emb[:, 0], intrinsic_emb[:, 1]) + else: + dec1, dec2 = self._decoder(feat1, pos1, feat2, pos2) + + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'token': + dec1, dec2 = list(dec1), list(dec2) + for i in range(len(dec1)): + dec1[i] = dec1[i][:, :-1] + dec2[i] = dec2[i][:, :-1] + + if return_views: + return dec1, dec2, shape1, shape2, view1, view2 + return dec1, dec2, shape1, shape2 + + @property + def patch_size(self) -> int: + return 16 + + @property + def d_out(self) -> int: + return 1024 diff --git a/src/model/encoder/backbone/backbone_croco_multiview.py b/src/model/encoder/backbone/backbone_croco_multiview.py new file mode 100644 index 0000000000000000000000000000000000000000..ee14d1f21ea8fc82f3b1ff5a79f799b2db693c73 --- /dev/null +++ b/src/model/encoder/backbone/backbone_croco_multiview.py @@ -0,0 +1,245 @@ +from copy import deepcopy +from dataclasses import dataclass +from typing import Literal + +import torch +from einops import rearrange +from torch import nn + +from .croco.blocks import DecoderBlock +from .croco.croco import CroCoNet +from .croco.misc import fill_default_args, freeze_all_params, transpose_to_landscape, is_symmetrized, interleave, \ + make_batch_symmetric +from .croco.patch_embed import get_patch_embed +from .backbone import Backbone +from src.geometry.camera_emb import get_intrinsic_embedding + +inf = float('inf') + + +croco_params = { + 'ViTLarge_BaseDecoder': { + 'enc_depth': 24, + 'dec_depth': 12, + 'enc_embed_dim': 1024, + 'dec_embed_dim': 768, + 'enc_num_heads': 16, + 'dec_num_heads': 12, + 'pos_embed': 'RoPE100', + 'img_size': (512, 512), + }, +} + +default_dust3r_params = { + 'enc_depth': 24, + 'dec_depth': 12, + 'enc_embed_dim': 1024, + 'dec_embed_dim': 768, + 'enc_num_heads': 16, + 'dec_num_heads': 12, + 'pos_embed': 'RoPE100', + 'patch_embed_cls': 'PatchEmbedDust3R', + 'img_size': (512, 512), + 'head_type': 'dpt', + 'output_mode': 'pts3d', + 'depth_mode': ('exp', -inf, inf), + 'conf_mode': ('exp', 1, inf) +} + + +@dataclass +class BackboneCrocoCfg: + name: Literal["croco"] + model: Literal["ViTLarge_BaseDecoder", "ViTBase_SmallDecoder", "ViTBase_BaseDecoder"] # keep interface for the last two models, but they are not supported + patch_embed_cls: str = 'PatchEmbedDust3R' # PatchEmbedDust3R or ManyAR_PatchEmbed + asymmetry_decoder: bool = True + intrinsics_embed_loc: Literal["encoder", "decoder", "none"] = 'none' + intrinsics_embed_degree: int = 0 + intrinsics_embed_type: Literal["pixelwise", "linear", "token"] = 'token' # linear or dpt + + +class AsymmetricCroCoMulti(CroCoNet): + """ Two siamese encoders, followed by two decoders. + The goal is to output 3d points directly, both images in view1's frame + (hence the asymmetry). + """ + + def __init__(self, cfg: BackboneCrocoCfg, d_in: int) -> None: + + self.intrinsics_embed_loc = cfg.intrinsics_embed_loc + self.intrinsics_embed_degree = cfg.intrinsics_embed_degree + self.intrinsics_embed_type = cfg.intrinsics_embed_type + self.intrinsics_embed_encoder_dim = 0 + self.intrinsics_embed_decoder_dim = 0 + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise': + self.intrinsics_embed_encoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3 + elif self.intrinsics_embed_loc == 'decoder' and self.intrinsics_embed_type == 'pixelwise': + self.intrinsics_embed_decoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3 + + self.patch_embed_cls = cfg.patch_embed_cls + self.croco_args = fill_default_args(croco_params[cfg.model], CroCoNet.__init__) + + super().__init__(**croco_params[cfg.model]) + + if cfg.asymmetry_decoder: + self.dec_blocks2 = deepcopy(self.dec_blocks) # This is used in DUSt3R and MASt3R + + if self.intrinsics_embed_type == 'linear' or self.intrinsics_embed_type == 'token': + self.intrinsic_encoder = nn.Linear(9, 1024) + + # self.set_downstream_head(output_mode, head_type, landscape_only, depth_mode, conf_mode, **croco_kwargs) + # self.set_freeze(freeze) + + def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768, in_chans=3): + in_chans = in_chans + self.intrinsics_embed_encoder_dim + self.patch_embed = get_patch_embed(self.patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans) + + def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec): + self.dec_depth = dec_depth + self.dec_embed_dim = dec_embed_dim + # transfer from encoder to decoder + enc_embed_dim = enc_embed_dim + self.intrinsics_embed_decoder_dim + self.decoder_embed = nn.Linear(enc_embed_dim, dec_embed_dim, bias=True) + # transformer for the decoder + self.dec_blocks = nn.ModuleList([ + DecoderBlock(dec_embed_dim, dec_num_heads, mlp_ratio=mlp_ratio, qkv_bias=True, norm_layer=norm_layer, norm_mem=norm_im2_in_dec, rope=self.rope) + for i in range(dec_depth)]) + # final norm layer + self.dec_norm = norm_layer(dec_embed_dim) + + def load_state_dict(self, ckpt, **kw): + # duplicate all weights for the second decoder if not present + new_ckpt = dict(ckpt) + if not any(k.startswith('dec_blocks2') for k in ckpt): + for key, value in ckpt.items(): + if key.startswith('dec_blocks'): + new_ckpt[key.replace('dec_blocks', 'dec_blocks2')] = value + return super().load_state_dict(new_ckpt, **kw) + + def set_freeze(self, freeze): # this is for use by downstream models + assert freeze in ['none', 'mask', 'encoder'], f"unexpected freeze={freeze}" + to_be_frozen = { + 'none': [], + 'mask': [self.mask_token], + 'encoder': [self.mask_token, self.patch_embed, self.enc_blocks], + 'encoder_decoder': [self.mask_token, self.patch_embed, self.enc_blocks, self.enc_norm, self.decoder_embed, self.dec_blocks, self.dec_blocks2, self.dec_norm], + } + freeze_all_params(to_be_frozen[freeze]) + + def _set_prediction_head(self, *args, **kwargs): + """ No prediction head """ + return + + def _encode_image(self, image, true_shape, intrinsics_embed=None): + # embed the image into patches (x has size B x Npatches x C) + x, pos = self.patch_embed(image, true_shape=true_shape) + + if intrinsics_embed is not None: + + if self.intrinsics_embed_type == 'linear': + x = x + intrinsics_embed + elif self.intrinsics_embed_type == 'token': + x = torch.cat((x, intrinsics_embed), dim=1) + add_pose = pos[:, 0:1, :].clone() + add_pose[:, :, 0] += (pos[:, -1, 0].unsqueeze(-1) + 1) + pos = torch.cat((pos, add_pose), dim=1) + + # add positional embedding without cls token + assert self.enc_pos_embed is None + + # now apply the transformer encoder and normalization + for blk in self.enc_blocks: + x = blk(x, pos) + + x = self.enc_norm(x) + return x, pos, None + + def _decoder(self, feat, pose, extra_embed=None): + b, v, l, c = feat.shape + final_output = [feat] # before projection + if extra_embed is not None: + feat = torch.cat((feat, extra_embed), dim=-1) + + # project to decoder dim + f = rearrange(feat, "b v l c -> (b v) l c") + f = self.decoder_embed(f) + f = rearrange(f, "(b v) l c -> b v l c", b=b, v=v) + final_output.append(f) + + def generate_ctx_views(x): + b, v, l, c = x.shape + ctx_views = x.unsqueeze(1).expand(b, v, v, l, c) + mask = torch.arange(v).unsqueeze(0) != torch.arange(v).unsqueeze(1) + ctx_views = ctx_views[:, mask].reshape(b, v, v - 1, l, c) # B, V, V-1, L, C + ctx_views = ctx_views.flatten(2, 3) # B, V, (V-1)*L, C + return ctx_views.contiguous() + + pos_ctx = generate_ctx_views(pose) + for blk1, blk2 in zip(self.dec_blocks, self.dec_blocks2): + feat_current = final_output[-1] + feat_current_ctx = generate_ctx_views(feat_current) + # img1 side + f1, _ = blk1(feat_current[:, 0].contiguous(), feat_current_ctx[:, 0].contiguous(), pose[:, 0].contiguous(), pos_ctx[:, 0].contiguous()) + f1 = f1.unsqueeze(1) + # img2 side + f2, _ = blk2(rearrange(feat_current[:, 1:], "b v l c -> (b v) l c"), + rearrange(feat_current_ctx[:, 1:], "b v l c -> (b v) l c"), + rearrange(pose[:, 1:], "b v l c -> (b v) l c"), + rearrange(pos_ctx[:, 1:], "b v l c -> (b v) l c")) + f2 = rearrange(f2, "(b v) l c -> b v l c", b=b, v=v-1) + # store the result + final_output.append(torch.cat((f1, f2), dim=1)) + + # normalize last output + del final_output[1] # duplicate with final_output[0] + last_feat = rearrange(final_output[-1], "b v l c -> (b v) l c") + last_feat = self.dec_norm(last_feat) + final_output[-1] = rearrange(last_feat, "(b v) l c -> b v l c", b=b, v=v) + return final_output + + def forward(self, + context: dict, + symmetrize_batch=False, + return_views=False, + ): + b, v, _, h, w = context["image"].shape + images_all = context["image"] + + # camera embedding in the encoder + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise': + intrinsic_embedding = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree) + images_all = torch.cat((images_all, intrinsic_embedding), dim=2) + + intrinsic_embedding_all = None + if self.intrinsics_embed_loc == 'encoder' and (self.intrinsics_embed_type == 'token' or self.intrinsics_embed_type == 'linear'): + intrinsic_embedding = self.intrinsic_encoder(context["intrinsics"].flatten(2)) + intrinsic_embedding_all = rearrange(intrinsic_embedding, "b v c -> (b v) c").unsqueeze(1) + + # step 1: encoder input images + images_all = rearrange(images_all, "b v c h w -> (b v) c h w") + shape_all = torch.tensor(images_all.shape[-2:])[None].repeat(b*v, 1) + + feat, pose, _ = self._encode_image(images_all, shape_all, intrinsic_embedding_all) + + feat = rearrange(feat, "(b v) l c -> b v l c", b=b, v=v) + pose = rearrange(pose, "(b v) l c -> b v l c", b=b, v=v) + + # step 2: decoder + dec_feat = self._decoder(feat, pose) + shape = rearrange(shape_all, "(b v) c -> b v c", b=b, v=v) + images = rearrange(images_all, "(b v) c h w -> b v c h w", b=b, v=v) + + if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'token': + dec_feat = list(dec_feat) + for i in range(len(dec_feat)): + dec_feat[i] = dec_feat[i][:, :, :-1] + + return dec_feat, shape, images + + @property + def patch_size(self) -> int: + return 16 + + @property + def d_out(self) -> int: + return 1024 diff --git a/src/model/encoder/backbone/backbone_dino.py b/src/model/encoder/backbone/backbone_dino.py new file mode 100644 index 0000000000000000000000000000000000000000..af12206a9d3d60ae26c4b0088f2b7b2e3fe00ea2 --- /dev/null +++ b/src/model/encoder/backbone/backbone_dino.py @@ -0,0 +1,79 @@ +from dataclasses import dataclass +from typing import Literal + +import torch +from einops import rearrange, repeat +from jaxtyping import Float +from torch import Tensor, nn + +from src.dataset.types import BatchedViews +from .backbone import Backbone +from .backbone_resnet import BackboneResnet, BackboneResnetCfg + + +@dataclass +class BackboneDinoCfg: + name: Literal["dino"] + model: Literal["dino_vits16", "dino_vits8", "dino_vitb16", "dino_vitb8"] + d_out: int + + +class BackboneDino(Backbone[BackboneDinoCfg]): + def __init__(self, cfg: BackboneDinoCfg, d_in: int) -> None: + super().__init__(cfg) + assert d_in == 3 + self.dino = torch.hub.load("facebookresearch/dino:main", cfg.model) + self.resnet_backbone = BackboneResnet( + BackboneResnetCfg("resnet", "dino_resnet50", 4, False, cfg.d_out), + d_in, + ) + self.global_token_mlp = nn.Sequential( + nn.Linear(768, 768), + nn.ReLU(), + nn.Linear(768, cfg.d_out), + ) + self.local_token_mlp = nn.Sequential( + nn.Linear(768, 768), + nn.ReLU(), + nn.Linear(768, cfg.d_out), + ) + + def forward( + self, + context: BatchedViews, + ) -> Float[Tensor, "batch view d_out height width"]: + # Compute features from the DINO-pretrained resnet50. + resnet_features = self.resnet_backbone(context) + + # Compute features from the DINO-pretrained ViT. + b, v, _, h, w = context["image"].shape + assert h % self.patch_size == 0 and w % self.patch_size == 0 + tokens = rearrange(context["image"], "b v c h w -> (b v) c h w") + tokens = self.dino.get_intermediate_layers(tokens)[0] + global_token = self.global_token_mlp(tokens[:, 0]) + local_tokens = self.local_token_mlp(tokens[:, 1:]) + + # Repeat the global token to match the image shape. + global_token = repeat(global_token, "(b v) c -> b v c h w", b=b, v=v, h=h, w=w) + + # Repeat the local tokens to match the image shape. + local_tokens = repeat( + local_tokens, + "(b v) (h w) c -> b v c (h hps) (w wps)", + b=b, + v=v, + h=h // self.patch_size, + hps=self.patch_size, + w=w // self.patch_size, + wps=self.patch_size, + ) + + return resnet_features + local_tokens + global_token + + @property + def patch_size(self) -> int: + return int("".join(filter(str.isdigit, self.cfg.model))) + + @property + def d_out(self) -> int: + return self.cfg.d_out diff --git a/src/model/encoder/backbone/backbone_resnet.py b/src/model/encoder/backbone/backbone_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb0183989df1663d43638feb95bfa8813d0aed9 --- /dev/null +++ b/src/model/encoder/backbone/backbone_resnet.py @@ -0,0 +1,100 @@ +import functools +from dataclasses import dataclass +from typing import Literal + +import torch +import torch.nn.functional as F +import torchvision +from einops import rearrange +from jaxtyping import Float +from torch import Tensor, nn +from torchvision.models import ResNet + +from src.dataset.types import BatchedViews +from .backbone import Backbone + + +@dataclass +class BackboneResnetCfg: + name: Literal["resnet"] + model: Literal[ + "resnet18", "resnet34", "resnet50", "resnet101", "resnet152", "dino_resnet50" + ] + num_layers: int + use_first_pool: bool + d_out: int + + +class BackboneResnet(Backbone[BackboneResnetCfg]): + model: ResNet + + def __init__(self, cfg: BackboneResnetCfg, d_in: int) -> None: + super().__init__(cfg) + + assert d_in == 3 + + norm_layer = functools.partial( + nn.InstanceNorm2d, + affine=False, + track_running_stats=False, + ) + + if cfg.model == "dino_resnet50": + self.model = torch.hub.load("facebookresearch/dino:main", "dino_resnet50") + else: + self.model = getattr(torchvision.models, cfg.model)(norm_layer=norm_layer) + + # Set up projections + self.projections = nn.ModuleDict({}) + for index in range(1, cfg.num_layers): + key = f"layer{index}" + block = getattr(self.model, key) + conv_index = 1 + try: + while True: + d_layer_out = getattr(block[-1], f"conv{conv_index}").out_channels + conv_index += 1 + except AttributeError: + pass + self.projections[key] = nn.Conv2d(d_layer_out, cfg.d_out, 1) + + # Add a projection for the first layer. + self.projections["layer0"] = nn.Conv2d( + self.model.conv1.out_channels, cfg.d_out, 1 + ) + + def forward( + self, + context: BatchedViews, + ) -> Float[Tensor, "batch view d_out height width"]: + # Merge the batch dimensions. + b, v, _, h, w = context["image"].shape + x = rearrange(context["image"], "b v c h w -> (b v) c h w") + + # Run the images through the resnet. + x = self.model.conv1(x) + x = self.model.bn1(x) + x = self.model.relu(x) + features = [self.projections["layer0"](x)] + + # Propagate the input through the resnet's layers. + for index in range(1, self.cfg.num_layers): + key = f"layer{index}" + if index == 0 and self.cfg.use_first_pool: + x = self.model.maxpool(x) + x = getattr(self.model, key)(x) + features.append(self.projections[key](x)) + + # Upscale the features. + features = [ + F.interpolate(f, (h, w), mode="bilinear", align_corners=True) + for f in features + ] + features = torch.stack(features).sum(dim=0) + + # Separate batch dimensions. + return rearrange(features, "(b v) c h w -> b v c h w", b=b, v=v) + + @property + def d_out(self) -> int: + return self.cfg.d_out diff --git a/src/model/encoder/backbone/croco/README.md b/src/model/encoder/backbone/croco/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a565eca32de791bd57afa7f9cc8c288e20ae95c9 --- /dev/null +++ b/src/model/encoder/backbone/croco/README.md @@ -0,0 +1,7 @@ +Most of the code under src/model/encoder/backbone/croco/ is from the original CROCO implementation. +The code is not modified in any way except the relative module path. +The original code can be found at [croco Github Repo](https://github.com/naver/croco/tree/743ee71a2a9bf57cea6832a9064a70a0597fcfcb/models). + + +Except: +- 'misc.py', 'patch_embed.py' is from DUSt3R. \ No newline at end of file diff --git a/src/model/encoder/backbone/croco/__init__.py b/src/model/encoder/backbone/croco/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/model/encoder/backbone/croco/blocks.py b/src/model/encoder/backbone/croco/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..75bce410b952660b03bae1876aa29c3877c4e753 --- /dev/null +++ b/src/model/encoder/backbone/croco/blocks.py @@ -0,0 +1,241 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + + +# -------------------------------------------------------- +# Main encoder/decoder blocks +# -------------------------------------------------------- +# References: +# timm +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/helpers.py +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/mlp.py +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/patch_embed.py + + +import torch +import torch.nn as nn + +from itertools import repeat +import collections.abc + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): + return x + return tuple(repeat(x, n)) + return parse +to_2tuple = _ntuple(2) + +def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + if drop_prob == 0. or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) + + def extra_repr(self): + return f'drop_prob={round(self.drop_prob,3):0.3f}' + +class Mlp(nn.Module): + """ MLP as used in Vision Transformer, MLP-Mixer and related networks""" + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + bias = to_2tuple(bias) + drop_probs = to_2tuple(drop) + + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0]) + self.act = act_layer() + self.drop1 = nn.Dropout(drop_probs[0]) + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1]) + self.drop2 = nn.Dropout(drop_probs[1]) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop1(x) + x = self.fc2(x) + x = self.drop2(x) + return x + +class Attention(nn.Module): + + def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim ** -0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.rope = rope + + def forward(self, x, xpos): + B, N, C = x.shape + + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).transpose(1,3) + q, k, v = [qkv[:,:,i] for i in range(3)] + # q,k,v = qkv.unbind(2) # make torchscript happy (cannot use tensor as tuple) + + if self.rope is not None: + q = self.rope(q, xpos) + k = self.rope(k, xpos) + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class Block(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, rope=None): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, xpos): + x = x + self.drop_path(self.attn(self.norm1(x), xpos)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + +class CrossAttention(nn.Module): + + def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim ** -0.5 + + self.projq = nn.Linear(dim, dim, bias=qkv_bias) + self.projk = nn.Linear(dim, dim, bias=qkv_bias) + self.projv = nn.Linear(dim, dim, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + self.rope = rope + + def forward(self, query, key, value, qpos, kpos): + B, Nq, C = query.shape + Nk = key.shape[1] + Nv = value.shape[1] + + q = self.projq(query).reshape(B,Nq,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) + k = self.projk(key).reshape(B,Nk,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) + v = self.projv(value).reshape(B,Nv,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3) + + if self.rope is not None: + q = self.rope(q, qpos) + k = self.rope(k, kpos) + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, Nq, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class DecoderBlock(nn.Module): + + def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, norm_mem=True, rope=None): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) + self.cross_attn = CrossAttention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop) + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + self.norm2 = norm_layer(dim) + self.norm3 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + self.norm_y = norm_layer(dim) if norm_mem else nn.Identity() + + def forward(self, x, y, xpos, ypos): + x = x + self.drop_path(self.attn(self.norm1(x), xpos)) + y_ = self.norm_y(y) + x = x + self.drop_path(self.cross_attn(self.norm2(x), y_, y_, xpos, ypos)) + x = x + self.drop_path(self.mlp(self.norm3(x))) + return x, y + + +# patch embedding +class PositionGetter(object): + """ return positions of patches """ + + def __init__(self): + self.cache_positions = {} + + def __call__(self, b, h, w, device): + if not (h,w) in self.cache_positions: + x = torch.arange(w, device=device) + y = torch.arange(h, device=device) + self.cache_positions[h,w] = torch.cartesian_prod(y, x) # (h, w, 2) + pos = self.cache_positions[h,w].view(1, h*w, 2).expand(b, -1, 2).clone() + return pos + +class PatchEmbed(nn.Module): + """ just adding _init_weights + position getter compared to timm.models.layers.patch_embed.PatchEmbed""" + + def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + self.img_size = img_size + self.patch_size = patch_size + self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) + self.num_patches = self.grid_size[0] * self.grid_size[1] + self.flatten = flatten + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + self.position_getter = PositionGetter() + + def forward(self, x): + B, C, H, W = x.shape + torch._assert(H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).") + torch._assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).") + x = self.proj(x) + pos = self.position_getter(B, x.size(2), x.size(3), x.device) + if self.flatten: + x = x.flatten(2).transpose(1, 2) # BCHW -> BNC + x = self.norm(x) + return x, pos + + def _init_weights(self): + w = self.proj.weight.data + torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + diff --git a/src/model/encoder/backbone/croco/croco.py b/src/model/encoder/backbone/croco/croco.py new file mode 100644 index 0000000000000000000000000000000000000000..fd4b31a69501f88a165ab49a99c744026d2ee6b1 --- /dev/null +++ b/src/model/encoder/backbone/croco/croco.py @@ -0,0 +1,249 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + + +# -------------------------------------------------------- +# CroCo model during pretraining +# -------------------------------------------------------- + + + +import torch +import torch.nn as nn +torch.backends.cuda.matmul.allow_tf32 = True # for gpu >= Ampere and pytorch >= 1.12 +from functools import partial + +from .blocks import Block, DecoderBlock, PatchEmbed +from .pos_embed import get_2d_sincos_pos_embed, RoPE2D +from .masking import RandomMask + + +class CroCoNet(nn.Module): + + def __init__(self, + img_size=224, # input image size + patch_size=16, # patch_size + mask_ratio=0.9, # ratios of masked tokens + enc_embed_dim=768, # encoder feature dimension + enc_depth=12, # encoder depth + enc_num_heads=12, # encoder number of heads in the transformer block + dec_embed_dim=512, # decoder feature dimension + dec_depth=8, # decoder depth + dec_num_heads=16, # decoder number of heads in the transformer block + mlp_ratio=4, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + norm_im2_in_dec=True, # whether to apply normalization of the 'memory' = (second image) in the decoder + pos_embed='cosine', # positional embedding (either cosine or RoPE100) + ): + + super(CroCoNet, self).__init__() + + # patch embeddings (with initialization done as in MAE) + self._set_patch_embed(img_size, patch_size, enc_embed_dim) + + # mask generations + self._set_mask_generator(self.patch_embed.num_patches, mask_ratio) + + self.pos_embed = pos_embed + if pos_embed=='cosine': + # positional embedding of the encoder + enc_pos_embed = get_2d_sincos_pos_embed(enc_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0) + self.register_buffer('enc_pos_embed', torch.from_numpy(enc_pos_embed).float()) + # positional embedding of the decoder + dec_pos_embed = get_2d_sincos_pos_embed(dec_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0) + self.register_buffer('dec_pos_embed', torch.from_numpy(dec_pos_embed).float()) + # pos embedding in each block + self.rope = None # nothing for cosine + elif pos_embed.startswith('RoPE'): # eg RoPE100 + self.enc_pos_embed = None # nothing to add in the encoder with RoPE + self.dec_pos_embed = None # nothing to add in the decoder with RoPE + if RoPE2D is None: raise ImportError("Cannot find cuRoPE2D, please install it following the README instructions") + freq = float(pos_embed[len('RoPE'):]) + self.rope = RoPE2D(freq=freq) + else: + raise NotImplementedError('Unknown pos_embed '+pos_embed) + + # transformer for the encoder + self.enc_depth = enc_depth + self.enc_embed_dim = enc_embed_dim + self.enc_blocks = nn.ModuleList([ + Block(enc_embed_dim, enc_num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer, rope=self.rope) + for i in range(enc_depth)]) + self.enc_norm = norm_layer(enc_embed_dim) + + # masked tokens + self._set_mask_token(dec_embed_dim) + + # decoder + self._set_decoder(enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec) + + # prediction head + self._set_prediction_head(dec_embed_dim, patch_size) + + # initializer weights + self.initialize_weights() + + def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768): + self.patch_embed = PatchEmbed(img_size, patch_size, 3, enc_embed_dim) + + def _set_mask_generator(self, num_patches, mask_ratio): + self.mask_generator = RandomMask(num_patches, mask_ratio) + + def _set_mask_token(self, dec_embed_dim): + self.mask_token = nn.Parameter(torch.zeros(1, 1, dec_embed_dim)) + + def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec): + self.dec_depth = dec_depth + self.dec_embed_dim = dec_embed_dim + # transfer from encoder to decoder + self.decoder_embed = nn.Linear(enc_embed_dim+0, dec_embed_dim, bias=True) + # transformer for the decoder + self.dec_blocks = nn.ModuleList([ + DecoderBlock(dec_embed_dim, dec_num_heads, mlp_ratio=mlp_ratio, qkv_bias=True, norm_layer=norm_layer, norm_mem=norm_im2_in_dec, rope=self.rope) + for i in range(dec_depth)]) + # final norm layer + self.dec_norm = norm_layer(dec_embed_dim) + + def _set_prediction_head(self, dec_embed_dim, patch_size): + self.prediction_head = nn.Linear(dec_embed_dim, patch_size**2 * 3, bias=True) + + + def initialize_weights(self): + # patch embed + self.patch_embed._init_weights() + # mask tokens + if self.mask_token is not None: torch.nn.init.normal_(self.mask_token, std=.02) + # linears and layer norms + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + # we use xavier_uniform following official JAX ViT: + torch.nn.init.xavier_uniform_(m.weight) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def _encode_image(self, image, do_mask=False, return_all_blocks=False): + """ + image has B x 3 x img_size x img_size + do_mask: whether to perform masking or not + return_all_blocks: if True, return the features at the end of every block + instead of just the features from the last block (eg for some prediction heads) + """ + # embed the image into patches (x has size B x Npatches x C) + # and get position if each return patch (pos has size B x Npatches x 2) + x, pos = self.patch_embed(image) + # add positional embedding without cls token + if self.enc_pos_embed is not None: + x = x + self.enc_pos_embed[None,...] + # apply masking + B,N,C = x.size() + if do_mask: + masks = self.mask_generator(x) + x = x[~masks].view(B, -1, C) + posvis = pos[~masks].view(B, -1, 2) + else: + B,N,C = x.size() + masks = torch.zeros((B,N), dtype=bool) + posvis = pos + # now apply the transformer encoder and normalization + if return_all_blocks: + out = [] + for blk in self.enc_blocks: + x = blk(x, posvis) + out.append(x) + out[-1] = self.enc_norm(out[-1]) + return out, pos, masks + else: + for blk in self.enc_blocks: + x = blk(x, posvis) + x = self.enc_norm(x) + return x, pos, masks + + def _decoder(self, feat1, pos1, masks1, feat2, pos2, return_all_blocks=False): + """ + return_all_blocks: if True, return the features at the end of every block + instead of just the features from the last block (eg for some prediction heads) + + masks1 can be None => assume image1 fully visible + """ + # encoder to decoder layer + visf1 = self.decoder_embed(feat1) + f2 = self.decoder_embed(feat2) + # append masked tokens to the sequence + B,Nenc,C = visf1.size() + if masks1 is None: # downstreams + f1_ = visf1 + else: # pretraining + Ntotal = masks1.size(1) + f1_ = self.mask_token.repeat(B, Ntotal, 1).to(dtype=visf1.dtype) + f1_[~masks1] = visf1.view(B * Nenc, C) + # add positional embedding + if self.dec_pos_embed is not None: + f1_ = f1_ + self.dec_pos_embed + f2 = f2 + self.dec_pos_embed + # apply Transformer blocks + out = f1_ + out2 = f2 + if return_all_blocks: + _out, out = out, [] + for blk in self.dec_blocks: + _out, out2 = blk(_out, out2, pos1, pos2) + out.append(_out) + out[-1] = self.dec_norm(out[-1]) + else: + for blk in self.dec_blocks: + out, out2 = blk(out, out2, pos1, pos2) + out = self.dec_norm(out) + return out + + def patchify(self, imgs): + """ + imgs: (B, 3, H, W) + x: (B, L, patch_size**2 *3) + """ + p = self.patch_embed.patch_size[0] + assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0 + + h = w = imgs.shape[2] // p + x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p)) + x = torch.einsum('nchpwq->nhwpqc', x) + x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3)) + + return x + + def unpatchify(self, x, channels=3): + """ + x: (N, L, patch_size**2 *channels) + imgs: (N, 3, H, W) + """ + patch_size = self.patch_embed.patch_size[0] + h = w = int(x.shape[1]**.5) + assert h * w == x.shape[1] + x = x.reshape(shape=(x.shape[0], h, w, patch_size, patch_size, channels)) + x = torch.einsum('nhwpqc->nchpwq', x) + imgs = x.reshape(shape=(x.shape[0], channels, h * patch_size, h * patch_size)) + return imgs + + def forward(self, img1, img2): + """ + img1: tensor of size B x 3 x img_size x img_size + img2: tensor of size B x 3 x img_size x img_size + + out will be B x N x (3*patch_size*patch_size) + masks are also returned as B x N just in case + """ + # encoder of the masked first image + feat1, pos1, mask1 = self._encode_image(img1, do_mask=True) + # encoder of the second image + feat2, pos2, _ = self._encode_image(img2, do_mask=False) + # decoder + decfeat = self._decoder(feat1, pos1, mask1, feat2, pos2) + # prediction head + out = self.prediction_head(decfeat) + # get target + target = self.patchify(img1) + return out, mask1, target diff --git a/src/model/encoder/backbone/croco/curope/__init__.py b/src/model/encoder/backbone/croco/curope/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..81ef84436b6e7cf447c349099f50f56388b9eb4d --- /dev/null +++ b/src/model/encoder/backbone/croco/curope/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + +from .curope2d import cuRoPE2D diff --git a/src/model/encoder/backbone/croco/curope/curope.cpp b/src/model/encoder/backbone/croco/curope/curope.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaa0905bd5bd6d117ff16750fd26b56aa818c8bb --- /dev/null +++ b/src/model/encoder/backbone/croco/curope/curope.cpp @@ -0,0 +1,69 @@ +/* + Copyright (C) 2022-present Naver Corporation. All rights reserved. + Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +*/ + +#include + +// forward declaration +void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd ); + +void rope_2d_cpu( torch::Tensor tokens, const torch::Tensor positions, const float base, const float fwd ) +{ + const int B = tokens.size(0); + const int N = tokens.size(1); + const int H = tokens.size(2); + const int D = tokens.size(3) / 4; + + auto tok = tokens.accessor(); + auto pos = positions.accessor(); + + for (int b = 0; b < B; b++) { + for (int x = 0; x < 2; x++) { // y and then x (2d) + for (int n = 0; n < N; n++) { + + // grab the token position + const int p = pos[b][n][x]; + + for (int h = 0; h < H; h++) { + for (int d = 0; d < D; d++) { + // grab the two values + float u = tok[b][n][h][d+0+x*2*D]; + float v = tok[b][n][h][d+D+x*2*D]; + + // grab the cos,sin + const float inv_freq = fwd * p / powf(base, d/float(D)); + float c = cosf(inv_freq); + float s = sinf(inv_freq); + + // write the result + tok[b][n][h][d+0+x*2*D] = u*c - v*s; + tok[b][n][h][d+D+x*2*D] = v*c + u*s; + } + } + } + } + } +} + +void rope_2d( torch::Tensor tokens, // B,N,H,D + const torch::Tensor positions, // B,N,2 + const float base, + const float fwd ) +{ + TORCH_CHECK(tokens.dim() == 4, "tokens must have 4 dimensions"); + TORCH_CHECK(positions.dim() == 3, "positions must have 3 dimensions"); + TORCH_CHECK(tokens.size(0) == positions.size(0), "batch size differs between tokens & positions"); + TORCH_CHECK(tokens.size(1) == positions.size(1), "seq_length differs between tokens & positions"); + TORCH_CHECK(positions.size(2) == 2, "positions.shape[2] must be equal to 2"); + TORCH_CHECK(tokens.is_cuda() == positions.is_cuda(), "tokens and positions are not on the same device" ); + + if (tokens.is_cuda()) + rope_2d_cuda( tokens, positions, base, fwd ); + else + rope_2d_cpu( tokens, positions, base, fwd ); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("rope_2d", &rope_2d, "RoPE 2d forward/backward"); +} diff --git a/src/model/encoder/backbone/croco/curope/curope2d.py b/src/model/encoder/backbone/croco/curope/curope2d.py new file mode 100644 index 0000000000000000000000000000000000000000..407f5c614f9d62a1f0ce7833858b6c7db053eed3 --- /dev/null +++ b/src/model/encoder/backbone/croco/curope/curope2d.py @@ -0,0 +1,40 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + +import torch + +try: + import curope as _kernels # run `python setup.py install` +except ModuleNotFoundError: + from . import curope as _kernels # run `python setup.py build_ext --inplace` + + +class cuRoPE2D_func (torch.autograd.Function): + + @staticmethod + def forward(ctx, tokens, positions, base, F0=1): + ctx.save_for_backward(positions) + ctx.saved_base = base + ctx.saved_F0 = F0 + # tokens = tokens.clone() # uncomment this if inplace doesn't work + _kernels.rope_2d( tokens, positions, base, F0 ) + ctx.mark_dirty(tokens) + return tokens + + @staticmethod + def backward(ctx, grad_res): + positions, base, F0 = ctx.saved_tensors[0], ctx.saved_base, ctx.saved_F0 + _kernels.rope_2d( grad_res, positions, base, -F0 ) + ctx.mark_dirty(grad_res) + return grad_res, None, None, None + + +class cuRoPE2D(torch.nn.Module): + def __init__(self, freq=100.0, F0=1.0): + super().__init__() + self.base = freq + self.F0 = F0 + + def forward(self, tokens, positions): + cuRoPE2D_func.apply( tokens.transpose(1,2), positions, self.base, self.F0 ) + return tokens \ No newline at end of file diff --git a/src/model/encoder/backbone/croco/curope/kernels.cu b/src/model/encoder/backbone/croco/curope/kernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..b9425fdfcb05e04b7ca496dd8c7d5388c97657ae --- /dev/null +++ b/src/model/encoder/backbone/croco/curope/kernels.cu @@ -0,0 +1,108 @@ +/* + Copyright (C) 2022-present Naver Corporation. All rights reserved. + Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +*/ + +#include +#include +#include +#include + +#define CHECK_CUDA(tensor) {\ + TORCH_CHECK((tensor).is_cuda(), #tensor " is not in cuda memory"); \ + TORCH_CHECK((tensor).is_contiguous(), #tensor " is not contiguous"); } +void CHECK_KERNEL() {auto error = cudaGetLastError(); TORCH_CHECK( error == cudaSuccess, cudaGetErrorString(error));} + + +template < typename scalar_t > +__global__ void rope_2d_cuda_kernel( + //scalar_t* __restrict__ tokens, + torch::PackedTensorAccessor32 tokens, + const int64_t* __restrict__ pos, + const float base, + const float fwd ) + // const int N, const int H, const int D ) +{ + // tokens shape = (B, N, H, D) + const int N = tokens.size(1); + const int H = tokens.size(2); + const int D = tokens.size(3); + + // each block update a single token, for all heads + // each thread takes care of a single output + extern __shared__ float shared[]; + float* shared_inv_freq = shared + D; + + const int b = blockIdx.x / N; + const int n = blockIdx.x % N; + + const int Q = D / 4; + // one token = [0..Q : Q..2Q : 2Q..3Q : 3Q..D] + // u_Y v_Y u_X v_X + + // shared memory: first, compute inv_freq + if (threadIdx.x < Q) + shared_inv_freq[threadIdx.x] = fwd / powf(base, threadIdx.x/float(Q)); + __syncthreads(); + + // start of X or Y part + const int X = threadIdx.x < D/2 ? 0 : 1; + const int m = (X*D/2) + (threadIdx.x % Q); // index of u_Y or u_X + + // grab the cos,sin appropriate for me + const float freq = pos[blockIdx.x*2+X] * shared_inv_freq[threadIdx.x % Q]; + const float cos = cosf(freq); + const float sin = sinf(freq); + /* + float* shared_cos_sin = shared + D + D/4; + if ((threadIdx.x % (D/2)) < Q) + shared_cos_sin[m+0] = cosf(freq); + else + shared_cos_sin[m+Q] = sinf(freq); + __syncthreads(); + const float cos = shared_cos_sin[m+0]; + const float sin = shared_cos_sin[m+Q]; + */ + + for (int h = 0; h < H; h++) + { + // then, load all the token for this head in shared memory + shared[threadIdx.x] = tokens[b][n][h][threadIdx.x]; + __syncthreads(); + + const float u = shared[m]; + const float v = shared[m+Q]; + + // write output + if ((threadIdx.x % (D/2)) < Q) + tokens[b][n][h][threadIdx.x] = u*cos - v*sin; + else + tokens[b][n][h][threadIdx.x] = v*cos + u*sin; + } +} + +void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd ) +{ + const int B = tokens.size(0); // batch size + const int N = tokens.size(1); // sequence length + const int H = tokens.size(2); // number of heads + const int D = tokens.size(3); // dimension per head + + TORCH_CHECK(tokens.stride(3) == 1 && tokens.stride(2) == D, "tokens are not contiguous"); + TORCH_CHECK(pos.is_contiguous(), "positions are not contiguous"); + TORCH_CHECK(pos.size(0) == B && pos.size(1) == N && pos.size(2) == 2, "bad pos.shape"); + TORCH_CHECK(D % 4 == 0, "token dim must be multiple of 4"); + + // one block for each layer, one thread per local-max + const int THREADS_PER_BLOCK = D; + const int N_BLOCKS = B * N; // each block takes care of H*D values + const int SHARED_MEM = sizeof(float) * (D + D/4); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(tokens.type(), "rope_2d_cuda", ([&] { + rope_2d_cuda_kernel <<>> ( + //tokens.data_ptr(), + tokens.packed_accessor32(), + pos.data_ptr(), + base, fwd); //, N, H, D ); + })); +} diff --git a/src/model/encoder/backbone/croco/curope/setup.py b/src/model/encoder/backbone/croco/curope/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f24f89fbd56bc8543e85e8653384e3b4aad4a448 --- /dev/null +++ b/src/model/encoder/backbone/croco/curope/setup.py @@ -0,0 +1,34 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + +from setuptools import setup +from torch import cuda +from torch.utils.cpp_extension import BuildExtension, CUDAExtension + +# compile for all possible CUDA architectures +all_cuda_archs = cuda.get_gencode_flags().replace('compute=','arch=').split() +# alternatively, you can list cuda archs that you want, eg: +# all_cuda_archs = [ + # '-gencode', 'arch=compute_70,code=sm_70', + # '-gencode', 'arch=compute_75,code=sm_75', + # '-gencode', 'arch=compute_80,code=sm_80', + # '-gencode', 'arch=compute_86,code=sm_86' +# ] + +setup( + name = 'curope', + ext_modules = [ + CUDAExtension( + name='curope', + sources=[ + "curope.cpp", + "kernels.cu", + ], + extra_compile_args = dict( + nvcc=['-O3','--ptxas-options=-v',"--use_fast_math"]+all_cuda_archs, + cxx=['-O3']) + ) + ], + cmdclass = { + 'build_ext': BuildExtension + }) diff --git a/src/model/encoder/backbone/croco/masking.py b/src/model/encoder/backbone/croco/masking.py new file mode 100644 index 0000000000000000000000000000000000000000..788afbd3d0993ffc62a5d436fda9f254771374d9 --- /dev/null +++ b/src/model/encoder/backbone/croco/masking.py @@ -0,0 +1,25 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + + +# -------------------------------------------------------- +# Masking utils +# -------------------------------------------------------- + +import torch +import torch.nn as nn + +class RandomMask(nn.Module): + """ + random masking + """ + + def __init__(self, num_patches, mask_ratio): + super().__init__() + self.num_patches = num_patches + self.num_mask = int(mask_ratio * self.num_patches) + + def __call__(self, x): + noise = torch.rand(x.size(0), self.num_patches, device=x.device) + argsort = torch.argsort(noise, dim=1) + return argsort < self.num_mask diff --git a/src/model/encoder/backbone/croco/misc.py b/src/model/encoder/backbone/croco/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..3543a1d3f0e38d23b51df5f235448eed7c8b8305 --- /dev/null +++ b/src/model/encoder/backbone/croco/misc.py @@ -0,0 +1,138 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# utilitary functions for DUSt3R +# -------------------------------------------------------- +import torch + + +def fill_default_args(kwargs, func): + import inspect # a bit hacky but it works reliably + signature = inspect.signature(func) + + for k, v in signature.parameters.items(): + if v.default is inspect.Parameter.empty: + continue + kwargs.setdefault(k, v.default) + + return kwargs + + +def freeze_all_params(modules): + for module in modules: + try: + for n, param in module.named_parameters(): + param.requires_grad = False + except AttributeError: + # module is directly a parameter + module.requires_grad = False + + +def is_symmetrized(gt1, gt2): + x = gt1['instance'] + y = gt2['instance'] + if len(x) == len(y) and len(x) == 1: + return False # special case of batchsize 1 + ok = True + for i in range(0, len(x), 2): + ok = ok and (x[i] == y[i+1]) and (x[i+1] == y[i]) + return ok + + +def flip(tensor): + """ flip so that tensor[0::2] <=> tensor[1::2] """ + return torch.stack((tensor[1::2], tensor[0::2]), dim=1).flatten(0, 1) + + +def interleave(tensor1, tensor2): + res1 = torch.stack((tensor1, tensor2), dim=1).flatten(0, 1) + res2 = torch.stack((tensor2, tensor1), dim=1).flatten(0, 1) + return res1, res2 + + +def _interleave_imgs(img1, img2): + res = {} + for key, value1 in img1.items(): + value2 = img2[key] + if isinstance(value1, torch.Tensor): + value = torch.stack((value1, value2), dim=1).flatten(0, 1) + else: + value = [x for pair in zip(value1, value2) for x in pair] + res[key] = value + return res + + +def make_batch_symmetric(view1, view2): + view1, view2 = (_interleave_imgs(view1, view2), _interleave_imgs(view2, view1)) + return view1, view2 + + +def transpose_to_landscape(head, activate=True): + """ Predict in the correct aspect-ratio, + then transpose the result in landscape + and stack everything back together. + """ + def wrapper_no(decout, true_shape, ray_embedding=None): + B = len(true_shape) + assert true_shape[0:1].allclose(true_shape), 'true_shape must be all identical' + H, W = true_shape[0].cpu().tolist() + res = head(decout, (H, W), ray_embedding=ray_embedding) + return res + + def wrapper_yes(decout, true_shape, ray_embedding=None): + B = len(true_shape) + # by definition, the batch is in landscape mode so W >= H + H, W = int(true_shape.min()), int(true_shape.max()) + + height, width = true_shape.T + is_landscape = (width >= height) + is_portrait = ~is_landscape + + # true_shape = true_shape.cpu() + if is_landscape.all(): + return head(decout, (H, W), ray_embedding=ray_embedding) + if is_portrait.all(): + return transposed(head(decout, (W, H), ray_embedding=ray_embedding)) + + # batch is a mix of both portraint & landscape + def selout(ar): return [d[ar] for d in decout] + l_result = head(selout(is_landscape), (H, W), ray_embedding=ray_embedding) + p_result = transposed(head(selout(is_portrait), (W, H), ray_embedding=ray_embedding)) + + # allocate full result + result = {} + for k in l_result | p_result: + x = l_result[k].new(B, *l_result[k].shape[1:]) + x[is_landscape] = l_result[k] + x[is_portrait] = p_result[k] + result[k] = x + + return result + + return wrapper_yes if activate else wrapper_no + + +def transposed(dic): + return {k: v.swapaxes(1, 2) for k, v in dic.items()} + + +def invalid_to_nans(arr, valid_mask, ndim=999): + if valid_mask is not None: + arr = arr.clone() + arr[~valid_mask] = float('nan') + if arr.ndim > ndim: + arr = arr.flatten(-2 - (arr.ndim - ndim), -2) + return arr + + +def invalid_to_zeros(arr, valid_mask, ndim=999): + if valid_mask is not None: + arr = arr.clone() + arr[~valid_mask] = 0 + nnz = valid_mask.view(len(valid_mask), -1).sum(1) + else: + nnz = arr.numel() // len(arr) if len(arr) else 0 # number of point per image + if arr.ndim > ndim: + arr = arr.flatten(-2 - (arr.ndim - ndim), -2) + return arr, nnz diff --git a/src/model/encoder/backbone/croco/patch_embed.py b/src/model/encoder/backbone/croco/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..24849ffc61776d6c29a371a5a40cac0dd06ea81c --- /dev/null +++ b/src/model/encoder/backbone/croco/patch_embed.py @@ -0,0 +1,70 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# PatchEmbed implementation for DUST3R, +# in particular ManyAR_PatchEmbed that Handle images with non-square aspect ratio +# -------------------------------------------------------- +import torch + +from .blocks import PatchEmbed + + +def get_patch_embed(patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans=3): + assert patch_embed_cls in ['PatchEmbedDust3R', 'ManyAR_PatchEmbed'] + patch_embed = eval(patch_embed_cls)(img_size, patch_size, in_chans, enc_embed_dim) + return patch_embed + + +class PatchEmbedDust3R(PatchEmbed): + def forward(self, x, **kw): + B, C, H, W = x.shape + assert H % self.patch_size[0] == 0, f"Input image height ({H}) is not a multiple of patch size ({self.patch_size[0]})." + assert W % self.patch_size[1] == 0, f"Input image width ({W}) is not a multiple of patch size ({self.patch_size[1]})." + x = self.proj(x) + pos = self.position_getter(B, x.size(2), x.size(3), x.device) + if self.flatten: + x = x.flatten(2).transpose(1, 2) # BCHW -> BNC + x = self.norm(x) + return x, pos + + +class ManyAR_PatchEmbed (PatchEmbed): + """ Handle images with non-square aspect ratio. + All images in the same batch have the same aspect ratio. + true_shape = [(height, width) ...] indicates the actual shape of each image. + """ + + def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): + self.embed_dim = embed_dim + super().__init__(img_size, patch_size, in_chans, embed_dim, norm_layer, flatten) + + def forward(self, img, true_shape): + B, C, H, W = img.shape + assert W >= H, f'img should be in landscape mode, but got {W=} {H=}' + assert H % self.patch_size[0] == 0, f"Input image height ({H}) is not a multiple of patch size ({self.patch_size[0]})." + assert W % self.patch_size[1] == 0, f"Input image width ({W}) is not a multiple of patch size ({self.patch_size[1]})." + assert true_shape.shape == (B, 2), f"true_shape has the wrong shape={true_shape.shape}" + + # size expressed in tokens + W //= self.patch_size[0] + H //= self.patch_size[1] + n_tokens = H * W + + height, width = true_shape.T + is_landscape = (width >= height) + is_portrait = ~is_landscape + + # allocate result + x = img.new_zeros((B, n_tokens, self.embed_dim)) + pos = img.new_zeros((B, n_tokens, 2), dtype=torch.int64) + + # linear projection, transposed if necessary + x[is_landscape] = self.proj(img[is_landscape]).permute(0, 2, 3, 1).flatten(1, 2).float() + x[is_portrait] = self.proj(img[is_portrait].swapaxes(-1, -2)).permute(0, 2, 3, 1).flatten(1, 2).float() + + pos[is_landscape] = self.position_getter(1, H, W, pos.device) + pos[is_portrait] = self.position_getter(1, W, H, pos.device) + + x = self.norm(x) + return x, pos diff --git a/src/model/encoder/backbone/croco/pos_embed.py b/src/model/encoder/backbone/croco/pos_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6685435f0c5893acdcb5409a64d31134670c37 --- /dev/null +++ b/src/model/encoder/backbone/croco/pos_embed.py @@ -0,0 +1,159 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + + +# -------------------------------------------------------- +# Position embedding utils +# -------------------------------------------------------- + + + +import numpy as np + +import torch + +# -------------------------------------------------------- +# 2D sine-cosine position embedding +# References: +# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py +# Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py +# MoCo v3: https://github.com/facebookresearch/moco-v3 +# -------------------------------------------------------- +def get_2d_sincos_pos_embed(embed_dim, grid_size, n_cls_token=0): + """ + grid_size: int of the grid height and width + return: + pos_embed: [grid_size*grid_size, embed_dim] or [n_cls_token+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) + """ + grid_h = np.arange(grid_size, dtype=np.float32) + grid_w = np.arange(grid_size, dtype=np.float32) + grid = np.meshgrid(grid_w, grid_h) # here w goes first + grid = np.stack(grid, axis=0) + + grid = grid.reshape([2, 1, grid_size, grid_size]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if n_cls_token>0: + pos_embed = np.concatenate([np.zeros([n_cls_token, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +# -------------------------------------------------------- +# Interpolate position embeddings for high-resolution +# References: +# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py +# DeiT: https://github.com/facebookresearch/deit +# -------------------------------------------------------- +def interpolate_pos_embed(model, checkpoint_model): + if 'pos_embed' in checkpoint_model: + pos_embed_checkpoint = checkpoint_model['pos_embed'] + embedding_size = pos_embed_checkpoint.shape[-1] + num_patches = model.patch_embed.num_patches + num_extra_tokens = model.pos_embed.shape[-2] - num_patches + # height (== width) for the checkpoint position embedding + orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) + # height (== width) for the new position embedding + new_size = int(num_patches ** 0.5) + # class_token and dist_token are kept unchanged + if orig_size != new_size: + print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) + extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] + # only the position tokens are interpolated + pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] + pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) + pos_tokens = torch.nn.functional.interpolate( + pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) + pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) + new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) + checkpoint_model['pos_embed'] = new_pos_embed + + +#---------------------------------------------------------- +# RoPE2D: RoPE implementation in 2D +#---------------------------------------------------------- + +try: + from .curope import cuRoPE2D + RoPE2D = cuRoPE2D +except ImportError: + print('Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead') + + class RoPE2D(torch.nn.Module): + + def __init__(self, freq=100.0, F0=1.0): + super().__init__() + self.base = freq + self.F0 = F0 + self.cache = {} + + def get_cos_sin(self, D, seq_len, device, dtype): + if (D,seq_len,device,dtype) not in self.cache: + inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D)) + t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype) + freqs = torch.cat((freqs, freqs), dim=-1) + cos = freqs.cos() # (Seq, Dim) + sin = freqs.sin() + self.cache[D,seq_len,device,dtype] = (cos,sin) + return self.cache[D,seq_len,device,dtype] + + @staticmethod + def rotate_half(x): + x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + def apply_rope1d(self, tokens, pos1d, cos, sin): + assert pos1d.ndim==2 + cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :] + sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :] + return (tokens * cos) + (self.rotate_half(tokens) * sin) + + def forward(self, tokens, positions): + """ + input: + * tokens: batch_size x nheads x ntokens x dim + * positions: batch_size x ntokens x 2 (y and x position of each token) + output: + * tokens after appplying RoPE2D (batch_size x nheads x ntokens x dim) + """ + assert tokens.size(3)%2==0, "number of dimensions should be a multiple of two" + D = tokens.size(3) // 2 + assert positions.ndim==3 and positions.shape[-1] == 2 # Batch, Seq, 2 + cos, sin = self.get_cos_sin(D, int(positions.max())+1, tokens.device, tokens.dtype) + # split features into two along the feature dimension, and apply rope1d on each half + y, x = tokens.chunk(2, dim=-1) + y = self.apply_rope1d(y, positions[:,:,0], cos, sin) + x = self.apply_rope1d(x, positions[:,:,1], cos, sin) + tokens = torch.cat((y, x), dim=-1) + return tokens \ No newline at end of file diff --git a/src/model/encoder/common/gaussian_adapter.py b/src/model/encoder/common/gaussian_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a807659295bc2b21ac1efede03e2dab2575ff6 --- /dev/null +++ b/src/model/encoder/common/gaussian_adapter.py @@ -0,0 +1,180 @@ +from dataclasses import dataclass +from typing import Optional + +import torch +import torch.nn.functional as F +from einops import einsum, rearrange +from jaxtyping import Float +from torch import Tensor, nn + +from src.geometry.projection import get_world_rays +from src.misc.sh_rotation import rotate_sh +from .gaussians import build_covariance + +from ...types import Gaussians + +@dataclass +class GaussianAdapterCfg: + gaussian_scale_min: float + gaussian_scale_max: float + sh_degree: int + + +class GaussianAdapter(nn.Module): + cfg: GaussianAdapterCfg + + def __init__(self, cfg: GaussianAdapterCfg): + super().__init__() + self.cfg = cfg + + # Create a mask for the spherical harmonics coefficients. This ensures that at + # initialization, the coefficients are biased towards having a large DC + # component and small view-dependent components. + self.register_buffer( + "sh_mask", + torch.ones((self.d_sh,), dtype=torch.float32), + persistent=False, + ) + for degree in range(1, self.cfg.sh_degree + 1): + self.sh_mask[degree**2 : (degree + 1) ** 2] = 0.1 * 0.25**degree + + def forward( + self, + extrinsics: Float[Tensor, "*#batch 4 4"], + intrinsics: Float[Tensor, "*#batch 3 3"], + coordinates: Float[Tensor, "*#batch 2"], + depths: Float[Tensor, "*#batch"], + opacities: Float[Tensor, "*#batch"], + raw_gaussians: Float[Tensor, "*#batch _"], + image_shape: tuple[int, int], + eps: float = 1e-8, + ) -> Gaussians: + device = extrinsics.device + scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1) + + # Map scale features to valid scale range. + scale_min = self.cfg.gaussian_scale_min + scale_max = self.cfg.gaussian_scale_max + scales = scale_min + (scale_max - scale_min) * scales.sigmoid() + h, w = image_shape + pixel_size = 1 / torch.tensor((w, h), dtype=torch.float32, device=device) + multiplier = self.get_scale_multiplier(intrinsics, pixel_size) + scales = scales * depths[..., None] * multiplier[..., None] + + # Normalize the quaternion features to yield a valid quaternion. + rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps) + + sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3) + sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask + + # Create world-space covariance matrices. + covariances = build_covariance(scales, rotations) + c2w_rotations = extrinsics[..., :3, :3] + covariances = c2w_rotations @ covariances @ c2w_rotations.transpose(-1, -2) + + # Compute Gaussian means. + origins, directions = get_world_rays(coordinates, extrinsics, intrinsics) + means = origins + directions * depths[..., None] + + return Gaussians( + means=means, + covariances=covariances, + # harmonics=rotate_sh(sh, c2w_rotations[..., None, :, :]), + harmonics=sh, + opacities=opacities, + # Note: These aren't yet rotated into world space, but they're only used for + # exporting Gaussians to ply files. This needs to be fixed... + scales=scales, + rotations=rotations.broadcast_to((*scales.shape[:-1], 4)), + ) + + def get_scale_multiplier( + self, + intrinsics: Float[Tensor, "*#batch 3 3"], + pixel_size: Float[Tensor, "*#batch 2"], + multiplier: float = 0.1, + ) -> Float[Tensor, " *batch"]: + xy_multipliers = multiplier * einsum( + intrinsics[..., :2, :2].inverse(), + pixel_size, + "... i j, j -> ... i", + ) + return xy_multipliers.sum(dim=-1) + + @property + def d_sh(self) -> int: + return (self.cfg.sh_degree + 1) ** 2 + + @property + def d_in(self) -> int: + return 7 + 3 * self.d_sh + + +class UnifiedGaussianAdapter(GaussianAdapter): + def forward( + self, + means: Float[Tensor, "*#batch 3"], + # levels: Float[Tensor, "*#batch"], + depths: Float[Tensor, "*#batch"], + opacities: Float[Tensor, "*#batch"], + raw_gaussians: Float[Tensor, "*#batch _"], + eps: float = 1e-8, + intrinsics: Optional[Float[Tensor, "*#batch 3 3"]] = None, + coordinates: Optional[Float[Tensor, "*#batch 2"]] = None, + ) -> Gaussians: + scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1) + + scales = 0.001 * F.softplus(scales) + scales = scales.clamp_max(0.3) + + # Normalize the quaternion features to yield a valid quaternion. + rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps) + + sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3) + sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask + # print(scales.max()) + covariances = build_covariance(scales, rotations) + + return Gaussians( + means=means.float(), + # levels=levels.int(), + covariances=covariances.float(), + harmonics=sh.float(), + opacities=opacities.float(), + scales=scales.float(), + rotations=rotations.float(), + ) + +class Unet3dGaussianAdapter(GaussianAdapter): + def forward( + self, + means: Float[Tensor, "*#batch 3"], + depths: Float[Tensor, "*#batch"], + opacities: Float[Tensor, "*#batch"], + raw_gaussians: Float[Tensor, "*#batch _"], + eps: float = 1e-8, + intrinsics: Optional[Float[Tensor, "*#batch 3 3"]] = None, + coordinates: Optional[Float[Tensor, "*#batch 2"]] = None, + ) -> Gaussians: + scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1) + + scales = 0.001 * F.softplus(scales) + scales = scales.clamp_max(0.3) + + # Normalize the quaternion features to yield a valid quaternion. + rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps) + + sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3) + sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask + + covariances = build_covariance(scales, rotations) + + return Gaussians( + means=means, + covariances=covariances, + harmonics=sh, + opacities=opacities, + scales=scales, + rotations=rotations, + ) + diff --git a/src/model/encoder/common/gaussians.py b/src/model/encoder/common/gaussians.py new file mode 100644 index 0000000000000000000000000000000000000000..22eae1a74d0516941e22f4453a91a2f7e96bdc62 --- /dev/null +++ b/src/model/encoder/common/gaussians.py @@ -0,0 +1,44 @@ +import torch +from einops import rearrange +from jaxtyping import Float +from torch import Tensor + + +# https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py +def quaternion_to_matrix( + quaternions: Float[Tensor, "*batch 4"], + eps: float = 1e-8, +) -> Float[Tensor, "*batch 3 3"]: + # Order changed to match scipy format! + i, j, k, r = torch.unbind(quaternions, dim=-1) + two_s = 2 / ((quaternions * quaternions).sum(dim=-1) + eps) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return rearrange(o, "... (i j) -> ... i j", i=3, j=3) + + +def build_covariance( + scale: Float[Tensor, "*#batch 3"], + rotation_xyzw: Float[Tensor, "*#batch 4"], +) -> Float[Tensor, "*batch 3 3"]: + scale = scale.diag_embed() + rotation = quaternion_to_matrix(rotation_xyzw) + return ( + rotation + @ scale + @ rearrange(scale, "... i j -> ... j i") + @ rearrange(rotation, "... i j -> ... j i") + ) diff --git a/src/model/encoder/encoder.py b/src/model/encoder/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..b203befbd020a1fbfb4a335bde451063fb12f493 --- /dev/null +++ b/src/model/encoder/encoder.py @@ -0,0 +1,38 @@ +from abc import ABC, abstractmethod +from typing import Generic, TypeVar + +from torch import nn +from dataclasses import dataclass +from src.dataset.types import BatchedViews, DataShim +from ..types import Gaussians +from jaxtyping import Float +from torch import Tensor, nn + +T = TypeVar("T") + +@dataclass +class EncoderOutput: + gaussians: Gaussians + pred_pose_enc_list: list[Float[Tensor, "batch view 6"]] | None + pred_context_pose: dict | None + depth_dict: dict | None + infos: dict | None + distill_infos: dict | None + +class Encoder(nn.Module, ABC, Generic[T]): + cfg: T + + def __init__(self, cfg: T) -> None: + super().__init__() + self.cfg = cfg + + @abstractmethod + def forward( + self, + context: BatchedViews, + ) -> Gaussians: + pass + + def get_data_shim(self) -> DataShim: + """The default shim doesn't modify the batch.""" + return lambda x: x diff --git a/src/model/encoder/heads/__init__.py b/src/model/encoder/heads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27edffe188e17fdc533241f53bb684c1d9925493 --- /dev/null +++ b/src/model/encoder/heads/__init__.py @@ -0,0 +1,27 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# head factory +# -------------------------------------------------------- +from .dpt_gs_head import create_gs_dpt_head +from .linear_head import LinearPts3d +from .linear_gs_head import create_gs_linear_head +from .dpt_head import create_dpt_head + + +def head_factory(head_type, output_mode, net, has_conf=False, out_nchan=3): + """" build a prediction head for the decoder + """ + if head_type == 'linear' and output_mode == 'pts3d': + return LinearPts3d(net, has_conf) + elif head_type == 'dpt' and output_mode == 'pts3d': + return create_dpt_head(net, has_conf=has_conf) + elif head_type == 'dpt' and output_mode == 'gs_params': + return create_dpt_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None) + elif head_type == 'dpt_gs' and output_mode == 'gs_params': + return create_gs_dpt_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None) + elif head_type == 'linear' and output_mode == 'ga_params': + return create_gs_linear_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None) + else: + raise NotImplementedError(f"unexpected {head_type=} and {output_mode=}") diff --git a/src/model/encoder/heads/dpt_block.py b/src/model/encoder/heads/dpt_block.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0cfd1fad7c7a81b68241b0ddde33278914b4db --- /dev/null +++ b/src/model/encoder/heads/dpt_block.py @@ -0,0 +1,459 @@ +# Copyright (C) 2022-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). + +# -------------------------------------------------------- +# DPT head for ViTs +# -------------------------------------------------------- +# References: +# https://github.com/isl-org/DPT +# https://github.com/EPFL-VILAB/MultiMAE/blob/main/multimae/output_adapters.py + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange, repeat +from typing import Union, Tuple, Iterable, List, Optional, Dict + +def pair(t): + return t if isinstance(t, tuple) else (t, t) + +def make_scratch(in_shape, out_shape, groups=1, expand=False): + scratch = nn.Module() + + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + out_shape4 = out_shape + if expand == True: + out_shape1 = out_shape + out_shape2 = out_shape * 2 + out_shape3 = out_shape * 4 + out_shape4 = out_shape * 8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], + out_shape1, + kernel_size=3, + stride=1, + padding=1, + bias=False, + groups=groups, + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], + out_shape2, + kernel_size=3, + stride=1, + padding=1, + bias=False, + groups=groups, + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], + out_shape3, + kernel_size=3, + stride=1, + padding=1, + bias=False, + groups=groups, + ) + scratch.layer4_rn = nn.Conv2d( + in_shape[3], + out_shape4, + kernel_size=3, + stride=1, + padding=1, + bias=False, + groups=groups, + ) + + scratch.layer_rn = nn.ModuleList([ + scratch.layer1_rn, + scratch.layer2_rn, + scratch.layer3_rn, + scratch.layer4_rn, + ]) + + return scratch + +class ResidualConvUnit_custom(nn.Module): + """Residual convolution module.""" + + def __init__(self, features, activation, bn): + """Init. + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + + self.groups = 1 + + self.conv1 = nn.Conv2d( + features, + features, + kernel_size=3, + stride=1, + padding=1, + bias=not self.bn, + groups=self.groups, + ) + + self.conv2 = nn.Conv2d( + features, + features, + kernel_size=3, + stride=1, + padding=1, + bias=not self.bn, + groups=self.groups, + ) + + if self.bn == True: + self.bn1 = nn.BatchNorm2d(features) + self.bn2 = nn.BatchNorm2d(features) + + self.activation = activation + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + Args: + x (tensor): input + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.bn == True: + out = self.bn1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.bn == True: + out = self.bn2(out) + + if self.groups > 1: + out = self.conv_merge(out) + + return self.skip_add.add(out, x) + +class FeatureFusionBlock_custom(nn.Module): + """Feature fusion block.""" + + def __init__( + self, + features, + activation, + deconv=False, + bn=False, + expand=False, + align_corners=True, + width_ratio=1, + ): + """Init. + Args: + features (int): number of features + """ + super(FeatureFusionBlock_custom, self).__init__() + self.width_ratio = width_ratio + + self.deconv = deconv + self.align_corners = align_corners + + self.groups = 1 + + self.expand = expand + out_features = features + if self.expand == True: + out_features = features // 2 + + self.out_conv = nn.Conv2d( + features, + out_features, + kernel_size=1, + stride=1, + padding=0, + bias=True, + groups=1, + ) + + self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn) + self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn) + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, *xs): + """Forward pass. + Returns: + tensor: output + """ + output = xs[0] + + if len(xs) == 2: + res = self.resConfUnit1(xs[1]) + if self.width_ratio != 1: + res = F.interpolate(res, size=(output.shape[2], output.shape[3]), mode='bilinear') + + output = self.skip_add.add(output, res) + # output += res + + output = self.resConfUnit2(output) + + if self.width_ratio != 1: + # and output.shape[3] < self.width_ratio * output.shape[2] + #size=(image.shape[]) + if (output.shape[3] / output.shape[2]) < (2 / 3) * self.width_ratio: + shape = 3 * output.shape[3] + else: + shape = int(self.width_ratio * 2 * output.shape[2]) + output = F.interpolate(output, size=(2* output.shape[2], shape), mode='bilinear') + else: + output = nn.functional.interpolate(output, scale_factor=2, + mode="bilinear", align_corners=self.align_corners) + output = self.out_conv(output) + return output + +def make_fusion_block(features, use_bn, width_ratio=1, expand=False): + return FeatureFusionBlock_custom( + features, + nn.ReLU(False), + deconv=False, + bn=use_bn, + expand=expand, + align_corners=True, + width_ratio=width_ratio, + ) + +class Interpolate(nn.Module): + """Interpolation module.""" + + def __init__(self, scale_factor, mode, align_corners=False): + """Init. + Args: + scale_factor (float): scaling + mode (str): interpolation mode + """ + super(Interpolate, self).__init__() + + self.interp = nn.functional.interpolate + self.scale_factor = scale_factor + self.mode = mode + self.align_corners = align_corners + + def forward(self, x): + """Forward pass. + Args: + x (tensor): input + Returns: + tensor: interpolated data + """ + + x = self.interp( + x, + scale_factor=self.scale_factor, + mode=self.mode, + align_corners=self.align_corners, + ) + + return x + +class DPTOutputAdapter(nn.Module): + """DPT output adapter. + + :param num_cahnnels: Number of output channels + :param stride_level: tride level compared to the full-sized image. + E.g. 4 for 1/4th the size of the image. + :param patch_size_full: Int or tuple of the patch size over the full image size. + Patch size for smaller inputs will be computed accordingly. + :param hooks: Index of intermediate layers + :param layer_dims: Dimension of intermediate layers + :param feature_dim: Feature dimension + :param last_dim: out_channels/in_channels for the last two Conv2d when head_type == regression + :param use_bn: If set to True, activates batch norm + :param dim_tokens_enc: Dimension of tokens coming from encoder + """ + + def __init__(self, + num_channels: int = 1, + stride_level: int = 1, + patch_size: Union[int, Tuple[int, int]] = 16, + main_tasks: Iterable[str] = ('rgb',), + hooks: List[int] = [2, 5, 8, 11], + layer_dims: List[int] = [96, 192, 384, 768], + feature_dim: int = 256, + last_dim: int = 32, + use_bn: bool = False, + dim_tokens_enc: Optional[int] = None, + head_type: str = 'regression', + output_width_ratio=1, + **kwargs): + super().__init__() + self.num_channels = num_channels + self.stride_level = stride_level + self.patch_size = pair(patch_size) + self.main_tasks = main_tasks + self.hooks = hooks + self.layer_dims = layer_dims + self.feature_dim = feature_dim + self.dim_tokens_enc = dim_tokens_enc * len(self.main_tasks) if dim_tokens_enc is not None else None + self.head_type = head_type + + # Actual patch height and width, taking into account stride of input + self.P_H = max(1, self.patch_size[0] // stride_level) + self.P_W = max(1, self.patch_size[1] // stride_level) + + self.scratch = make_scratch(layer_dims, feature_dim, groups=1, expand=False) + + self.scratch.refinenet1 = make_fusion_block(feature_dim, use_bn, output_width_ratio) + self.scratch.refinenet2 = make_fusion_block(feature_dim, use_bn, output_width_ratio) + self.scratch.refinenet3 = make_fusion_block(feature_dim, use_bn, output_width_ratio) + self.scratch.refinenet4 = make_fusion_block(feature_dim, use_bn, output_width_ratio) + + if self.head_type == 'regression': + # The "DPTDepthModel" head + self.head = nn.Sequential( + nn.Conv2d(feature_dim, feature_dim // 2, kernel_size=3, stride=1, padding=1), + Interpolate(scale_factor=2, mode="bilinear", align_corners=True), + nn.Conv2d(feature_dim // 2, last_dim, kernel_size=3, stride=1, padding=1), + nn.ReLU(True), + nn.Conv2d(last_dim, self.num_channels, kernel_size=1, stride=1, padding=0) + ) + elif self.head_type == 'semseg': + # The "DPTSegmentationModel" head + self.head = nn.Sequential( + nn.Conv2d(feature_dim, feature_dim, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(feature_dim) if use_bn else nn.Identity(), + nn.ReLU(True), + nn.Dropout(0.1, False), + nn.Conv2d(feature_dim, self.num_channels, kernel_size=1), + Interpolate(scale_factor=2, mode="bilinear", align_corners=True), + ) + elif self.head_type == 'gs_params': + # The "DPTSegmentationModel" head + self.head = nn.Sequential( + nn.Conv2d(feature_dim, feature_dim, kernel_size=3, padding=1, bias=False), + nn.BatchNorm2d(feature_dim) if use_bn else nn.Identity(), + nn.ReLU(True), + nn.Dropout(0.1, False), + nn.Conv2d(feature_dim, self.num_channels, kernel_size=1), + ) + else: + raise ValueError('DPT head_type must be "regression" or "semseg".') + + if self.dim_tokens_enc is not None: + self.init(dim_tokens_enc=dim_tokens_enc) + + def init(self, dim_tokens_enc=768): + """ + Initialize parts of decoder that are dependent on dimension of encoder tokens. + Should be called when setting up MultiMAE. + + :param dim_tokens_enc: Dimension of tokens coming from encoder + """ + #print(dim_tokens_enc) + + # Set up activation postprocessing layers + if isinstance(dim_tokens_enc, int): + dim_tokens_enc = 4 * [dim_tokens_enc] + + self.dim_tokens_enc = [dt * len(self.main_tasks) for dt in dim_tokens_enc] + + self.act_1_postprocess = nn.Sequential( + nn.Conv2d( + in_channels=self.dim_tokens_enc[0], + out_channels=self.layer_dims[0], + kernel_size=1, stride=1, padding=0, + ), + nn.ConvTranspose2d( + in_channels=self.layer_dims[0], + out_channels=self.layer_dims[0], + kernel_size=4, stride=4, padding=0, + bias=True, dilation=1, groups=1, + ) + ) + + self.act_2_postprocess = nn.Sequential( + nn.Conv2d( + in_channels=self.dim_tokens_enc[1], + out_channels=self.layer_dims[1], + kernel_size=1, stride=1, padding=0, + ), + nn.ConvTranspose2d( + in_channels=self.layer_dims[1], + out_channels=self.layer_dims[1], + kernel_size=2, stride=2, padding=0, + bias=True, dilation=1, groups=1, + ) + ) + + self.act_3_postprocess = nn.Sequential( + nn.Conv2d( + in_channels=self.dim_tokens_enc[2], + out_channels=self.layer_dims[2], + kernel_size=1, stride=1, padding=0, + ) + ) + + self.act_4_postprocess = nn.Sequential( + nn.Conv2d( + in_channels=self.dim_tokens_enc[3], + out_channels=self.layer_dims[3], + kernel_size=1, stride=1, padding=0, + ), + nn.Conv2d( + in_channels=self.layer_dims[3], + out_channels=self.layer_dims[3], + kernel_size=3, stride=2, padding=1, + ) + ) + + self.act_postprocess = nn.ModuleList([ + self.act_1_postprocess, + self.act_2_postprocess, + self.act_3_postprocess, + self.act_4_postprocess + ]) + + def adapt_tokens(self, encoder_tokens): + # Adapt tokens + x = [] + x.append(encoder_tokens[:, :]) + x = torch.cat(x, dim=-1) + return x + + def forward(self, encoder_tokens: List[torch.Tensor], image_size): + #input_info: Dict): + assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' + H, W = image_size + + # Number of patches in height and width + N_H = H // (self.stride_level * self.P_H) + N_W = W // (self.stride_level * self.P_W) + + # Hook decoder onto 4 layers from specified ViT layers + layers = [encoder_tokens[hook] for hook in self.hooks] + + # Extract only task-relevant tokens and ignore global tokens. + layers = [self.adapt_tokens(l) for l in layers] + + # Reshape tokens to spatial representation + layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] + + layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] + # Project layers to chosen feature dim + layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] + + # Fuse layers using refinement stages + path_4 = self.scratch.refinenet4(layers[3]) + path_3 = self.scratch.refinenet3(path_4, layers[2]) + path_2 = self.scratch.refinenet2(path_3, layers[1]) + path_1 = self.scratch.refinenet1(path_2, layers[0]) + + # Output head + out = self.head(path_1) + + return out diff --git a/src/model/encoder/heads/dpt_gs_head.py b/src/model/encoder/heads/dpt_gs_head.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa8a78f535b3ffbbecaa280ea5525d77221c359 --- /dev/null +++ b/src/model/encoder/heads/dpt_gs_head.py @@ -0,0 +1,284 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# dpt head implementation for DUST3R +# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ; +# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True +# the forward function also takes as input a dictionnary img_info with key "height" and "width" +# for PixelwiseTask, the output will be of dimension B x num_channels x H x W +# -------------------------------------------------------- +from einops import rearrange +from typing import List +import torch +import torch.nn as nn +import torch.nn.functional as F +# import dust3r.utils.path_to_croco +from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block +from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights +from .postprocess import postprocess + +# class DPTOutputAdapter_fix(DPTOutputAdapter): +# """ +# Adapt croco's DPTOutputAdapter implementation for dust3r: +# remove duplicated weigths, and fix forward for dust3r +# """ +# +# def init(self, dim_tokens_enc=768): +# super().init(dim_tokens_enc) +# # these are duplicated weights +# del self.act_1_postprocess +# del self.act_2_postprocess +# del self.act_3_postprocess +# del self.act_4_postprocess +# +# self.scratch.refinenet1 = make_fusion_block(256 * 2, False, 1, expand=True) +# self.scratch.refinenet2 = make_fusion_block(256 * 2, False, 1, expand=True) +# self.scratch.refinenet3 = make_fusion_block(256 * 2, False, 1, expand=True) +# # self.scratch.refinenet4 = make_fusion_block(256 * 2, False, 1) +# +# self.depth_encoder = UnetExtractor(in_channel=3) +# self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True) +# self.out_conv = nn.Conv2d(256+3+4, 256, kernel_size=3, padding=1) +# self.out_relu = nn.ReLU(inplace=True) +# +# self.input_merger = nn.Sequential( +# # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1), +# nn.Conv2d(256+3+3, 256, kernel_size=3, padding=1), +# nn.ReLU(), +# ) +# +# def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None): +# assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' +# # H, W = input_info['image_size'] +# image_size = self.image_size if image_size is None else image_size +# H, W = image_size +# # Number of patches in height and width +# N_H = H // (self.stride_level * self.P_H) +# N_W = W // (self.stride_level * self.P_W) +# +# # Hook decoder onto 4 layers from specified ViT layers +# layers = [encoder_tokens[hook] for hook in self.hooks] +# +# # Extract only task-relevant tokens and ignore global tokens. +# layers = [self.adapt_tokens(l) for l in layers] +# +# # Reshape tokens to spatial representation +# layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] +# +# layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] +# # Project layers to chosen feature dim +# layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] +# +# # get depth features +# depth_features = self.depth_encoder(depths) +# depth_feature1, depth_feature2, depth_feature3 = depth_features +# +# # Fuse layers using refinement stages +# path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]] +# path_3 = self.scratch.refinenet3(torch.cat([path_4, depth_feature3], dim=1), torch.cat([layers[2], depth_feature3], dim=1)) +# path_2 = self.scratch.refinenet2(torch.cat([path_3, depth_feature2], dim=1), torch.cat([layers[1], depth_feature2], dim=1)) +# path_1 = self.scratch.refinenet1(torch.cat([path_2, depth_feature1], dim=1), torch.cat([layers[0], depth_feature1], dim=1)) +# # path_3 = self.scratch.refinenet3(path_4, layers[2], depth_feature3) +# # path_2 = self.scratch.refinenet2(path_3, layers[1], depth_feature2) +# # path_1 = self.scratch.refinenet1(path_2, layers[0], depth_feature1) +# +# path_1 = self.feat_up(path_1) +# path_1 = torch.cat([path_1, imgs, depths], dim=1) +# if conf is not None: +# path_1 = torch.cat([path_1, conf], dim=1) +# path_1 = self.input_merger(path_1) +# +# # Output head +# out = self.head(path_1) +# +# return out + + +class DPTOutputAdapter_fix(DPTOutputAdapter): + """ + Adapt croco's DPTOutputAdapter implementation for dust3r: + remove duplicated weigths, and fix forward for dust3r + """ + + def init(self, dim_tokens_enc=768): + super().init(dim_tokens_enc) + # these are duplicated weights + del self.act_1_postprocess + del self.act_2_postprocess + del self.act_3_postprocess + del self.act_4_postprocess + + self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True) + self.input_merger = nn.Sequential( + # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1), + # nn.Conv2d(3+6, 256, 7, 1, 3), + nn.Conv2d(3, 256, 7, 1, 3), + nn.ReLU(), + ) + + def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None): + assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' + # H, W = input_info['image_size'] + image_size = self.image_size if image_size is None else image_size + H, W = image_size + # Number of patches in height and width + N_H = H // (self.stride_level * self.P_H) + N_W = W // (self.stride_level * self.P_W) + + # Hook decoder onto 4 layers from specified ViT layers + layers = [encoder_tokens[hook] for hook in self.hooks] + + # Extract only task-relevant tokens and ignore global tokens. + layers = [self.adapt_tokens(l) for l in layers] + + # Reshape tokens to spatial representation + layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] + + layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] + # Project layers to chosen feature dim + layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] + + # Fuse layers using refinement stages + path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]] + path_3 = self.scratch.refinenet3(path_4, layers[2]) + path_2 = self.scratch.refinenet2(path_3, layers[1]) + path_1 = self.scratch.refinenet1(path_2, layers[0]) + + direct_img_feat = self.input_merger(imgs) + # imgs = imgs.permute(0, 2, 3, 1).flatten(1, 2).contiguous() + # # Pachify + # patch_size = self.patch_size + # hh = H // patch_size[0] + # ww = W // patch_size[1] + # direct_img_feat = rearrange(imgs, "b (hh ph ww pw) d -> b (hh ww) (ph pw d)", hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1]) + + # actually, we just do interpolate here + # path_1 = self.feat_up(path_1) + path_1 = F.interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True) + path_1 = path_1 + direct_img_feat + + # path_1 = torch.cat([path_1, imgs], dim=1) + + # Output head + out = self.head(path_1) + + return out, [path_4, path_3, path_2] + + +class PixelwiseTaskWithDPT(nn.Module): + """ DPT module for dust3r, can return 3D points + confidence for all pixels""" + + def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None, + output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs): + super(PixelwiseTaskWithDPT, self).__init__() + self.return_all_layers = True # backbone needs to return all layers + self.postprocess = postprocess + self.depth_mode = depth_mode + self.conf_mode = conf_mode + + assert n_cls_token == 0, "Not implemented" + dpt_args = dict(output_width_ratio=output_width_ratio, + num_channels=num_channels, + **kwargs) + if hooks_idx is not None: + dpt_args.update(hooks=hooks_idx) + self.dpt = DPTOutputAdapter_fix(**dpt_args) + dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens} + self.dpt.init(**dpt_init_args) + + def forward(self, x, depths, imgs, img_info, conf=None): + out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf) + if self.postprocess: + out = self.postprocess(out, self.depth_mode, self.conf_mode) + return out, interm_feats + +class AttnBasedAppearanceHead(nn.Module): + """ + Attention head Appearence Reconstruction + """ + + def __init__(self, num_channels, patch_size, feature_dim, last_dim, hooks_idx, dim_tokens, postprocess, depth_mode, conf_mode, head_type='gs_params'): + super().__init__() + + self.num_channels = num_channels + self.patch_size = patch_size + + self.hooks = hooks_idx + + assert len(set(dim_tokens)) == 1 + + self.tokenizer = nn.Linear(3 * self.patch_size[0] ** 2, dim_tokens[0], bias=False) + + self.attn_processor = AppearanceTransformer(num_layers=4, attn_dim=dim_tokens[0] * 2, head_dim=feature_dim) + + self.token_decoder = nn.Sequential( + nn.LayerNorm(dim_tokens[0] * 2, bias=False), + nn.Linear( + dim_tokens[0] * 2, self.num_channels * (self.patch_size[0] ** 2), + bias=False, + ) + ) + self.token_decoder.apply(_init_weights) + + + def img_pts_tokenizer(self, imgs, pts3d): + B, V, _, H, W = imgs.shape + pts3d = pts3d.flatten(2, 3).contiguous() + imgs = imgs.permute(0, 1, 3, 4, 2).flatten(2, 3).contiguous() + mean = pts3d.mean(dim=-2, keepdim=True) # (B, V, 1, 3) + z_median = torch.median(torch.norm(pts3d, dim=-1, keepdim=True), dim=2, keepdim=True)[0] # (B, V, 1, 1) + pts3d_normed = (pts3d - mean) / (z_median + 1e-8) # (B, V, N, 3) + + input = imgs #torch.cat([pts3d_normed, imgs], dim=-1) # (B, V, H*W, 9) + # Pachify + patch_size = self.patch_size + hh = H // patch_size[0] + ww = W // patch_size[1] + input = rearrange(input, "b v (hh ph ww pw) d -> (b v) (hh ww) (ph pw d)", hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1]) + # Tokenize the input images + input_tokens = self.tokenizer(input) + return input_tokens + + def forward(self, x, depths, imgs, img_info, conf=None): + B, V, H, W = img_info + input_tokens = rearrange(self.img_pts_tokenizer(imgs, depths), "(b v) l d -> b (v l) d", b=B, v=V) + + # Hook decoder onto 4 layers from specified ViT layers + layer_tokens = [rearrange(x[hook].detach(), "(b v) l d -> b (v l) d", b=B, v=V) for hook in self.hooks] + + tokens = self.attn_processor(torch.cat([input_tokens, layer_tokens[-1]], dim=-1)) + + gaussian_params = self.token_decoder(tokens) + + patch_size = self.patch_size + hh = H // patch_size[0] + ww = W // patch_size[1] + gaussians = rearrange(gaussian_params, "b (v hh ww) (ph pw d) -> b (v hh ph ww pw) d", v=V, hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1]) + return gaussians.view(B, V, H*W, -1) + +def create_gs_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess): + """ + return PixelwiseTaskWithDPT for given net params + """ + assert net.dec_depth > 9 + l2 = net.dec_depth + feature_dim = net.feature_dim + last_dim = feature_dim//2 + ed = net.enc_embed_dim + dd = net.dec_embed_dim + try: + patch_size = net.patch_size + except: + patch_size = (16, 16) + + return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf, + patch_size=patch_size, + feature_dim=feature_dim, + last_dim=last_dim, + hooks_idx=[0, l2*2//4, l2*3//4, l2], + dim_tokens=[ed, dd, dd, dd], + postprocess=postprocess_func, + depth_mode=net.depth_mode, + conf_mode=net.conf_mode, + head_type='gs_params') \ No newline at end of file diff --git a/src/model/encoder/heads/dpt_head.py b/src/model/encoder/heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad16742bab1f31df3353cd92a8a3741f7585e00 --- /dev/null +++ b/src/model/encoder/heads/dpt_head.py @@ -0,0 +1,119 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# dpt head implementation for DUST3R +# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ; +# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True +# the forward function also takes as input a dictionnary img_info with key "height" and "width" +# for PixelwiseTask, the output will be of dimension B x num_channels x H x W +# -------------------------------------------------------- +from einops import rearrange +from typing import List +import torch +import torch.nn as nn +import torch.nn.functional as F +# import dust3r.utils.path_to_croco +from .dpt_block import DPTOutputAdapter +from .postprocess import postprocess + + +class DPTOutputAdapter_fix(DPTOutputAdapter): + """ + Adapt croco's DPTOutputAdapter implementation for dust3r: + remove duplicated weigths, and fix forward for dust3r + """ + + def init(self, dim_tokens_enc=768): + super().init(dim_tokens_enc) + # these are duplicated weights + del self.act_1_postprocess + del self.act_2_postprocess + del self.act_3_postprocess + del self.act_4_postprocess + + def forward(self, encoder_tokens: List[torch.Tensor], image_size=None, ray_embedding=None): + assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' + # H, W = input_info['image_size'] + image_size = self.image_size if image_size is None else image_size + H, W = image_size + # Number of patches in height and width + N_H = H // (self.stride_level * self.P_H) + N_W = W // (self.stride_level * self.P_W) + + # Hook decoder onto 4 layers from specified ViT layers + layers = [encoder_tokens[hook] for hook in self.hooks] + + # Extract only task-relevant tokens and ignore global tokens. + layers = [self.adapt_tokens(l) for l in layers] + + # Reshape tokens to spatial representation + layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] + + layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] + # Project layers to chosen feature dim + layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] + + # Fuse layers using refinement stages + path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]] + path_3 = self.scratch.refinenet3(path_4, layers[2]) + path_2 = self.scratch.refinenet2(path_3, layers[1]) + path_1 = self.scratch.refinenet1(path_2, layers[0]) + + # if ray_embedding is not None: + # ray_embedding = F.interpolate(ray_embedding, size=(path_1.shape[2], path_1.shape[3]), mode='bilinear') + # path_1 = torch.cat([path_1, ray_embedding], dim=1) + + # Output head + out = self.head(path_1) + + return out + + +class PixelwiseTaskWithDPT(nn.Module): + """ DPT module for dust3r, can return 3D points + confidence for all pixels""" + + def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None, + output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs): + super(PixelwiseTaskWithDPT, self).__init__() + self.return_all_layers = True # backbone needs to return all layers + self.postprocess = postprocess + self.depth_mode = depth_mode + self.conf_mode = conf_mode + + assert n_cls_token == 0, "Not implemented" + dpt_args = dict(output_width_ratio=output_width_ratio, + num_channels=num_channels, + **kwargs) + if hooks_idx is not None: + dpt_args.update(hooks=hooks_idx) + self.dpt = DPTOutputAdapter_fix(**dpt_args) + dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens} + self.dpt.init(**dpt_init_args) + + def forward(self, x, img_info, ray_embedding=None): + out = self.dpt(x, image_size=(img_info[0], img_info[1]), ray_embedding=ray_embedding) + if self.postprocess: + out = self.postprocess(out, self.depth_mode, self.conf_mode) + return out + + +def create_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess): + """ + return PixelwiseTaskWithDPT for given net params + """ + assert net.dec_depth > 9 + l2 = net.dec_depth + feature_dim = 256 + last_dim = feature_dim//2 + ed = net.enc_embed_dim + dd = net.dec_embed_dim + return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf, + feature_dim=feature_dim, + last_dim=last_dim, + hooks_idx=[0, l2*2//4, l2*3//4, l2], + dim_tokens=[ed, dd, dd, dd], + postprocess=postprocess_func, + depth_mode=net.depth_mode, + conf_mode=net.conf_mode, + head_type='regression') diff --git a/src/model/encoder/heads/head_modules.py b/src/model/encoder/heads/head_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca271d390693b2e78f68a70247cf5fe6c3da8f6 --- /dev/null +++ b/src/model/encoder/heads/head_modules.py @@ -0,0 +1,322 @@ +import torch +import torch.nn as nn +from einops import rearrange +from torch.nn import functional as F +import numbers + +class RMSNorm(nn.Module): + def __init__(self, dim, eps=1e-6): + super(RMSNorm, self).__init__() + self.eps = eps + self.scale = nn.Parameter(torch.ones(dim)) + + def forward(self, x): + rms = torch.sqrt(torch.mean(x**2, dim=-1, keepdim=True) + self.eps) + return self.scale * x / rms + + +class ResidualBlock(nn.Module): + def __init__(self, in_planes, planes, norm_fn='group', stride=1): + super(ResidualBlock, self).__init__() + + self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == 'group': + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not (stride == 1 and in_planes == planes): + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == 'batch': + self.norm1 = nn.BatchNorm2d(planes) + self.norm2 = nn.BatchNorm2d(planes) + if not (stride == 1 and in_planes == planes): + self.norm3 = nn.BatchNorm2d(planes) + + elif norm_fn == 'instance': + self.norm1 = nn.InstanceNorm2d(planes) + self.norm2 = nn.InstanceNorm2d(planes) + if not (stride == 1 and in_planes == planes): + self.norm3 = nn.InstanceNorm2d(planes) + + elif norm_fn == 'none': + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + if not (stride == 1 and in_planes == planes): + self.norm3 = nn.Sequential() + + if stride == 1 and in_planes == planes: + self.downsample = None + + else: + self.downsample = nn.Sequential( + nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3) + + def forward(self, x): + y = x + y = self.conv1(y) + y = self.norm1(y) + y = self.relu(y) + y = self.conv2(y) + y = self.norm2(y) + y = self.relu(y) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class UnetExtractor(nn.Module): + def __init__(self, in_channel=3, encoder_dim=[256, 256, 256], norm_fn='group'): + super().__init__() + self.in_ds = nn.Sequential( + nn.Conv2d(in_channel, 64, kernel_size=7, stride=2, padding=3), + nn.GroupNorm(num_groups=8, num_channels=64), + nn.ReLU(inplace=True) + ) + + self.res1 = nn.Sequential( + ResidualBlock(64, encoder_dim[0], stride=2, norm_fn=norm_fn), + ResidualBlock(encoder_dim[0], encoder_dim[0], norm_fn=norm_fn) + ) + self.res2 = nn.Sequential( + ResidualBlock(encoder_dim[0], encoder_dim[1], stride=2, norm_fn=norm_fn), + ResidualBlock(encoder_dim[1], encoder_dim[1], norm_fn=norm_fn) + ) + self.res3 = nn.Sequential( + ResidualBlock(encoder_dim[1], encoder_dim[2], stride=2, norm_fn=norm_fn), + ResidualBlock(encoder_dim[2], encoder_dim[2], norm_fn=norm_fn), + ) + + def forward(self, x): + x = self.in_ds(x) + x1 = self.res1(x) + x2 = self.res2(x1) + x3 = self.res3(x2) + + return x1, x2, x3 + + +class MultiBasicEncoder(nn.Module): + def __init__(self, output_dim=[128], encoder_dim=[64, 96, 128]): + super(MultiBasicEncoder, self).__init__() + + # output convolution for feature + self.conv2 = nn.Sequential( + ResidualBlock(encoder_dim[2], encoder_dim[2], stride=1), + nn.Conv2d(encoder_dim[2], encoder_dim[2] * 2, 3, padding=1)) + + # output convolution for context + output_list = [] + for dim in output_dim: + conv_out = nn.Sequential( + ResidualBlock(encoder_dim[2], encoder_dim[2], stride=1), + nn.Conv2d(encoder_dim[2], dim[2], 3, padding=1)) + output_list.append(conv_out) + + self.outputs08 = nn.ModuleList(output_list) + + def forward(self, x): + feat1, feat2 = self.conv2(x).split(dim=0, split_size=x.shape[0] // 2) + + outputs08 = [f(x) for f in self.outputs08] + return outputs08, feat1, feat2 + + + +# attention processor for appreaance head + +def _init_weights(m): + if isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + +class Mlp(nn.Module): + def __init__(self, in_features, mlp_ratio=4., mlp_bias=False, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = int(in_features * mlp_ratio) + self.fc1 = nn.Linear(in_features, hidden_features, bias=mlp_bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=mlp_bias) + self.drop = nn.Dropout(drop) + + def forward(self, x): + """ + x: (B, L, D) + Returns: same shape as input + """ + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + +class SelfAttention(nn.Module): + def __init__(self, dim, head_dim=64, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., use_flashatt_v2=True): + super().__init__() + assert dim % head_dim == 0, 'dim must be divisible by head_dim' + self.num_heads = dim // head_dim + self.scale = qk_scale or head_dim ** -0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop_p = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=False) + self.proj_drop = nn.Dropout(proj_drop) + + self.norm_q = RMSNorm(head_dim, eps=1e-5) + self.norm_k = RMSNorm(head_dim, eps=1e-5) + + self.use_flashatt_v2 = use_flashatt_v2 + + def forward(self, x): + """ + x: (B, L, D) + Returns: same shape as input + """ + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + if self.use_flashatt_v2: + qkv = qkv.permute(2, 0, 1, 3, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # (B, N, H, C) + q, k = self.norm_q(q).to(v.dtype), self.norm_k(k).to(v.dtype) + x = xops.memory_efficient_attention(q, k, v, op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp), p=self.attn_drop_p) + x = rearrange(x, 'b n h d -> b n (h d)') + + x = self.proj(x) + x = self.proj_drop(x) + return x + +class CrossAttention(nn.Module): + def __init__(self, dim, head_dim=64, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., use_flashatt_v2=True): + super().__init__() + assert dim % head_dim == 0, 'dim must be divisible by head_dim' + self.num_heads = dim // head_dim + self.scale = qk_scale or head_dim ** -0.5 + + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.k = nn.Linear(dim, dim, bias=qkv_bias) + self.v = nn.Linear(dim, dim, bias=qkv_bias) + + self.attn_drop_p = attn_drop + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=False) + self.proj_drop = nn.Dropout(proj_drop) + + self.norm_q = RMSNorm(head_dim, eps=1e-5) + self.norm_k = RMSNorm(head_dim, eps=1e-5) + + self.use_flashatt_v2 = use_flashatt_v2 + + def forward(self, x_q, x_kv): + """ + x_q: query input (B, L_q, D) + x_kv: key-value input (B, L_kv, D) + Returns: same shape as query input (B, L_q, D) + """ + B, N_q, C = x_q.shape + _, N_kv, _ = x_kv.shape + + q = self.q(x_q).reshape(B, N_q, self.num_heads, C // self.num_heads) + k = self.k(x_kv).reshape(B, N_kv, self.num_heads, C // self.num_heads) + v = self.v(x_kv).reshape(B, N_kv, self.num_heads, C // self.num_heads) + + if self.use_flashatt_v2: + q, k = self.norm_q(q).to(v.dtype), self.norm_k(k).to(v.dtype) + x = xops.memory_efficient_attention( + q, k, v, + op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp), + p=self.attn_drop_p + ) + x = rearrange(x, 'b n h d -> b n (h d)') + + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class TransformerBlockSelfAttn(nn.Module): + def __init__(self, dim, head_dim, mlp_ratio=4., mlp_bias=False, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flashatt_v2=True): + super().__init__() + self.norm1 = norm_layer(dim, bias=False) + self.attn = SelfAttention( + dim, head_dim=head_dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, use_flashatt_v2=use_flashatt_v2) + self.norm2 = norm_layer(dim, bias=False) + self.mlp = Mlp(in_features=dim, mlp_ratio=mlp_ratio, mlp_bias=mlp_bias, act_layer=act_layer, drop=drop) + + def forward(self, x): + """ + x: (B, L, D) + Returns: same shape as input + """ + y = self.attn(self.norm1(x)) + x = x + y + x = x + self.mlp(self.norm2(x)) + return x + +class TransformerBlockCrossAttn(nn.Module): + def __init__(self, dim, head_dim, mlp_ratio=4., mlp_bias=False, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flashatt_v2=True): + super().__init__() + self.norm1 = norm_layer(dim, bias=False) + self.attn = CrossAttention( + dim, head_dim=head_dim, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, use_flashatt_v2=use_flashatt_v2) + self.norm2 = norm_layer(dim, bias=False) + self.mlp = Mlp(in_features=dim, mlp_ratio=mlp_ratio, mlp_bias=mlp_bias, act_layer=act_layer, drop=drop) + + def forward(self, x_list): + """ + x_q: (B, L_q, D) + x_kv: (B, L_kv, D) + Returns: same shape as input + """ + x_q, x_kv = x_list + y = self.attn(self.norm1(x_q), self.norm1(x_kv)) + x = x_q + y + x = x + self.mlp(self.norm2(x)) + return x + +class AppearanceTransformer(nn.Module): + def __init__(self, num_layers, attn_dim, head_dim, ca_incides=[1, 3, 5, 7]): + super().__init__() + self.attn_dim = attn_dim + self.num_layers = num_layers + self.blocks = nn.ModuleList() + self.ca_incides = ca_incides + + for attn_index in range(num_layers): + self.blocks.append(TransformerBlockSelfAttn(self.attn_dim, head_dim)) + self.blocks[-1].apply(_init_weights) + + def forward(self, x, use_checkpoint=True): + """ + input_tokens: (B, L, D) + aggregated_tokens: List of (B, L, D) + Returns: B and D remain the same, L might change if there are merge layers + """ + for block in self.blocks: + if use_checkpoint: + x = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False) + else: + x = block(x) + + return x + + +if __name__ == '__main__': + data = torch.ones((1, 3, 1024, 1024)) + + model = UnetExtractor(in_channel=3, encoder_dim=[64, 96, 128]) + + x1, x2, x3 = model(data) + print(x1.shape, x2.shape, x3.shape) diff --git a/src/model/encoder/heads/linear_gs_head.py b/src/model/encoder/heads/linear_gs_head.py new file mode 100644 index 0000000000000000000000000000000000000000..08affc71c442a9036e266d36d9b4768ff6adfe2e --- /dev/null +++ b/src/model/encoder/heads/linear_gs_head.py @@ -0,0 +1,383 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# dpt head implementation for DUST3R +# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ; +# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True +# the forward function also takes as input a dictionnary img_info with key "height" and "width" +# for PixelwiseTask, the output will be of dimension B x num_channels x H x W +# -------------------------------------------------------- +from einops import rearrange +from typing import List, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +# import dust3r.utils.path_to_croco +from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block +from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights +from .postprocess import postprocess +import torchvision + +def custom_interpolate( + x: torch.Tensor, + size: Tuple[int, int] = None, + scale_factor: float = None, + mode: str = "bilinear", + align_corners: bool = True, +) -> torch.Tensor: + """ + Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. + """ + if size is None: + size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) + + INT_MAX = 1610612736 + + input_elements = size[0] * size[1] * x.shape[0] * x.shape[1] + + if input_elements > INT_MAX: + chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) + interpolated_chunks = [ + nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks + ] + x = torch.cat(interpolated_chunks, dim=0) + return x.contiguous() + else: + return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) + +# class DPTOutputAdapter_fix(DPTOutputAdapter): +# """ +# Adapt croco's DPTOutputAdapter implementation for dust3r: +# remove duplicated weigths, and fix forward for dust3r +# """ +# +# def init(self, dim_tokens_enc=768): +# super().init(dim_tokens_enc) +# # these are duplicated weights +# del self.act_1_postprocess +# del self.act_2_postprocess +# del self.act_3_postprocess +# del self.act_4_postprocess +# +# self.scratch.refinenet1 = make_fusion_block(256 * 2, False, 1, expand=True) +# self.scratch.refinenet2 = make_fusion_block(256 * 2, False, 1, expand=True) +# self.scratch.refinenet3 = make_fusion_block(256 * 2, False, 1, expand=True) +# # self.scratch.refinenet4 = make_fusion_block(256 * 2, False, 1) +# +# self.depth_encoder = UnetExtractor(in_channel=3) +# self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True) +# self.out_conv = nn.Conv2d(256+3+4, 256, kernel_size=3, padding=1) +# self.out_relu = nn.ReLU(inplace=True) +# +# self.input_merger = nn.Sequential( +# # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1), +# nn.Conv2d(256+3+3, 256, kernel_size=3, padding=1), +# nn.ReLU(), +# ) +# +# def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None): +# assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' +# # H, W = input_info['image_size'] +# image_size = self.image_size if image_size is None else image_size +# H, W = image_size +# # Number of patches in height and width +# N_H = H // (self.stride_level * self.P_H) +# N_W = W // (self.stride_level * self.P_W) +# +# # Hook decoder onto 4 layers from specified ViT layers +# layers = [encoder_tokens[hook] for hook in self.hooks] +# +# # Extract only task-relevant tokens and ignore global tokens. +# layers = [self.adapt_tokens(l) for l in layers] +# +# # Reshape tokens to spatial representation +# layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] +# +# layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] +# # Project layers to chosen feature dim +# layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] +# +# # get depth features +# depth_features = self.depth_encoder(depths) +# depth_feature1, depth_feature2, depth_feature3 = depth_features +# +# # Fuse layers using refinement stages +# path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]] +# path_3 = self.scratch.refinenet3(torch.cat([path_4, depth_feature3], dim=1), torch.cat([layers[2], depth_feature3], dim=1)) +# path_2 = self.scratch.refinenet2(torch.cat([path_3, depth_feature2], dim=1), torch.cat([layers[1], depth_feature2], dim=1)) +# path_1 = self.scratch.refinenet1(torch.cat([path_2, depth_feature1], dim=1), torch.cat([layers[0], depth_feature1], dim=1)) +# # path_3 = self.scratch.refinenet3(path_4, layers[2], depth_feature3) +# # path_2 = self.scratch.refinenet2(path_3, layers[1], depth_feature2) +# # path_1 = self.scratch.refinenet1(path_2, layers[0], depth_feature1) +# +# path_1 = self.feat_up(path_1) +# path_1 = torch.cat([path_1, imgs, depths], dim=1) +# if conf is not None: +# path_1 = torch.cat([path_1, conf], dim=1) +# path_1 = self.input_merger(path_1) +# +# # Output head +# out = self.head(path_1) +# +# return out + + +class DPTOutputAdapter_fix(DPTOutputAdapter): + """ + Adapt croco's DPTOutputAdapter implementation for dust3r: + remove duplicated weigths, and fix forward for dust3r + """ + + def init(self, dim_tokens_enc=768): + super().init(dim_tokens_enc) + # these are duplicated weights + del self.act_1_postprocess + del self.act_2_postprocess + del self.act_3_postprocess + del self.act_4_postprocess + + self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True) + # self.input_merger = nn.Sequential( + # # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1), + # # nn.Conv2d(3+6, 256, 7, 1, 3), + # nn.Conv2d(3, 256, 7, 1, 3), + # nn.ReLU(), + # ) + + def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None): + assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first' + # H, W = input_info['image_size'] + image_size = self.image_size if image_size is None else image_size + H, W = image_size + # Number of patches in height and width + N_H = H // (self.stride_level * self.P_H) + N_W = W // (self.stride_level * self.P_W) + + # Hook decoder onto 4 layers from specified ViT layers + layers = [encoder_tokens[hook] for hook in self.hooks] + + # Extract only task-relevant tokens and ignore global tokens. + layers = [self.adapt_tokens(l) for l in layers] + + # Reshape tokens to spatial representation + layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers] + + layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)] + # Project layers to chosen feature dim + layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)] + + # Fuse layers using refinement stages + path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]] + path_3 = self.scratch.refinenet3(path_4, layers[2]) + path_2 = self.scratch.refinenet2(path_3, layers[1]) + path_1 = self.scratch.refinenet1(path_2, layers[0]) + + # direct_img_feat = self.input_merger(imgs) + # actually, we just do interpolate here + # path_1 = self.feat_up(path_1) + path_1 = custom_interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True) + # path_1 = F.interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True) + # path_1 = path_1 + direct_img_feat + + # path_1 = torch.cat([path_1, imgs], dim=1) + + # Output head + # out = self.head(path_1) + out = path_1 + return out, [path_4, path_3, path_2] + + +class PixelwiseTaskWithDPT(nn.Module): + """ DPT module for dust3r, can return 3D points + confidence for all pixels""" + + def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None, + output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs): + super(PixelwiseTaskWithDPT, self).__init__() + self.return_all_layers = True # backbone needs to return all layers + self.postprocess = postprocess + self.depth_mode = depth_mode + self.conf_mode = conf_mode + + assert n_cls_token == 0, "Not implemented" + dpt_args = dict(output_width_ratio=output_width_ratio, + num_channels=num_channels, + **kwargs) + if hooks_idx is not None: + dpt_args.update(hooks=hooks_idx) + self.dpt = DPTOutputAdapter_fix(**dpt_args) + dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens} + self.dpt.init(**dpt_init_args) + + def forward(self, x, depths, imgs, img_info, conf=None): + out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf) + if self.postprocess: + out = self.postprocess(out, self.depth_mode, self.conf_mode) + return out, interm_feats + +class AttnBasedAppearanceHead(nn.Module): + """ + Attention head Appearence Reconstruction + """ + + def __init__(self, num_channels, patch_size, feature_dim, last_dim, hooks_idx, dim_tokens, postprocess, depth_mode, conf_mode, head_type='gs_params'): + super().__init__() + + self.num_channels = num_channels + self.patch_size = patch_size + + self.hooks = hooks_idx + + assert len(set(dim_tokens)) == 1 + + self.tokenizer = nn.Linear(3 * self.patch_size[0] ** 2 + 512, dim_tokens[0], bias=False) + self.C_feat = 128 + + self.vgg_feature_extractor = torchvision.models.vgg16(pretrained=True).features + # Freeze the VGG parameters + for param in self.vgg_feature_extractor.parameters(): + param.requires_grad = False + + self.token_decoder = nn.Sequential( + nn.Linear(dim_tokens[0] * (len(self.hooks) + 1), self.C_feat * (self.patch_size[0] ** 2)), + nn.SiLU(), + nn.Linear(self.C_feat * (self.patch_size[0] ** 2), self.C_feat * (self.patch_size[0] ** 2)), + ) + + self.pixel_linear = nn.Linear(self.C_feat, self.num_channels) + + + def img_pts_tokenizer(self, imgs): + _, _, H, W = imgs.shape + # Process images through VGG to extract features + # imgs = imgs.permute(0, 2, 3, 1).contiguous() + with torch.no_grad(): + vgg_features = self.vgg_feature_extractor(imgs) + + # 1. concat original images with vgg features and then patchify + vgg_features = F.interpolate(vgg_features, size=(H, W), mode='bilinear', align_corners=False) + combined = torch.cat([imgs, vgg_features], dim=1) # [B, C+512, H, W] + combined = combined.permute(0, 2, 3, 1).contiguous() + + patch_size = self.patch_size + hh = H // patch_size[0] + ww = W // patch_size[1] + input_patches = rearrange(combined, "b (hh ph) (ww pw) c -> b (hh ww) (ph pw c)", + hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1]) + + input_tokens = self.tokenizer(input_patches) + + # 2. only use vgg features, use a shallow conv to get the token + + # # Combine original images with VGG features + # imgs = torch.cat([imgs, vgg_features], dim=1) + # imgs = imgs.permute(0, 2, 3, 1).flatten(1, 2).contiguous() + + # # Pachify + # patch_size = self.patch_size + # hh = H // patch_size[0] + # ww = W // patch_size[1] + # input = rearrange(imgs, "b (hh ph ww pw) d -> b (hh ww) (ph pw d)", hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1]) + # Tokenize the input images + input_tokens = self.tokenizer(input) + return input_tokens + + def forward(self, x, depths, imgs, img_info, conf=None): + B, V, H, W = img_info + input_tokens = self.img_pts_tokenizer(imgs) + # Hook decoder onto 4 layers from specified ViT layers + layer_tokens = [x[hook] for hook in self.hooks] # [B, S, D] + # layer_tokens.append(input_tokens) + + x = self.token_decoder(torch.cat(layer_tokens, dim=-1)) + x = x.view(B*V, (H // self.patch_size[0]) * (W // self.patch_size[1]), self.patch_size[0]**2, self.C_feat).flatten(1, 2).contiguous() + out_flat = self.pixel_linear(x) + + return out_flat.view(B*V, H, W, -1).permute(0, 3, 1, 2) + +# class Pixellevel_Linear_Pts3d(nn.Module): +# """ +# Pixel-level linear head for DUST3R +# Each pixel outputs: 3D point (+ confidence) +# """ + +# def __init__(self, dec_embed_dim, patch_size, depth_mode, conf_mode, has_conf=False, index_hook=[-1]): +# super().__init__() +# self.patch_size = patch_size +# self.depth_mode = depth_mode +# self.conf_mode = conf_mode +# self.has_conf = has_conf +# self.dec_embed_dim = dec_embed_dim +# self.index_hook = index_hook + +# # Total embedding dimension per token (possibly concatenated) +# D = self.dec_embed_dim * len(self.index_hook) +# # Ensure divisible into pixel-level features +# assert D % (self.patch_size**2) == 0, \ +# f"Embedding dim {D} not divisible by patch_size^2 ({self.patch_size**2})" +# # Feature dimension for each pixel +# self.C_feat = D // (self.patch_size**2) * 4 +# # Output channels: x,y,z (+ confidence) +# self.out_dim = 3 + int(self.has_conf) + +# self.feat_expand = nn.Sequential(nn.Linear(D, 4*D), +# nn.SiLU(), +# nn.Linear(4*D, 4*D) +# ) +# # Per-pixel linear head +# self.pixel_linear = nn.Linear(self.C_feat, self.out_dim) + +# def setup(self, croconet): +# pass + +# def forward(self, decout, img_shape): +# H, W = img_shape +# # Combine specified decoder tokens: B x num_patches x D +# tokens = [decout[i] for i in self.index_hook] +# x = torch.cat(tokens, dim=-1) # B, S, D +# x = self.feat_expand(x) +# B, S, D = x.shape + +# # Validate pixel count +# assert S * (self.patch_size**2) == H * W, \ +# f"Mismatch: S*ps^2 ({S*self.patch_size**2}) != H*W ({H*W})" + +# # 1. Reshape embedding into pixel features +# # x -> B, S, (ps^2), C_feat -> flatten to B, (S*ps^2), C_feat +# x = x.view(B, S, self.patch_size**2, self.C_feat) +# x = x.reshape(B, S * self.patch_size**2, self.C_feat) + +# # 2. Per-pixel linear output +# out_flat = self.pixel_linear(x) # B, S*ps^2, out_dim + +# # 3. Reshape to image map: B x out_dim x H x W +# out = out_flat.permute(0, 2, 1).view(B, self.out_dim, H, W) + +# # 4. Postprocess depth/conf +# return out + +def create_gs_linear_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess): + """ + return PixelwiseTaskWithDPT for given net params + """ + assert net.dec_depth > 9 + l2 = net.dec_depth + feature_dim = net.feature_dim + last_dim = feature_dim//2 + ed = net.enc_embed_dim + dd = net.dec_embed_dim + try: + patch_size = net.patch_size + except: + patch_size = (16, 16) + + return AttnBasedAppearanceHead(num_channels=out_nchan + has_conf, + patch_size=patch_size, + feature_dim=feature_dim, + last_dim=last_dim, + hooks_idx=[0, l2*2//4, l2*3//4, l2], + dim_tokens=[ed, dd, dd, dd], + postprocess=postprocess_func, + depth_mode=net.depth_mode, + conf_mode=net.conf_mode, + head_type='gs_params') diff --git a/src/model/encoder/heads/linear_head.py b/src/model/encoder/heads/linear_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e1879e2912313400f97dad7159c4b8ca4291b395 --- /dev/null +++ b/src/model/encoder/heads/linear_head.py @@ -0,0 +1,73 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# linear head implementation for DUST3R +# -------------------------------------------------------- +import torch.nn as nn +import torch.nn.functional as F +from .postprocess import postprocess + + +class LinearPts3d (nn.Module): + """ + Linear head for dust3r + Each token outputs: - 16x16 3D points (+ confidence) + """ + + def __init__(self, net, has_conf=False): + super().__init__() + self.patch_size = net.patch_embed.patch_size[0] + self.depth_mode = net.depth_mode + self.conf_mode = net.conf_mode + self.has_conf = has_conf + + self.proj = nn.Linear(net.dec_embed_dim, (3 + has_conf)*self.patch_size**2) + + def setup(self, croconet): + pass + + def forward(self, decout, img_shape): + H, W = img_shape + tokens = decout[-1] + B, S, D = tokens.shape + + # extract 3D points + feat = self.proj(tokens) # B,S,D + feat = feat.transpose(-1, -2).view(B, -1, H//self.patch_size, W//self.patch_size) + feat = F.pixel_shuffle(feat, self.patch_size) # B,3,H,W + + # permute + norm depth + return postprocess(feat, self.depth_mode, self.conf_mode) + + +class LinearGS(nn.Module): + """ + Linear head for GS parameter prediction + Each token outputs: - 16x16 3D points (+ confidence) + """ + + def __init__(self, net, has_conf=False): + super().__init__() + self.patch_size = net.patch_embed.patch_size[0] + self.depth_mode = net.depth_mode + self.conf_mode = net.conf_mode + self.has_conf = has_conf + + self.proj = nn.Linear(net.dec_embed_dim, (2 + 1 + net.gaussian_adapter.d_in)*self.patch_size**2) # 2 for xy offset, 1 for opacity + + def setup(self, croconet): + pass + + def forward(self, decout, img_shape): + H, W = img_shape + tokens = decout[-1] + B, S, D = tokens.shape + + # extract 3D points + feat = self.proj(tokens) # B,S,D + feat = feat.transpose(-1, -2).view(B, -1, H//self.patch_size, W//self.patch_size) + feat = F.pixel_shuffle(feat, self.patch_size) # B,3,H,W + + # permute + norm depth + return postprocess(feat, self.depth_mode, self.conf_mode) diff --git a/src/model/encoder/heads/postprocess.py b/src/model/encoder/heads/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..35c98c68933f16e652c15b7392eb3a55d0b6fb9f --- /dev/null +++ b/src/model/encoder/heads/postprocess.py @@ -0,0 +1,77 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# post process function for all heads: extract 3D points/confidence from output +# -------------------------------------------------------- +import torch + + +def postprocess(out, depth_mode, conf_mode): + """ + extract 3D points/confidence from prediction head output + """ + fmap = out.permute(0, 2, 3, 1) # B,H,W,3 + res = dict(pts3d=reg_dense_depth(fmap[:, :, :, 0:3], mode=depth_mode)) + + if conf_mode is not None: + res['conf'] = reg_dense_conf(fmap[:, :, :, 3], mode=conf_mode) + return res + + +def reg_dense_depth(xyz, mode): + """ + extract 3D points from prediction head output + """ + mode, vmin, vmax = mode + + no_bounds = (vmin == -float('inf')) and (vmax == float('inf')) + # assert no_bounds + + if mode == 'range': + xyz = xyz.sigmoid() + xyz = (1 - xyz) * vmin + xyz * vmax + return xyz + + if mode == 'linear': + if no_bounds: + return xyz # [-inf, +inf] + return xyz.clip(min=vmin, max=vmax) + + if mode == 'exp_direct': + xyz = xyz.expm1() + return xyz.clip(min=vmin, max=vmax) + + # distance to origin + d = xyz.norm(dim=-1, keepdim=True) + xyz = xyz / d.clip(min=1e-8) + + if mode == 'square': + return xyz * d.square() + + if mode == 'exp': + exp_d = d.expm1() + if not no_bounds: + exp_d = exp_d.clip(min=vmin, max=vmax) + xyz = xyz * exp_d + # if not no_bounds: + # # xyz = xyz.clip(min=vmin, max=vmax) + # depth = xyz.clone()[..., 2].clip(min=vmin, max=vmax) + # xyz = torch.cat([xyz[..., :2], depth.unsqueeze(-1)], dim=-1) + return xyz + + raise ValueError(f'bad {mode=}') + + +def reg_dense_conf(x, mode): + """ + extract confidence from prediction head output + """ + mode, vmin, vmax = mode + if mode == 'opacity': + return x.sigmoid() + if mode == 'exp': + return vmin + x.exp().clip(max=vmax-vmin) + if mode == 'sigmoid': + return (vmax - vmin) * torch.sigmoid(x) + vmin + raise ValueError(f'bad {mode=}') diff --git a/src/model/encoder/heads/vggt_dpt_gs_head.py b/src/model/encoder/heads/vggt_dpt_gs_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d4f6c5d101ceeba7d2eff0887565fb485374dd --- /dev/null +++ b/src/model/encoder/heads/vggt_dpt_gs_head.py @@ -0,0 +1,195 @@ +# Copyright (C) 2024-present Naver Corporation. All rights reserved. +# Licensed under CC BY-NC-SA 4.0 (non-commercial use only). +# +# -------------------------------------------------------- +# dpt head implementation for DUST3R +# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ; +# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True +# the forward function also takes as input a dictionnary img_info with key "height" and "width" +# for PixelwiseTask, the output will be of dimension B x num_channels x H x W +# -------------------------------------------------------- +from einops import rearrange +from typing import List +import torch +import torch.nn as nn +import torch.nn.functional as F +# import dust3r.utils.path_to_croco +from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block +from src.model.encoder.vggt.heads.dpt_head import DPTHead +from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights +from .postprocess import postprocess + + + # def __init__(self, + # num_channels: int = 1, + # stride_level: int = 1, + # patch_size: Union[int, Tuple[int, int]] = 16, + # main_tasks: Iterable[str] = ('rgb',), + # hooks: List[int] = [2, 5, 8, 11], + # layer_dims: List[int] = [96, 192, 384, 768], + # feature_dim: int = 256, + # last_dim: int = 32, + # use_bn: bool = False, + # dim_tokens_enc: Optional[int] = None, + # head_type: str = 'regression', + # output_width_ratio=1, + +class VGGT_DPT_GS_Head(DPTHead): + def __init__(self, + dim_in: int, + patch_size: int = 14, + output_dim: int = 83, + activation: str = "inv_log", + conf_activation: str = "expp1", + features: int = 256, + out_channels: List[int] = [256, 512, 1024, 1024], + intermediate_layer_idx: List[int] = [4, 11, 17, 23], + pos_embed: bool = True, + feature_only: bool = False, + down_ratio: int = 1, + ): + super().__init__(dim_in, patch_size, output_dim, activation, conf_activation, features, out_channels, intermediate_layer_idx, pos_embed, feature_only, down_ratio) + + head_features_1 = 128 + head_features_2 = 128 if output_dim > 50 else 32 # sh=0, head_features_2 = 32; sh=4, head_features_2 = 128 + self.input_merger = nn.Sequential( + nn.Conv2d(3, head_features_2, 7, 1, 3), + nn.ReLU(), + ) + + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(head_features_1, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, patch_start_idx: int = 5, image_size=None, conf=None, frames_chunk_size: int = 8): + # H, W = input_info['image_size'] + B, S, _, H, W = imgs.shape + image_size = self.image_size if image_size is None else image_size + + # If frames_chunk_size is not specified or greater than S, process all frames at once + if frames_chunk_size is None or frames_chunk_size >= S: + return self._forward_impl(encoder_tokens, imgs, patch_start_idx) + + # Otherwise, process frames in chunks to manage memory usage + assert frames_chunk_size > 0 + + # Process frames in batches + all_preds = [] + + for frames_start_idx in range(0, S, frames_chunk_size): + frames_end_idx = min(frames_start_idx + frames_chunk_size, S) + + # Process batch of frames + chunk_output = self._forward_impl( + encoder_tokens, imgs, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_output) + + # Concatenate results along the sequence dimension + return torch.cat(all_preds, dim=1) + + def _forward_impl(self, encoder_tokens: List[torch.Tensor], imgs, patch_start_idx: int = 5, frames_start_idx: int = None, frames_end_idx: int = None): + + if frames_start_idx is not None and frames_end_idx is not None: + imgs = imgs[:, frames_start_idx:frames_end_idx] + + B, S, _, H, W = imgs.shape + + patch_h, patch_w = H // self.patch_size[0], W // self.patch_size[1] + + out = [] + dpt_idx = 0 + for layer_idx in self.intermediate_layer_idx: + # x = encoder_tokens[layer_idx][:, :, patch_start_idx:] + if len(encoder_tokens) > 10: + x = encoder_tokens[layer_idx][:, :, patch_start_idx:] + else: + list_idx = self.intermediate_layer_idx.index(layer_idx) + x = encoder_tokens[list_idx][:, :, patch_start_idx:] + + # Select frames if processing a chunk + if frames_start_idx is not None and frames_end_idx is not None: + x = x[:, frames_start_idx:frames_end_idx].contiguous() + + x = x.view(B * S, -1, x.shape[-1]) + + x = self.norm(x) + + x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) + + x = self.projects[dpt_idx](x) + if self.pos_embed: + x = self._apply_pos_embed(x, W, H) + x = self.resize_layers[dpt_idx](x) + + out.append(x) + dpt_idx += 1 + + # Fuse features from multiple layers. + out = self.scratch_forward(out) + direct_img_feat = self.input_merger(imgs.flatten(0,1)) + out = F.interpolate(out, size=(H, W), mode='bilinear', align_corners=True) + out = out + direct_img_feat + + if self.pos_embed: + out = self._apply_pos_embed(out, W, H) + + out = self.scratch.output_conv2(out) + out = out.view(B, S, *out.shape[1:]) + return out + + +class PixelwiseTaskWithDPT(nn.Module): + """ DPT module for dust3r, can return 3D points + confidence for all pixels""" + + def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None, + output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs): + super(PixelwiseTaskWithDPT, self).__init__() + self.return_all_layers = True # backbone needs to return all layers + self.postprocess = postprocess + self.depth_mode = depth_mode + self.conf_mode = conf_mode + + assert n_cls_token == 0, "Not implemented" + dpt_args = dict(output_width_ratio=output_width_ratio, + num_channels=num_channels, + **kwargs) + if hooks_idx is not None: + dpt_args.update(hooks=hooks_idx) + self.dpt = DPTOutputAdapter_fix(**dpt_args) + dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens} + self.dpt.init(**dpt_init_args) + + def forward(self, x, depths, imgs, img_info, conf=None): + out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf) + if self.postprocess: + out = self.postprocess(out, self.depth_mode, self.conf_mode) + return out, interm_feats + +def create_gs_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess): + """ + return PixelwiseTaskWithDPT for given net params + """ + assert net.dec_depth > 9 + l2 = net.dec_depth + feature_dim = net.feature_dim + last_dim = feature_dim//2 + ed = net.enc_embed_dim + dd = net.dec_embed_dim + try: + patch_size = net.patch_size + except: + patch_size = (16, 16) + + return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf, + patch_size=patch_size, + feature_dim=feature_dim, + last_dim=last_dim, + hooks_idx=[0, l2*2//4, l2*3//4, l2], + dim_tokens=[ed, dd, dd, dd], + postprocess=postprocess_func, + depth_mode=net.depth_mode, + conf_mode=net.conf_mode, + head_type='gs_params') \ No newline at end of file diff --git a/src/model/encoder/vggt/heads/camera_head.py b/src/model/encoder/vggt/heads/camera_head.py new file mode 100644 index 0000000000000000000000000000000000000000..eb854c2b1247499398ae6654418cd85d5843c08c --- /dev/null +++ b/src/model/encoder/vggt/heads/camera_head.py @@ -0,0 +1,168 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from src.model.encoder.vggt.layers import Mlp +from src.model.encoder.vggt.layers.block import Block +from src.model.encoder.vggt.heads.head_act import activate_pose + + +class CameraHead(nn.Module): + """ + CameraHead predicts camera parameters from token representations using iterative refinement. + + It applies a series of transformer blocks (the "trunk") to dedicated camera tokens. + """ + + def __init__( + self, + dim_in: int = 2048, + trunk_depth: int = 4, + pose_encoding_type: str = "absT_quaR_FoV", + num_heads: int = 16, + mlp_ratio: int = 4, + init_values: float = 0.01, + trans_act: str = "linear", + quat_act: str = "linear", + fl_act: str = "relu", # Field of view activations: ensures FOV values are positive. + ): + super().__init__() + + if pose_encoding_type == "absT_quaR_FoV": + self.target_dim = 9 + else: + raise ValueError(f"Unsupported camera encoding type: {pose_encoding_type}") + + self.trans_act = trans_act + self.quat_act = quat_act + self.fl_act = fl_act + self.trunk_depth = trunk_depth + + # Build the trunk using a sequence of transformer blocks. + self.trunk = nn.Sequential( + *[ + Block( + dim=dim_in, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + init_values=init_values, + ) + for _ in range(trunk_depth) + ] + ) + + # Normalizations for camera token and trunk output. + self.token_norm = nn.LayerNorm(dim_in) + self.trunk_norm = nn.LayerNorm(dim_in) + + # Learnable empty camera pose token. + self.empty_pose_tokens = nn.Parameter(torch.zeros(1, 1, self.target_dim)) + self.embed_pose = nn.Linear(self.target_dim, dim_in) + + # Module for producing modulation parameters: shift, scale, and a gate. + self.poseLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim_in, 3 * dim_in, bias=True)) + + # Adaptive layer normalization without affine parameters. + self.adaln_norm = nn.LayerNorm(dim_in, elementwise_affine=False, eps=1e-6) + self.pose_branch = Mlp( + in_features=dim_in, + hidden_features=dim_in // 2, + out_features=self.target_dim, + drop=0, + ) + + def forward(self, aggregated_tokens_list: list, num_iterations: int = 4) -> list: + """ + Forward pass to predict camera parameters. + + Args: + aggregated_tokens_list (list): List of token tensors from the network; + the last tensor is used for prediction. + num_iterations (int, optional): Number of iterative refinement steps. Defaults to 4. + + Returns: + list: A list of predicted camera encodings (post-activation) from each iteration. + """ + # Use tokens from the last block for camera prediction. + tokens = aggregated_tokens_list[-1] + + # Extract the camera tokens + pose_tokens = tokens[:, :, 0] + + pose_tokens = self.token_norm(pose_tokens) + + pred_pose_enc_list = self.trunk_fn(pose_tokens, num_iterations) + return pred_pose_enc_list + + def trunk_fn(self, pose_tokens: torch.Tensor, num_iterations: int) -> list: + """ + Iteratively refine camera pose predictions. + + Args: + pose_tokens (torch.Tensor): Normalized camera tokens with shape [B, 1, C]. + num_iterations (int): Number of refinement iterations. + + Returns: + list: List of activated camera encodings from each iteration. + """ + B, S, C = pose_tokens.shape # S is expected to be 1. + pred_pose_enc = None + pred_pose_enc_list = [] + + for _ in range(num_iterations): + # Use a learned empty pose for the first iteration. + if pred_pose_enc is None: + module_input = self.embed_pose(self.empty_pose_tokens.expand(B, S, -1)) + else: + # Detach the previous prediction to avoid backprop through time. + pred_pose_enc = pred_pose_enc.detach() + module_input = self.embed_pose(pred_pose_enc) + + # Generate modulation parameters and split them into shift, scale, and gate components. + shift_msa, scale_msa, gate_msa = self.poseLN_modulation(module_input).chunk(3, dim=-1) + + # Adaptive layer normalization and modulation. + pose_tokens_modulated = gate_msa * modulate(self.adaln_norm(pose_tokens), shift_msa, scale_msa) + pose_tokens_modulated = pose_tokens_modulated + pose_tokens + + pose_tokens_modulated = torch.utils.checkpoint.checkpoint( + self.trunk, + pose_tokens_modulated, + use_reentrant=False, + ) + + # Compute the delta update for the pose encoding. + pred_pose_enc_delta = self.pose_branch(self.trunk_norm(pose_tokens_modulated)) + + if pred_pose_enc is None: + pred_pose_enc = pred_pose_enc_delta + else: + pred_pose_enc = pred_pose_enc + pred_pose_enc_delta + + # Apply final activation functions for translation, quaternion, and field-of-view. + activated_pose = activate_pose( + pred_pose_enc, + trans_act=self.trans_act, + quat_act=self.quat_act, + fl_act=self.fl_act, + ) + pred_pose_enc_list.append(activated_pose) + + return pred_pose_enc_list + + +def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: + """ + Modulate the input tensor using scaling and shifting parameters. + """ + # modified from https://github.com/facebookresearch/DiT/blob/796c29e532f47bba17c5b9c5eb39b9354b8b7c64/models.py#L19 + return x * (1 + scale) + shift diff --git a/src/model/encoder/vggt/heads/dpt_head.py b/src/model/encoder/vggt/heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..42a625c317f221ac303fccd6983198dc82a823e0 --- /dev/null +++ b/src/model/encoder/vggt/heads/dpt_head.py @@ -0,0 +1,503 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +# Inspired by https://github.com/DepthAnything/Depth-Anything-V2 + + +import os +from typing import List, Dict, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from .head_act import activate_head +from .utils import create_uv_grid, position_grid_to_embed + + +class DPTHead(nn.Module): + """ + DPT Head for dense prediction tasks. + + This implementation follows the architecture described in "Vision Transformers for Dense Prediction" + (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer + backbone and produces dense predictions by fusing multi-scale features. + + Args: + dim_in (int): Input dimension (channels). + patch_size (int, optional): Patch size. Default is 14. + output_dim (int, optional): Number of output channels. Default is 4. + activation (str, optional): Activation type. Default is "inv_log". + conf_activation (str, optional): Confidence activation type. Default is "expp1". + features (int, optional): Feature channels for intermediate representations. Default is 256. + out_channels (List[int], optional): Output channels for each intermediate layer. + intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT. + pos_embed (bool, optional): Whether to use positional embedding. Default is True. + feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False. + down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1. + """ + + def __init__( + self, + dim_in: int, + patch_size: int = 14, + output_dim: int = 4, + activation: str = "inv_log", + conf_activation: str = "expp1", + features: int = 256, + out_channels: List[int] = [256, 512, 1024, 1024], + intermediate_layer_idx: List[int] = [4, 11, 17, 23], + pos_embed: bool = True, + feature_only: bool = False, + down_ratio: int = 1, + ) -> None: + super(DPTHead, self).__init__() + self.patch_size = patch_size + self.activation = activation + self.conf_activation = conf_activation + self.pos_embed = pos_embed + self.feature_only = feature_only + self.down_ratio = down_ratio + self.intermediate_layer_idx = intermediate_layer_idx + + self.norm = nn.LayerNorm(dim_in) + + # Projection layers for each output channel from tokens. + self.projects = nn.ModuleList( + [ + nn.Conv2d( + in_channels=dim_in, + out_channels=oc, + kernel_size=1, + stride=1, + padding=0, + ) + for oc in out_channels + ] + ) + + # Resize layers for upsampling feature maps. + self.resize_layers = nn.ModuleList( + [ + nn.ConvTranspose2d( + in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0 + ), + nn.ConvTranspose2d( + in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0 + ), + nn.Identity(), + nn.Conv2d( + in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1 + ), + ] + ) + + self.scratch = _make_scratch( + out_channels, + features, + expand=False, + ) + + # Attach additional modules to scratch. + self.scratch.stem_transpose = None + self.scratch.refinenet1 = _make_fusion_block(features) + self.scratch.refinenet2 = _make_fusion_block(features) + self.scratch.refinenet3 = _make_fusion_block(features) + self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False) + + head_features_1 = features + head_features_2 = 32 + + if feature_only: + self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1) + else: + self.scratch.output_conv1 = nn.Conv2d( + head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 + ) + conv2_in_channels = head_features_1 // 2 + + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + def forward( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_chunk_size: int = 8, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Forward pass through the DPT head, supports processing by chunking frames. + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. + patch_start_idx (int): Starting index for patch tokens in the token sequence. + Used to separate patch tokens from other tokens (e.g., camera or register tokens). + frames_chunk_size (int, optional): Number of frames to process in each chunk. + If None or larger than S, all frames are processed at once. Default: 8. + + Returns: + Tensor or Tuple[Tensor, Tensor]: + - If feature_only=True: Feature maps with shape [B, S, C, H, W] + - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W] + """ + B, S, _, H, W = images.shape + + # If frames_chunk_size is not specified or greater than S, process all frames at once + if frames_chunk_size is None or frames_chunk_size >= S: + return self._forward_impl(aggregated_tokens_list, images, patch_start_idx) + + # Otherwise, process frames in chunks to manage memory usage + assert frames_chunk_size > 0 + + # Process frames in batches + all_preds = [] + all_conf = [] + + for frames_start_idx in range(0, S, frames_chunk_size): + frames_end_idx = min(frames_start_idx + frames_chunk_size, S) + + # Process batch of frames + if self.feature_only: + chunk_output = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_output) + else: + chunk_preds, chunk_conf = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_preds) + all_conf.append(chunk_conf) + + # Concatenate results along the sequence dimension + if self.feature_only: + return torch.cat(all_preds, dim=1) + else: + return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1) + + def _forward_impl( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_start_idx: int = None, + frames_end_idx: int = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Implementation of the forward pass through the DPT head. + + This method processes a specific chunk of frames from the sequence. + + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W]. + patch_start_idx (int): Starting index for patch tokens. + frames_start_idx (int, optional): Starting index for frames to process. + frames_end_idx (int, optional): Ending index for frames to process. + + Returns: + Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence). + """ + if frames_start_idx is not None and frames_end_idx is not None: + images = images[:, frames_start_idx:frames_end_idx] + + B, S, _, H, W = images.shape + + patch_h, patch_w = H // self.patch_size, W // self.patch_size + + out = [] + dpt_idx = 0 + + for layer_idx in self.intermediate_layer_idx: + # x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] + if len(aggregated_tokens_list) > 10: + x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] + else: + list_idx = self.intermediate_layer_idx.index(layer_idx) + x = aggregated_tokens_list[list_idx][:, :, patch_start_idx:] + + # Select frames if processing a chunk + if frames_start_idx is not None and frames_end_idx is not None: + x = x[:, frames_start_idx:frames_end_idx].contiguous() + + x = x.view(B * S, -1, x.shape[-1]) + x = self.norm(x) + + x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) + + x = x.to(self.projects[dpt_idx].weight.dtype) + x = self.projects[dpt_idx](x) + if self.pos_embed: + x = self._apply_pos_embed(x, W, H) + + x = self.resize_layers[dpt_idx](x) + + out.append(x) + dpt_idx += 1 + + # Fuse features from multiple layers. + out = self.scratch_forward(out) + # Interpolate fused output to match target image resolution. + out = custom_interpolate( + out, + (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)), + mode="bilinear", + align_corners=True, + ) + + if self.pos_embed: + out = self._apply_pos_embed(out, W, H) + + if self.feature_only: + return out.view(B, S, *out.shape[1:]) + + out = self.scratch.output_conv2(out) + preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation) + + preds = preds.view(B, S, *preds.shape[1:]) + conf = conf.view(B, S, *conf.shape[1:]) + return preds, conf + + def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: + """ + Apply positional embedding to tensor x. + """ + patch_w = x.shape[-1] + patch_h = x.shape[-2] + pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device) + pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) + pos_embed = pos_embed * ratio + pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) + return x + pos_embed + + def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor: + """ + Forward pass through the fusion blocks. + + Args: + features (List[Tensor]): List of feature maps from different layers. + + Returns: + Tensor: Fused feature map. + """ + layer_1, layer_2, layer_3, layer_4 = features + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) + del layer_4_rn, layer_4 + + out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:]) + del layer_3_rn, layer_3 + + out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:]) + del layer_2_rn, layer_2 + + out = self.scratch.refinenet1(out, layer_1_rn) + del layer_1_rn, layer_1 + + out = self.scratch.output_conv1(out) + return out + + +################################################################################ +# Modules +################################################################################ + + +def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module: + return FeatureFusionBlock( + features, + nn.ReLU(inplace=True), + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=size, + has_residual=has_residual, + groups=groups, + ) + + +def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module: + scratch = nn.Module() + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + if len(in_shape) >= 4: + out_shape4 = out_shape + + if expand: + out_shape1 = out_shape + out_shape2 = out_shape * 2 + out_shape3 = out_shape * 4 + if len(in_shape) >= 4: + out_shape4 = out_shape * 8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + if len(in_shape) >= 4: + scratch.layer4_rn = nn.Conv2d( + in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + return scratch + + +class ResidualConvUnit(nn.Module): + """Residual convolution module.""" + + def __init__(self, features, activation, bn, groups=1): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + self.groups = groups + self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + + self.norm1 = None + self.norm2 = None + + self.activation = activation + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.norm1 is not None: + out = self.norm1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.norm2 is not None: + out = self.norm2(out) + + return self.skip_add.add(out, x) + + +class FeatureFusionBlock(nn.Module): + """Feature fusion block.""" + + def __init__( + self, + features, + activation, + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=None, + has_residual=True, + groups=1, + ): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock, self).__init__() + + self.deconv = deconv + self.align_corners = align_corners + self.groups = groups + self.expand = expand + out_features = features + if self.expand == True: + out_features = features // 2 + + self.out_conv = nn.Conv2d( + features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups + ) + + if has_residual: + self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.has_residual = has_residual + self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.skip_add = nn.quantized.FloatFunctional() + self.size = size + + def forward(self, *xs, size=None): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if self.has_residual: + res = self.resConfUnit1(xs[1]) + output = self.skip_add.add(output, res) + + output = self.resConfUnit2(output) + + if (size is None) and (self.size is None): + modifier = {"scale_factor": 2} + elif size is None: + modifier = {"size": self.size} + else: + modifier = {"size": size} + + output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners) + output = self.out_conv(output) + + return output + + +def custom_interpolate( + x: torch.Tensor, + size: Tuple[int, int] = None, + scale_factor: float = None, + mode: str = "bilinear", + align_corners: bool = True, +) -> torch.Tensor: + """ + Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. + """ + if size is None: + size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) + + INT_MAX = 1610612736 + + input_elements = size[0] * size[1] * x.shape[0] * x.shape[1] + + if input_elements > INT_MAX: + chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) + interpolated_chunks = [ + nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks + ] + x = torch.cat(interpolated_chunks, dim=0) + return x.contiguous() + else: + return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) diff --git a/src/model/encoder/vggt/heads/head_act.py b/src/model/encoder/vggt/heads/head_act.py new file mode 100644 index 0000000000000000000000000000000000000000..260888d888b7ef49588f9719ac07ec4b8a7dcb98 --- /dev/null +++ b/src/model/encoder/vggt/heads/head_act.py @@ -0,0 +1,125 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import torch +import torch.nn.functional as F + + +def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"): + """ + Activate pose parameters with specified activation functions. + + Args: + pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length] + trans_act: Activation type for translation component + quat_act: Activation type for quaternion component + fl_act: Activation type for focal length component + + Returns: + Activated pose parameters tensor + """ + T = pred_pose_enc[..., :3] + quat = pred_pose_enc[..., 3:7] + fl = pred_pose_enc[..., 7:] # or fov + + T = base_pose_act(T, trans_act) + quat = base_pose_act(quat, quat_act) + fl = base_pose_act(fl, fl_act) # or fov + + pred_pose_enc = torch.cat([T, quat, fl], dim=-1) + + return pred_pose_enc + + +def base_pose_act(pose_enc, act_type="linear"): + """ + Apply basic activation function to pose parameters. + + Args: + pose_enc: Tensor containing encoded pose parameters + act_type: Activation type ("linear", "inv_log", "exp", "relu") + + Returns: + Activated pose parameters + """ + if act_type == "linear": + return pose_enc + elif act_type == "inv_log": + return inverse_log_transform(pose_enc) + elif act_type == "exp": + return torch.exp(pose_enc) + elif act_type == "relu": + return F.relu(pose_enc) + else: + raise ValueError(f"Unknown act_type: {act_type}") + + +def activate_head(out, activation="norm_exp", conf_activation="expp1"): + """ + Process network output to extract 3D points and confidence values. + + Args: + out: Network output tensor (B, C, H, W) + activation: Activation type for 3D points + conf_activation: Activation type for confidence values + + Returns: + Tuple of (3D points tensor, confidence tensor) + """ + # Move channels from last dim to the 4th dimension => (B, H, W, C) + fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected + + # Split into xyz (first C-1 channels) and confidence (last channel) + xyz = fmap[:, :, :, :-1] + conf = fmap[:, :, :, -1] + + if activation == "norm_exp": + d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) + xyz_normed = xyz / d + pts3d = xyz_normed * torch.expm1(d) + elif activation == "norm": + pts3d = xyz / xyz.norm(dim=-1, keepdim=True) + elif activation == "exp": + pts3d = torch.exp(xyz) + elif activation == "relu": + pts3d = F.relu(xyz) + elif activation == "inv_log": + pts3d = inverse_log_transform(xyz) + elif activation == "xy_inv_log": + xy, z = xyz.split([2, 1], dim=-1) + z = inverse_log_transform(z) + pts3d = torch.cat([xy * z, z], dim=-1) + elif activation == "sigmoid": + pts3d = torch.sigmoid(xyz) + elif activation == "linear": + pts3d = xyz + else: + raise ValueError(f"Unknown activation: {activation}") + + if conf_activation == "expp1": + conf_out = 1 + conf.exp() + elif conf_activation == "expp0": + conf_out = conf.exp() + elif conf_activation == "sigmoid": + conf_out = torch.sigmoid(conf) + else: + raise ValueError(f"Unknown conf_activation: {conf_activation}") + + return pts3d, conf_out + + +def inverse_log_transform(y): + """ + Apply inverse log transform: sign(y) * (exp(|y|) - 1) + + Args: + y: Input tensor + + Returns: + Transformed tensor + """ + return torch.sign(y) * (torch.expm1(torch.abs(y))) diff --git a/src/model/encoder/vggt/heads/track_head.py b/src/model/encoder/vggt/heads/track_head.py new file mode 100644 index 0000000000000000000000000000000000000000..27fa06726c147fa4a611f7bed58dae767fb3f354 --- /dev/null +++ b/src/model/encoder/vggt/heads/track_head.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch.nn as nn +from .dpt_head import DPTHead +from .track_modules.base_track_predictor import BaseTrackerPredictor + + +class TrackHead(nn.Module): + """ + Track head that uses DPT head to process tokens and BaseTrackerPredictor for tracking. + The tracking is performed iteratively, refining predictions over multiple iterations. + """ + + def __init__( + self, + dim_in, + patch_size=14, + features=128, + iters=4, + predict_conf=True, + stride=2, + corr_levels=7, + corr_radius=4, + hidden_size=384, + ): + """ + Initialize the TrackHead module. + + Args: + dim_in (int): Input dimension of tokens from the backbone. + patch_size (int): Size of image patches used in the vision transformer. + features (int): Number of feature channels in the feature extractor output. + iters (int): Number of refinement iterations for tracking predictions. + predict_conf (bool): Whether to predict confidence scores for tracked points. + stride (int): Stride value for the tracker predictor. + corr_levels (int): Number of correlation pyramid levels + corr_radius (int): Radius for correlation computation, controlling the search area. + hidden_size (int): Size of hidden layers in the tracker network. + """ + super().__init__() + + self.patch_size = patch_size + + # Feature extractor based on DPT architecture + # Processes tokens into feature maps for tracking + self.feature_extractor = DPTHead( + dim_in=dim_in, + patch_size=patch_size, + features=features, + feature_only=True, # Only output features, no activation + down_ratio=2, # Reduces spatial dimensions by factor of 2 + pos_embed=False, + ) + + # Tracker module that predicts point trajectories + # Takes feature maps and predicts coordinates and visibility + self.tracker = BaseTrackerPredictor( + latent_dim=features, # Match the output_dim of feature extractor + predict_conf=predict_conf, + stride=stride, + corr_levels=corr_levels, + corr_radius=corr_radius, + hidden_size=hidden_size, + ) + + self.iters = iters + + def forward(self, aggregated_tokens_list, images, patch_start_idx, query_points=None, iters=None): + """ + Forward pass of the TrackHead. + + Args: + aggregated_tokens_list (list): List of aggregated tokens from the backbone. + images (torch.Tensor): Input images of shape (B, S, C, H, W) where: + B = batch size, S = sequence length. + patch_start_idx (int): Starting index for patch tokens. + query_points (torch.Tensor, optional): Initial query points to track. + If None, points are initialized by the tracker. + iters (int, optional): Number of refinement iterations. If None, uses self.iters. + + Returns: + tuple: + - coord_preds (torch.Tensor): Predicted coordinates for tracked points. + - vis_scores (torch.Tensor): Visibility scores for tracked points. + - conf_scores (torch.Tensor): Confidence scores for tracked points (if predict_conf=True). + """ + B, S, _, H, W = images.shape + + # Extract features from tokens + # feature_maps has shape (B, S, C, H//2, W//2) due to down_ratio=2 + feature_maps = self.feature_extractor(aggregated_tokens_list, images, patch_start_idx) + + # Use default iterations if not specified + if iters is None: + iters = self.iters + + # Perform tracking using the extracted features + coord_preds, vis_scores, conf_scores = self.tracker( + query_points=query_points, + fmaps=feature_maps, + iters=iters, + ) + + return coord_preds, vis_scores, conf_scores diff --git a/src/model/encoder/vggt/heads/track_modules/__init__.py b/src/model/encoder/vggt/heads/track_modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4196294309799347172dba54a17360698071ca8 --- /dev/null +++ b/src/model/encoder/vggt/heads/track_modules/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/src/model/encoder/vggt/heads/track_modules/base_track_predictor.py b/src/model/encoder/vggt/heads/track_modules/base_track_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..540c1d110d4b35b36fdbd2a8a81121d9f9cf2f9b --- /dev/null +++ b/src/model/encoder/vggt/heads/track_modules/base_track_predictor.py @@ -0,0 +1,209 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from einops import rearrange, repeat + + +from .blocks import EfficientUpdateFormer, CorrBlock +from .utils import sample_features4d, get_2d_embedding, get_2d_sincos_pos_embed +from .modules import Mlp + + +class BaseTrackerPredictor(nn.Module): + def __init__( + self, + stride=1, + corr_levels=5, + corr_radius=4, + latent_dim=128, + hidden_size=384, + use_spaceatt=True, + depth=6, + max_scale=518, + predict_conf=True, + ): + super(BaseTrackerPredictor, self).__init__() + """ + The base template to create a track predictor + + Modified from https://github.com/facebookresearch/co-tracker/ + and https://github.com/facebookresearch/vggsfm + """ + + self.stride = stride + self.latent_dim = latent_dim + self.corr_levels = corr_levels + self.corr_radius = corr_radius + self.hidden_size = hidden_size + self.max_scale = max_scale + self.predict_conf = predict_conf + + self.flows_emb_dim = latent_dim // 2 + + self.corr_mlp = Mlp( + in_features=self.corr_levels * (self.corr_radius * 2 + 1) ** 2, + hidden_features=self.hidden_size, + out_features=self.latent_dim, + ) + + self.transformer_dim = self.latent_dim + self.latent_dim + self.latent_dim + 4 + + self.query_ref_token = nn.Parameter(torch.randn(1, 2, self.transformer_dim)) + + space_depth = depth if use_spaceatt else 0 + time_depth = depth + + self.updateformer = EfficientUpdateFormer( + space_depth=space_depth, + time_depth=time_depth, + input_dim=self.transformer_dim, + hidden_size=self.hidden_size, + output_dim=self.latent_dim + 2, + mlp_ratio=4.0, + add_space_attn=use_spaceatt, + ) + + self.fmap_norm = nn.LayerNorm(self.latent_dim) + self.ffeat_norm = nn.GroupNorm(1, self.latent_dim) + + # A linear layer to update track feats at each iteration + self.ffeat_updater = nn.Sequential(nn.Linear(self.latent_dim, self.latent_dim), nn.GELU()) + + self.vis_predictor = nn.Sequential(nn.Linear(self.latent_dim, 1)) + + if predict_conf: + self.conf_predictor = nn.Sequential(nn.Linear(self.latent_dim, 1)) + + def forward(self, query_points, fmaps=None, iters=6, return_feat=False, down_ratio=1, apply_sigmoid=True): + """ + query_points: B x N x 2, the number of batches, tracks, and xy + fmaps: B x S x C x HH x WW, the number of batches, frames, and feature dimension. + note HH and WW is the size of feature maps instead of original images + """ + B, N, D = query_points.shape + B, S, C, HH, WW = fmaps.shape + + assert D == 2, "Input points must be 2D coordinates" + + # apply a layernorm to fmaps here + fmaps = self.fmap_norm(fmaps.permute(0, 1, 3, 4, 2)) + fmaps = fmaps.permute(0, 1, 4, 2, 3) + + # Scale the input query_points because we may downsample the images + # by down_ratio or self.stride + # e.g., if a 3x1024x1024 image is processed to a 128x256x256 feature map + # its query_points should be query_points/4 + if down_ratio > 1: + query_points = query_points / float(down_ratio) + + query_points = query_points / float(self.stride) + + # Init with coords as the query points + # It means the search will start from the position of query points at the reference frames + coords = query_points.clone().reshape(B, 1, N, 2).repeat(1, S, 1, 1) + + # Sample/extract the features of the query points in the query frame + query_track_feat = sample_features4d(fmaps[:, 0], coords[:, 0]) + + # init track feats by query feats + track_feats = query_track_feat.unsqueeze(1).repeat(1, S, 1, 1) # B, S, N, C + # back up the init coords + coords_backup = coords.clone() + + fcorr_fn = CorrBlock(fmaps, num_levels=self.corr_levels, radius=self.corr_radius) + + coord_preds = [] + + # Iterative Refinement + for _ in range(iters): + # Detach the gradients from the last iteration + # (in my experience, not very important for performance) + coords = coords.detach() + + fcorrs = fcorr_fn.corr_sample(track_feats, coords) + + corr_dim = fcorrs.shape[3] + fcorrs_ = fcorrs.permute(0, 2, 1, 3).reshape(B * N, S, corr_dim) + fcorrs_ = self.corr_mlp(fcorrs_) + + # Movement of current coords relative to query points + flows = (coords - coords[:, 0:1]).permute(0, 2, 1, 3).reshape(B * N, S, 2) + + flows_emb = get_2d_embedding(flows, self.flows_emb_dim, cat_coords=False) + + # (In my trials, it is also okay to just add the flows_emb instead of concat) + flows_emb = torch.cat([flows_emb, flows / self.max_scale, flows / self.max_scale], dim=-1) + + track_feats_ = track_feats.permute(0, 2, 1, 3).reshape(B * N, S, self.latent_dim) + + # Concatenate them as the input for the transformers + transformer_input = torch.cat([flows_emb, fcorrs_, track_feats_], dim=2) + + # 2D positional embed + # TODO: this can be much simplified + pos_embed = get_2d_sincos_pos_embed(self.transformer_dim, grid_size=(HH, WW)).to(query_points.device) + sampled_pos_emb = sample_features4d(pos_embed.expand(B, -1, -1, -1), coords[:, 0]) + + sampled_pos_emb = rearrange(sampled_pos_emb, "b n c -> (b n) c").unsqueeze(1) + + x = transformer_input + sampled_pos_emb + + # Add the query ref token to the track feats + query_ref_token = torch.cat( + [self.query_ref_token[:, 0:1], self.query_ref_token[:, 1:2].expand(-1, S - 1, -1)], dim=1 + ) + x = x + query_ref_token.to(x.device).to(x.dtype) + + # B, N, S, C + x = rearrange(x, "(b n) s d -> b n s d", b=B) + + # Compute the delta coordinates and delta track features + delta, _ = self.updateformer(x) + + # BN, S, C + delta = rearrange(delta, " b n s d -> (b n) s d", b=B) + delta_coords_ = delta[:, :, :2] + delta_feats_ = delta[:, :, 2:] + + track_feats_ = track_feats_.reshape(B * N * S, self.latent_dim) + delta_feats_ = delta_feats_.reshape(B * N * S, self.latent_dim) + + # Update the track features + track_feats_ = self.ffeat_updater(self.ffeat_norm(delta_feats_)) + track_feats_ + + track_feats = track_feats_.reshape(B, N, S, self.latent_dim).permute(0, 2, 1, 3) # BxSxNxC + + # B x S x N x 2 + coords = coords + delta_coords_.reshape(B, N, S, 2).permute(0, 2, 1, 3) + + # Force coord0 as query + # because we assume the query points should not be changed + coords[:, 0] = coords_backup[:, 0] + + # The predicted tracks are in the original image scale + if down_ratio > 1: + coord_preds.append(coords * self.stride * down_ratio) + else: + coord_preds.append(coords * self.stride) + + # B, S, N + vis_e = self.vis_predictor(track_feats.reshape(B * S * N, self.latent_dim)).reshape(B, S, N) + if apply_sigmoid: + vis_e = torch.sigmoid(vis_e) + + if self.predict_conf: + conf_e = self.conf_predictor(track_feats.reshape(B * S * N, self.latent_dim)).reshape(B, S, N) + if apply_sigmoid: + conf_e = torch.sigmoid(conf_e) + else: + conf_e = None + + if return_feat: + return coord_preds, vis_e, track_feats, query_track_feat, conf_e + else: + return coord_preds, vis_e, conf_e diff --git a/src/model/encoder/vggt/heads/track_modules/blocks.py b/src/model/encoder/vggt/heads/track_modules/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4ea13611d6aa4171a3cb4224685bcd48a717c9 --- /dev/null +++ b/src/model/encoder/vggt/heads/track_modules/blocks.py @@ -0,0 +1,246 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +# Modified from https://github.com/facebookresearch/co-tracker/ + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .utils import bilinear_sampler +from .modules import Mlp, AttnBlock, CrossAttnBlock, ResidualBlock + + +class EfficientUpdateFormer(nn.Module): + """ + Transformer model that updates track estimates. + """ + + def __init__( + self, + space_depth=6, + time_depth=6, + input_dim=320, + hidden_size=384, + num_heads=8, + output_dim=130, + mlp_ratio=4.0, + add_space_attn=True, + num_virtual_tracks=64, + ): + super().__init__() + + self.out_channels = 2 + self.num_heads = num_heads + self.hidden_size = hidden_size + self.add_space_attn = add_space_attn + + # Add input LayerNorm before linear projection + self.input_norm = nn.LayerNorm(input_dim) + self.input_transform = torch.nn.Linear(input_dim, hidden_size, bias=True) + + # Add output LayerNorm before final projection + self.output_norm = nn.LayerNorm(hidden_size) + self.flow_head = torch.nn.Linear(hidden_size, output_dim, bias=True) + self.num_virtual_tracks = num_virtual_tracks + + if self.add_space_attn: + self.virual_tracks = nn.Parameter(torch.randn(1, num_virtual_tracks, 1, hidden_size)) + else: + self.virual_tracks = None + + self.time_blocks = nn.ModuleList( + [ + AttnBlock( + hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + attn_class=nn.MultiheadAttention, + ) + for _ in range(time_depth) + ] + ) + + if add_space_attn: + self.space_virtual_blocks = nn.ModuleList( + [ + AttnBlock( + hidden_size, + num_heads, + mlp_ratio=mlp_ratio, + attn_class=nn.MultiheadAttention, + ) + for _ in range(space_depth) + ] + ) + self.space_point2virtual_blocks = nn.ModuleList( + [CrossAttnBlock(hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(space_depth)] + ) + self.space_virtual2point_blocks = nn.ModuleList( + [CrossAttnBlock(hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(space_depth)] + ) + assert len(self.time_blocks) >= len(self.space_virtual2point_blocks) + self.initialize_weights() + + def initialize_weights(self): + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + torch.nn.init.trunc_normal_(self.flow_head.weight, std=0.001) + + self.apply(_basic_init) + + def forward(self, input_tensor, mask=None): + # Apply input LayerNorm + input_tensor = self.input_norm(input_tensor) + tokens = self.input_transform(input_tensor) + + init_tokens = tokens + + B, _, T, _ = tokens.shape + + if self.add_space_attn: + virtual_tokens = self.virual_tracks.repeat(B, 1, T, 1) + tokens = torch.cat([tokens, virtual_tokens], dim=1) + + _, N, _, _ = tokens.shape + + j = 0 + for i in range(len(self.time_blocks)): + time_tokens = tokens.contiguous().view(B * N, T, -1) # B N T C -> (B N) T C + + time_tokens = self.time_blocks[i](time_tokens) + + tokens = time_tokens.view(B, N, T, -1) # (B N) T C -> B N T C + if self.add_space_attn and (i % (len(self.time_blocks) // len(self.space_virtual_blocks)) == 0): + space_tokens = tokens.permute(0, 2, 1, 3).contiguous().view(B * T, N, -1) # B N T C -> (B T) N C + point_tokens = space_tokens[:, : N - self.num_virtual_tracks] + virtual_tokens = space_tokens[:, N - self.num_virtual_tracks :] + + virtual_tokens = self.space_virtual2point_blocks[j](virtual_tokens, point_tokens, mask=mask) + virtual_tokens = self.space_virtual_blocks[j](virtual_tokens) + point_tokens = self.space_point2virtual_blocks[j](point_tokens, virtual_tokens, mask=mask) + + space_tokens = torch.cat([point_tokens, virtual_tokens], dim=1) + tokens = space_tokens.view(B, T, N, -1).permute(0, 2, 1, 3) # (B T) N C -> B N T C + j += 1 + + if self.add_space_attn: + tokens = tokens[:, : N - self.num_virtual_tracks] + + tokens = tokens + init_tokens + + # Apply output LayerNorm before final projection + tokens = self.output_norm(tokens) + flow = self.flow_head(tokens) + + return flow, None + + +class CorrBlock: + def __init__(self, fmaps, num_levels=4, radius=4, multiple_track_feats=False, padding_mode="zeros"): + """ + Build a pyramid of feature maps from the input. + + fmaps: Tensor (B, S, C, H, W) + num_levels: number of pyramid levels (each downsampled by factor 2) + radius: search radius for sampling correlation + multiple_track_feats: if True, split the target features per pyramid level + padding_mode: passed to grid_sample / bilinear_sampler + """ + B, S, C, H, W = fmaps.shape + self.S, self.C, self.H, self.W = S, C, H, W + self.num_levels = num_levels + self.radius = radius + self.padding_mode = padding_mode + self.multiple_track_feats = multiple_track_feats + + # Build pyramid: each level is half the spatial resolution of the previous + self.fmaps_pyramid = [fmaps] # level 0 is full resolution + current_fmaps = fmaps + for i in range(num_levels - 1): + B, S, C, H, W = current_fmaps.shape + # Merge batch & sequence dimensions + current_fmaps = current_fmaps.reshape(B * S, C, H, W) + # Avg pool down by factor 2 + current_fmaps = F.avg_pool2d(current_fmaps, kernel_size=2, stride=2) + _, _, H_new, W_new = current_fmaps.shape + current_fmaps = current_fmaps.reshape(B, S, C, H_new, W_new) + self.fmaps_pyramid.append(current_fmaps) + + # Precompute a delta grid (of shape (2r+1, 2r+1, 2)) for sampling. + # This grid is added to the (scaled) coordinate centroids. + r = self.radius + dx = torch.linspace(-r, r, 2 * r + 1, device=fmaps.device, dtype=fmaps.dtype) + dy = torch.linspace(-r, r, 2 * r + 1, device=fmaps.device, dtype=fmaps.dtype) + # delta: for every (dy,dx) displacement (i.e. Δx, Δy) + self.delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), dim=-1) # shape: (2r+1, 2r+1, 2) + + def corr_sample(self, targets, coords): + """ + Instead of storing the entire correlation pyramid, we compute each level's correlation + volume, sample it immediately, then discard it. This saves GPU memory. + + Args: + targets: Tensor (B, S, N, C) — features for the current targets. + coords: Tensor (B, S, N, 2) — coordinates at full resolution. + + Returns: + Tensor (B, S, N, L) where L = num_levels * (2*radius+1)**2 (concatenated sampled correlations) + """ + B, S, N, C = targets.shape + + # If you have multiple track features, split them per level. + if self.multiple_track_feats: + targets_split = torch.split(targets, C // self.num_levels, dim=-1) + + out_pyramid = [] + for i, fmaps in enumerate(self.fmaps_pyramid): + # Get current spatial resolution H, W for this pyramid level. + B, S, C, H, W = fmaps.shape + # Reshape feature maps for correlation computation: + # fmap2s: (B, S, C, H*W) + fmap2s = fmaps.view(B, S, C, H * W) + # Choose appropriate target features. + fmap1 = targets_split[i] if self.multiple_track_feats else targets # shape: (B, S, N, C) + + # Compute correlation directly + corrs = compute_corr_level(fmap1, fmap2s, C) + corrs = corrs.view(B, S, N, H, W) + + # Prepare sampling grid: + # Scale down the coordinates for the current level. + centroid_lvl = coords.reshape(B * S * N, 1, 1, 2) / (2**i) + # Make sure our precomputed delta grid is on the same device/dtype. + delta_lvl = self.delta.to(coords.device).to(coords.dtype) + # Now the grid for grid_sample is: + # coords_lvl = centroid_lvl + delta_lvl (broadcasted over grid) + coords_lvl = centroid_lvl + delta_lvl.view(1, 2 * self.radius + 1, 2 * self.radius + 1, 2) + + # Sample from the correlation volume using bilinear interpolation. + # We reshape corrs to (B * S * N, 1, H, W) so grid_sample acts over each target. + corrs_sampled = bilinear_sampler( + corrs.reshape(B * S * N, 1, H, W), coords_lvl, padding_mode=self.padding_mode + ) + # The sampled output is (B * S * N, 1, 2r+1, 2r+1). Flatten the last two dims. + corrs_sampled = corrs_sampled.view(B, S, N, -1) # Now shape: (B, S, N, (2r+1)^2) + out_pyramid.append(corrs_sampled) + + # Concatenate all levels along the last dimension. + out = torch.cat(out_pyramid, dim=-1).contiguous() + return out + + +def compute_corr_level(fmap1, fmap2s, C): + # fmap1: (B, S, N, C) + # fmap2s: (B, S, C, H*W) + corrs = torch.matmul(fmap1, fmap2s) # (B, S, N, H*W) + corrs = corrs.view(fmap1.shape[0], fmap1.shape[1], fmap1.shape[2], -1) # (B, S, N, H*W) + return corrs / math.sqrt(C) diff --git a/src/model/encoder/vggt/heads/track_modules/modules.py b/src/model/encoder/vggt/heads/track_modules/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..68b4a826cb8b064d4e423e8c8273afd66e43e992 --- /dev/null +++ b/src/model/encoder/vggt/heads/track_modules/modules.py @@ -0,0 +1,218 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +from typing import Callable +import collections +from torch import Tensor +from itertools import repeat + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): + return tuple(x) + return tuple(repeat(x, n)) + + return parse + + +def exists(val): + return val is not None + + +def default(val, d): + return val if exists(val) else d + + +to_2tuple = _ntuple(2) + + +class ResidualBlock(nn.Module): + """ + ResidualBlock: construct a block of two conv layers with residual connections + """ + + def __init__(self, in_planes, planes, norm_fn="group", stride=1, kernel_size=3): + super(ResidualBlock, self).__init__() + + self.conv1 = nn.Conv2d( + in_planes, + planes, + kernel_size=kernel_size, + padding=1, + stride=stride, + padding_mode="zeros", + ) + self.conv2 = nn.Conv2d( + planes, + planes, + kernel_size=kernel_size, + padding=1, + padding_mode="zeros", + ) + self.relu = nn.ReLU(inplace=True) + + num_groups = planes // 8 + + if norm_fn == "group": + self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + if not stride == 1: + self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) + + elif norm_fn == "batch": + self.norm1 = nn.BatchNorm2d(planes) + self.norm2 = nn.BatchNorm2d(planes) + if not stride == 1: + self.norm3 = nn.BatchNorm2d(planes) + + elif norm_fn == "instance": + self.norm1 = nn.InstanceNorm2d(planes) + self.norm2 = nn.InstanceNorm2d(planes) + if not stride == 1: + self.norm3 = nn.InstanceNorm2d(planes) + + elif norm_fn == "none": + self.norm1 = nn.Sequential() + self.norm2 = nn.Sequential() + if not stride == 1: + self.norm3 = nn.Sequential() + else: + raise NotImplementedError + + if stride == 1: + self.downsample = None + else: + self.downsample = nn.Sequential( + nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), + self.norm3, + ) + + def forward(self, x): + y = x + y = self.relu(self.norm1(self.conv1(y))) + y = self.relu(self.norm2(self.conv2(y))) + + if self.downsample is not None: + x = self.downsample(x) + + return self.relu(x + y) + + +class Mlp(nn.Module): + """MLP as used in Vision Transformer, MLP-Mixer and related networks""" + + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + norm_layer=None, + bias=True, + drop=0.0, + use_conv=False, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + bias = to_2tuple(bias) + drop_probs = to_2tuple(drop) + linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear + + self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0]) + self.act = act_layer() + self.drop1 = nn.Dropout(drop_probs[0]) + self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1]) + self.drop2 = nn.Dropout(drop_probs[1]) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop1(x) + x = self.fc2(x) + x = self.drop2(x) + return x + + +class AttnBlock(nn.Module): + def __init__( + self, + hidden_size, + num_heads, + attn_class: Callable[..., nn.Module] = nn.MultiheadAttention, + mlp_ratio=4.0, + **block_kwargs + ): + """ + Self attention block + """ + super().__init__() + + self.norm1 = nn.LayerNorm(hidden_size) + self.norm2 = nn.LayerNorm(hidden_size) + + self.attn = attn_class(embed_dim=hidden_size, num_heads=num_heads, batch_first=True, **block_kwargs) + + mlp_hidden_dim = int(hidden_size * mlp_ratio) + + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) + + def forward(self, x, mask=None): + # Prepare the mask for PyTorch's attention (it expects a different format) + # attn_mask = mask if mask is not None else None + # Normalize before attention + x = self.norm1(x) + + # PyTorch's MultiheadAttention returns attn_output, attn_output_weights + # attn_output, _ = self.attn(x, x, x, attn_mask=attn_mask) + + attn_output, _ = self.attn(x, x, x) + + # Add & Norm + x = x + attn_output + x = x + self.mlp(self.norm2(x)) + return x + + +class CrossAttnBlock(nn.Module): + def __init__(self, hidden_size, context_dim, num_heads=1, mlp_ratio=4.0, **block_kwargs): + """ + Cross attention block + """ + super().__init__() + + self.norm1 = nn.LayerNorm(hidden_size) + self.norm_context = nn.LayerNorm(hidden_size) + self.norm2 = nn.LayerNorm(hidden_size) + + self.cross_attn = nn.MultiheadAttention( + embed_dim=hidden_size, num_heads=num_heads, batch_first=True, **block_kwargs + ) + + mlp_hidden_dim = int(hidden_size * mlp_ratio) + + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) + + def forward(self, x, context, mask=None): + # Normalize inputs + x = self.norm1(x) + context = self.norm_context(context) + + # Apply cross attention + # Note: nn.MultiheadAttention returns attn_output, attn_output_weights + attn_output, _ = self.cross_attn(x, context, context, attn_mask=mask) + + # Add & Norm + x = x + attn_output + x = x + self.mlp(self.norm2(x)) + return x diff --git a/src/model/encoder/vggt/heads/track_modules/utils.py b/src/model/encoder/vggt/heads/track_modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e620ff5b45abf67cc4e4e8372535ed3064c7f7bc --- /dev/null +++ b/src/model/encoder/vggt/heads/track_modules/utils.py @@ -0,0 +1,226 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from https://github.com/facebookresearch/vggsfm +# and https://github.com/facebookresearch/co-tracker/tree/main + + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Union + + +def get_2d_sincos_pos_embed(embed_dim: int, grid_size: Union[int, Tuple[int, int]], return_grid=False) -> torch.Tensor: + """ + This function initializes a grid and generates a 2D positional embedding using sine and cosine functions. + It is a wrapper of get_2d_sincos_pos_embed_from_grid. + Args: + - embed_dim: The embedding dimension. + - grid_size: The grid size. + Returns: + - pos_embed: The generated 2D positional embedding. + """ + if isinstance(grid_size, tuple): + grid_size_h, grid_size_w = grid_size + else: + grid_size_h = grid_size_w = grid_size + grid_h = torch.arange(grid_size_h, dtype=torch.float) + grid_w = torch.arange(grid_size_w, dtype=torch.float) + grid = torch.meshgrid(grid_w, grid_h, indexing="xy") + grid = torch.stack(grid, dim=0) + grid = grid.reshape([2, 1, grid_size_h, grid_size_w]) + pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) + if return_grid: + return ( + pos_embed.reshape(1, grid_size_h, grid_size_w, -1).permute(0, 3, 1, 2), + grid, + ) + return pos_embed.reshape(1, grid_size_h, grid_size_w, -1).permute(0, 3, 1, 2) + + +def get_2d_sincos_pos_embed_from_grid(embed_dim: int, grid: torch.Tensor) -> torch.Tensor: + """ + This function generates a 2D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - grid: The grid to generate the embedding from. + + Returns: + - emb: The generated 2D positional embedding. + """ + assert embed_dim % 2 == 0 + + # use half of dimensions to encode grid_h + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) + + emb = torch.cat([emb_h, emb_w], dim=2) # (H*W, D) + return emb + + +def get_1d_sincos_pos_embed_from_grid(embed_dim: int, pos: torch.Tensor) -> torch.Tensor: + """ + This function generates a 1D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - pos: The position to generate the embedding from. + + Returns: + - emb: The generated 1D positional embedding. + """ + assert embed_dim % 2 == 0 + omega = torch.arange(embed_dim // 2, dtype=torch.double) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb[None].float() + + +def get_2d_embedding(xy: torch.Tensor, C: int, cat_coords: bool = True) -> torch.Tensor: + """ + This function generates a 2D positional embedding from given coordinates using sine and cosine functions. + + Args: + - xy: The coordinates to generate the embedding from. + - C: The size of the embedding. + - cat_coords: A flag to indicate whether to concatenate the original coordinates to the embedding. + + Returns: + - pe: The generated 2D positional embedding. + """ + B, N, D = xy.shape + assert D == 2 + + x = xy[:, :, 0:1] + y = xy[:, :, 1:2] + div_term = (torch.arange(0, C, 2, device=xy.device, dtype=torch.float32) * (1000.0 / C)).reshape(1, 1, int(C / 2)) + + pe_x = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32) + pe_y = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32) + + pe_x[:, :, 0::2] = torch.sin(x * div_term) + pe_x[:, :, 1::2] = torch.cos(x * div_term) + + pe_y[:, :, 0::2] = torch.sin(y * div_term) + pe_y[:, :, 1::2] = torch.cos(y * div_term) + + pe = torch.cat([pe_x, pe_y], dim=2) # (B, N, C*3) + if cat_coords: + pe = torch.cat([xy, pe], dim=2) # (B, N, C*3+3) + return pe + + +def bilinear_sampler(input, coords, align_corners=True, padding_mode="border"): + r"""Sample a tensor using bilinear interpolation + + `bilinear_sampler(input, coords)` samples a tensor :attr:`input` at + coordinates :attr:`coords` using bilinear interpolation. It is the same + as `torch.nn.functional.grid_sample()` but with a different coordinate + convention. + + The input tensor is assumed to be of shape :math:`(B, C, H, W)`, where + :math:`B` is the batch size, :math:`C` is the number of channels, + :math:`H` is the height of the image, and :math:`W` is the width of the + image. The tensor :attr:`coords` of shape :math:`(B, H_o, W_o, 2)` is + interpreted as an array of 2D point coordinates :math:`(x_i,y_i)`. + + Alternatively, the input tensor can be of size :math:`(B, C, T, H, W)`, + in which case sample points are triplets :math:`(t_i,x_i,y_i)`. Note + that in this case the order of the components is slightly different + from `grid_sample()`, which would expect :math:`(x_i,y_i,t_i)`. + + If `align_corners` is `True`, the coordinate :math:`x` is assumed to be + in the range :math:`[0,W-1]`, with 0 corresponding to the center of the + left-most image pixel :math:`W-1` to the center of the right-most + pixel. + + If `align_corners` is `False`, the coordinate :math:`x` is assumed to + be in the range :math:`[0,W]`, with 0 corresponding to the left edge of + the left-most pixel :math:`W` to the right edge of the right-most + pixel. + + Similar conventions apply to the :math:`y` for the range + :math:`[0,H-1]` and :math:`[0,H]` and to :math:`t` for the range + :math:`[0,T-1]` and :math:`[0,T]`. + + Args: + input (Tensor): batch of input images. + coords (Tensor): batch of coordinates. + align_corners (bool, optional): Coordinate convention. Defaults to `True`. + padding_mode (str, optional): Padding mode. Defaults to `"border"`. + + Returns: + Tensor: sampled points. + """ + coords = coords.detach().clone() + ############################################################ + # IMPORTANT: + coords = coords.to(input.device).to(input.dtype) + ############################################################ + + sizes = input.shape[2:] + + assert len(sizes) in [2, 3] + + if len(sizes) == 3: + # t x y -> x y t to match dimensions T H W in grid_sample + coords = coords[..., [1, 2, 0]] + + if align_corners: + scale = torch.tensor( + [2 / max(size - 1, 1) for size in reversed(sizes)], device=coords.device, dtype=coords.dtype + ) + else: + scale = torch.tensor([2 / size for size in reversed(sizes)], device=coords.device, dtype=coords.dtype) + + coords.mul_(scale) # coords = coords * scale + coords.sub_(1) # coords = coords - 1 + + return F.grid_sample(input, coords, align_corners=align_corners, padding_mode=padding_mode) + + +def sample_features4d(input, coords): + r"""Sample spatial features + + `sample_features4d(input, coords)` samples the spatial features + :attr:`input` represented by a 4D tensor :math:`(B, C, H, W)`. + + The field is sampled at coordinates :attr:`coords` using bilinear + interpolation. :attr:`coords` is assumed to be of shape :math:`(B, R, + 2)`, where each sample has the format :math:`(x_i, y_i)`. This uses the + same convention as :func:`bilinear_sampler` with `align_corners=True`. + + The output tensor has one feature per point, and has shape :math:`(B, + R, C)`. + + Args: + input (Tensor): spatial features. + coords (Tensor): points. + + Returns: + Tensor: sampled features. + """ + + B, _, _, _ = input.shape + + # B R 2 -> B R 1 2 + coords = coords.unsqueeze(2) + + # B C R 1 + feats = bilinear_sampler(input, coords) + + return feats.permute(0, 2, 1, 3).view(B, -1, feats.shape[1] * feats.shape[3]) # B C R 1 -> B R C diff --git a/src/model/encoder/vggt/heads/utils.py b/src/model/encoder/vggt/heads/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d470561153cae577e15ec474fa2de573e7337608 --- /dev/null +++ b/src/model/encoder/vggt/heads/utils.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + + +def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor: + """ + Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC) + + Args: + pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates + embed_dim: Output channel dimension for embeddings + + Returns: + Tensor of shape (H, W, embed_dim) with positional embeddings + """ + H, W, grid_dim = pos_grid.shape + assert grid_dim == 2 + pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2) + + # Process x and y coordinates separately + emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] + emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2] + + # Combine and reshape + emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D] + + return emb.view(H, W, embed_dim) # [H, W, D] + + +def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: + """ + This function generates a 1D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - pos: The position to generate the embedding from. + + Returns: + - emb: The generated 1D positional embedding. + """ + assert embed_dim % 2 == 0 + omega = torch.arange(embed_dim // 2, dtype=torch.double, device=pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / omega_0**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb.float() + + +# Inspired by https://github.com/microsoft/moge + + +def create_uv_grid( + width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None +) -> torch.Tensor: + """ + Create a normalized UV grid of shape (width, height, 2). + + The grid spans horizontally and vertically according to an aspect ratio, + ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right + corner is at (x_span, y_span), normalized by the diagonal of the plane. + + Args: + width (int): Number of points horizontally. + height (int): Number of points vertically. + aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. + dtype (torch.dtype, optional): Data type of the resulting tensor. + device (torch.device, optional): Device on which the tensor is created. + + Returns: + torch.Tensor: A (width, height, 2) tensor of UV coordinates. + """ + # Derive aspect ratio if not explicitly provided + if aspect_ratio is None: + aspect_ratio = float(width) / float(height) + + # Compute normalized spans for X and Y + diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 + span_x = aspect_ratio / diag_factor + span_y = 1.0 / diag_factor + + # Establish the linspace boundaries + left_x = -span_x * (width - 1) / width + right_x = span_x * (width - 1) / width + top_y = -span_y * (height - 1) / height + bottom_y = span_y * (height - 1) / height + + # Generate 1D coordinates + x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) + y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device) + + # Create 2D meshgrid (width x height) and stack into UV + uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") + uv_grid = torch.stack((uu, vv), dim=-1) + + return uv_grid diff --git a/src/model/encoder/vggt/layers/__init__.py b/src/model/encoder/vggt/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e59a83eb90512d763b03e4d38536b6ae07e87541 --- /dev/null +++ b/src/model/encoder/vggt/layers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .mlp import Mlp +from .patch_embed import PatchEmbed +from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused +from .block import NestedTensorBlock +from .attention import MemEffAttention diff --git a/src/model/encoder/vggt/layers/attention.py b/src/model/encoder/vggt/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..693387cd4bbbbd68b5d331ede798015b41048f9f --- /dev/null +++ b/src/model/encoder/vggt/layers/attention.py @@ -0,0 +1,98 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +import logging +import os +import warnings + +from torch import Tensor +from torch import nn +import torch.nn.functional as F + +XFORMERS_AVAILABLE = False + + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + norm_layer: nn.Module = nn.LayerNorm, + qk_norm: bool = False, + fused_attn: bool = True, # use F.scaled_dot_product_attention or not + rope=None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, "dim should be divisible by num_heads" + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + self.fused_attn = fused_attn + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + self.rope = rope + + def forward(self, x: Tensor, pos=None) -> Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if self.rope is not None: + q = self.rope(q, pos) + k = self.rope(k, pos) + + if self.fused_attn: + x = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.attn_drop.p if self.training else 0.0, + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class MemEffAttention(Attention): + def forward(self, x: Tensor, attn_bias=None, pos=None) -> Tensor: + assert pos is None + if not XFORMERS_AVAILABLE: + if attn_bias is not None: + raise AssertionError("xFormers is required for using nested tensors") + return super().forward(x) + + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + + q, k, v = unbind(qkv, 2) + + x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) + x = x.reshape([B, N, C]) + + x = self.proj(x) + x = self.proj_drop(x) + return x diff --git a/src/model/encoder/vggt/layers/block.py b/src/model/encoder/vggt/layers/block.py new file mode 100644 index 0000000000000000000000000000000000000000..58c7428bab5042319e0ad1ef535dfdaafc962da2 --- /dev/null +++ b/src/model/encoder/vggt/layers/block.py @@ -0,0 +1,259 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +import logging +import os +from typing import Callable, List, Any, Tuple, Dict +import warnings + +import torch +from torch import nn, Tensor + +from .attention import Attention +from .drop_path import DropPath +from .layer_scale import LayerScale +from .mlp import Mlp + + +XFORMERS_AVAILABLE = False + + +class Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = Attention, + ffn_layer: Callable[..., nn.Module] = Mlp, + qk_norm: bool = False, + fused_attn: bool = True, # use F.scaled_dot_product_attention or not + rope=None, + ) -> None: + super().__init__() + + self.norm1 = norm_layer(dim) + + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + qk_norm=qk_norm, + fused_attn=fused_attn, + rope=rope, + ) + + self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + ) + self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.sample_drop_ratio = drop_path + + def forward(self, x: Tensor, pos=None) -> Tensor: + def attn_residual_func(x: Tensor, pos=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), pos=pos)) + + def ffn_residual_func(x: Tensor) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + if self.training and self.sample_drop_ratio > 0.1: + # the overhead is compensated only for a drop path rate larger than 0.1 + x = drop_add_residual_stochastic_depth( + x, + pos=pos, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + x = drop_add_residual_stochastic_depth( + x, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + ) + elif self.training and self.sample_drop_ratio > 0.0: + x = x + self.drop_path1(attn_residual_func(x, pos=pos)) + x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 + else: + x = x + attn_residual_func(x, pos=pos) + x = x + ffn_residual_func(x) + return x + + +def drop_add_residual_stochastic_depth( + x: Tensor, + residual_func: Callable[[Tensor], Tensor], + sample_drop_ratio: float = 0.0, + pos=None, +) -> Tensor: + # 1) extract subset using permutation + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + x_subset = x[brange] + + # 2) apply residual_func to get residual + if pos is not None: + # if necessary, apply rope to the subset + pos = pos[brange] + residual = residual_func(x_subset, pos=pos) + else: + residual = residual_func(x_subset) + + x_flat = x.flatten(1) + residual = residual.flatten(1) + + residual_scale_factor = b / sample_subset_size + + # 3) add the residual + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + return x_plus_residual.view_as(x) + + +def get_branges_scales(x, sample_drop_ratio=0.0): + b, n, d = x.shape + sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) + brange = (torch.randperm(b, device=x.device))[:sample_subset_size] + residual_scale_factor = b / sample_subset_size + return brange, residual_scale_factor + + +def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): + if scaling_vector is None: + x_flat = x.flatten(1) + residual = residual.flatten(1) + x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) + else: + x_plus_residual = scaled_index_add( + x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor + ) + return x_plus_residual + + +attn_bias_cache: Dict[Tuple, Any] = {} + + +def get_attn_bias_and_cat(x_list, branges=None): + """ + this will perform the index select, cat the tensors, and provide the attn_bias from cache + """ + batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] + all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) + if all_shapes not in attn_bias_cache.keys(): + seqlens = [] + for b, x in zip(batch_sizes, x_list): + for _ in range(b): + seqlens.append(x.shape[1]) + attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) + attn_bias._batch_sizes = batch_sizes + attn_bias_cache[all_shapes] = attn_bias + + if branges is not None: + cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) + else: + tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) + cat_tensors = torch.cat(tensors_bs1, dim=1) + + return attn_bias_cache[all_shapes], cat_tensors + + +def drop_add_residual_stochastic_depth_list( + x_list: List[Tensor], + residual_func: Callable[[Tensor, Any], Tensor], + sample_drop_ratio: float = 0.0, + scaling_vector=None, +) -> Tensor: + # 1) generate random set of indices for dropping samples in the batch + branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list] + branges = [s[0] for s in branges_scales] + residual_scale_factors = [s[1] for s in branges_scales] + + # 2) get attention bias and index+concat the tensors + attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges) + + # 3) apply residual_func to get residual, and split the result + residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore + + outputs = [] + for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors): + outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x)) + return outputs + + +class NestedTensorBlock(Block): + def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: + """ + x_list contains a list of tensors to nest together and run + """ + assert isinstance(self.attn, MemEffAttention) + + if self.training and self.sample_drop_ratio > 0.0: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.attn(self.norm1(x), attn_bias=attn_bias) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.mlp(self.norm2(x)) + + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=attn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, + ) + x_list = drop_add_residual_stochastic_depth_list( + x_list, + residual_func=ffn_residual_func, + sample_drop_ratio=self.sample_drop_ratio, + scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, + ) + return x_list + else: + + def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias)) + + def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: + return self.ls2(self.mlp(self.norm2(x))) + + attn_bias, x = get_attn_bias_and_cat(x_list) + x = x + attn_residual_func(x, attn_bias=attn_bias) + x = x + ffn_residual_func(x) + return attn_bias.split(x) + + def forward(self, x_or_x_list): + if isinstance(x_or_x_list, Tensor): + return super().forward(x_or_x_list) + elif isinstance(x_or_x_list, list): + if not XFORMERS_AVAILABLE: + raise AssertionError("xFormers is required for using nested tensors") + return self.forward_nested(x_or_x_list) + else: + raise AssertionError diff --git a/src/model/encoder/vggt/layers/drop_path.py b/src/model/encoder/vggt/layers/drop_path.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb1487b0eed4cb14dc0d5d1ee57a2acc78de34a --- /dev/null +++ b/src/model/encoder/vggt/layers/drop_path.py @@ -0,0 +1,34 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py + + +from torch import nn + + +def drop_path(x, drop_prob: float = 0.0, training: bool = False): + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + output = x * random_tensor + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) diff --git a/src/model/encoder/vggt/layers/layer_scale.py b/src/model/encoder/vggt/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..5468ee2dce0a9446c028791de5cff1ff068a4fe5 --- /dev/null +++ b/src/model/encoder/vggt/layers/layer_scale.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110 + +from typing import Union + +import torch +from torch import Tensor +from torch import nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/src/model/encoder/vggt/layers/mlp.py b/src/model/encoder/vggt/layers/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..0965768a9aef04ac6b81322f4dd60cf035159e91 --- /dev/null +++ b/src/model/encoder/vggt/layers/mlp.py @@ -0,0 +1,40 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py + + +from typing import Callable, Optional + +from torch import Tensor, nn + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x diff --git a/src/model/encoder/vggt/layers/patch_embed.py b/src/model/encoder/vggt/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3aaf46c523ab1ae27430419187bbad11e302ab --- /dev/null +++ b/src/model/encoder/vggt/layers/patch_embed.py @@ -0,0 +1,88 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py + +from typing import Callable, Optional, Tuple, Union + +from torch import Tensor +import torch.nn as nn + + +def make_2tuple(x): + if isinstance(x, tuple): + assert len(x) == 2 + return x + + assert isinstance(x, int) + return (x, x) + + +class PatchEmbed(nn.Module): + """ + 2D image to patch embedding: (B,C,H,W) -> (B,N,D) + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[Callable] = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + patch_H, patch_W = self.patch_size + + assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" + assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}" + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops diff --git a/src/model/encoder/vggt/layers/rope.py b/src/model/encoder/vggt/layers/rope.py new file mode 100644 index 0000000000000000000000000000000000000000..107ff7a2267e936bc01c4dbd576e1da4f038f904 --- /dev/null +++ b/src/model/encoder/vggt/layers/rope.py @@ -0,0 +1,188 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + + +# Implementation of 2D Rotary Position Embeddings (RoPE). + +# This module provides a clean implementation of 2D Rotary Position Embeddings, +# which extends the original RoPE concept to handle 2D spatial positions. + +# Inspired by: +# https://github.com/meta-llama/codellama/blob/main/llama/model.py +# https://github.com/naver-ai/rope-vit + + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Dict, Tuple + + +class PositionGetter: + """Generates and caches 2D spatial positions for patches in a grid. + + This class efficiently manages the generation of spatial coordinates for patches + in a 2D grid, caching results to avoid redundant computations. + + Attributes: + position_cache: Dictionary storing precomputed position tensors for different + grid dimensions. + """ + + def __init__(self): + """Initializes the position generator with an empty cache.""" + self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {} + + def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor: + """Generates spatial positions for a batch of patches. + + Args: + batch_size: Number of samples in the batch. + height: Height of the grid in patches. + width: Width of the grid in patches. + device: Target device for the position tensor. + + Returns: + Tensor of shape (batch_size, height*width, 2) containing y,x coordinates + for each position in the grid, repeated for each batch item. + """ + if (height, width) not in self.position_cache: + y_coords = torch.arange(height, device=device) + x_coords = torch.arange(width, device=device) + positions = torch.cartesian_prod(y_coords, x_coords) + self.position_cache[height, width] = positions + + cached_positions = self.position_cache[height, width] + return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone() + + +class RotaryPositionEmbedding2D(nn.Module): + """2D Rotary Position Embedding implementation. + + This module applies rotary position embeddings to input tokens based on their + 2D spatial positions. It handles the position-dependent rotation of features + separately for vertical and horizontal dimensions. + + Args: + frequency: Base frequency for the position embeddings. Default: 100.0 + scaling_factor: Scaling factor for frequency computation. Default: 1.0 + + Attributes: + base_frequency: Base frequency for computing position embeddings. + scaling_factor: Factor to scale the computed frequencies. + frequency_cache: Cache for storing precomputed frequency components. + """ + + def __init__(self, frequency: float = 100.0, scaling_factor: float = 1.0): + """Initializes the 2D RoPE module.""" + super().__init__() + self.base_frequency = frequency + self.scaling_factor = scaling_factor + self.frequency_cache: Dict[Tuple, Tuple[torch.Tensor, torch.Tensor]] = {} + + def _compute_frequency_components( + self, dim: int, seq_len: int, device: torch.device, dtype: torch.dtype + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Computes frequency components for rotary embeddings. + + Args: + dim: Feature dimension (must be even). + seq_len: Maximum sequence length. + device: Target device for computations. + dtype: Data type for the computed tensors. + + Returns: + Tuple of (cosine, sine) tensors for frequency components. + """ + cache_key = (dim, seq_len, device, dtype) + if cache_key not in self.frequency_cache: + # Compute frequency bands + exponents = torch.arange(0, dim, 2, device=device).float() / dim + inv_freq = 1.0 / (self.base_frequency**exponents) + + # Generate position-dependent frequencies + positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + angles = torch.einsum("i,j->ij", positions, inv_freq) + + # Compute and cache frequency components + angles = angles.to(dtype) + angles = torch.cat((angles, angles), dim=-1) + cos_components = angles.cos().to(dtype) + sin_components = angles.sin().to(dtype) + self.frequency_cache[cache_key] = (cos_components, sin_components) + + return self.frequency_cache[cache_key] + + @staticmethod + def _rotate_features(x: torch.Tensor) -> torch.Tensor: + """Performs feature rotation by splitting and recombining feature dimensions. + + Args: + x: Input tensor to rotate. + + Returns: + Rotated feature tensor. + """ + feature_dim = x.shape[-1] + x1, x2 = x[..., : feature_dim // 2], x[..., feature_dim // 2 :] + return torch.cat((-x2, x1), dim=-1) + + def _apply_1d_rope( + self, tokens: torch.Tensor, positions: torch.Tensor, cos_comp: torch.Tensor, sin_comp: torch.Tensor + ) -> torch.Tensor: + """Applies 1D rotary position embeddings along one dimension. + + Args: + tokens: Input token features. + positions: Position indices. + cos_comp: Cosine components for rotation. + sin_comp: Sine components for rotation. + + Returns: + Tokens with applied rotary position embeddings. + """ + # Embed positions with frequency components + cos = F.embedding(positions, cos_comp)[:, None, :, :] + sin = F.embedding(positions, sin_comp)[:, None, :, :] + + # Apply rotation + return (tokens * cos) + (self._rotate_features(tokens) * sin) + + def forward(self, tokens: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: + """Applies 2D rotary position embeddings to input tokens. + + Args: + tokens: Input tensor of shape (batch_size, n_heads, n_tokens, dim). + The feature dimension (dim) must be divisible by 4. + positions: Position tensor of shape (batch_size, n_tokens, 2) containing + the y and x coordinates for each token. + + Returns: + Tensor of same shape as input with applied 2D rotary position embeddings. + + Raises: + AssertionError: If input dimensions are invalid or positions are malformed. + """ + # Validate inputs + assert tokens.size(-1) % 2 == 0, "Feature dimension must be even" + assert positions.ndim == 3 and positions.shape[-1] == 2, "Positions must have shape (batch_size, n_tokens, 2)" + + # Compute feature dimension for each spatial direction + feature_dim = tokens.size(-1) // 2 + + # Get frequency components + max_position = int(positions.max()) + 1 + cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype) + + # Split features for vertical and horizontal processing + vertical_features, horizontal_features = tokens.chunk(2, dim=-1) + + # Apply RoPE separately for each dimension + vertical_features = self._apply_1d_rope(vertical_features, positions[..., 0], cos_comp, sin_comp) + horizontal_features = self._apply_1d_rope(horizontal_features, positions[..., 1], cos_comp, sin_comp) + + # Combine processed features + return torch.cat((vertical_features, horizontal_features), dim=-1) diff --git a/src/model/encoder/vggt/layers/swiglu_ffn.py b/src/model/encoder/vggt/layers/swiglu_ffn.py new file mode 100644 index 0000000000000000000000000000000000000000..90ba0a1b7104b0feb4595043453205f13448303b --- /dev/null +++ b/src/model/encoder/vggt/layers/swiglu_ffn.py @@ -0,0 +1,72 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +import os +from typing import Callable, Optional +import warnings + +from torch import Tensor, nn +import torch.nn.functional as F + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x12 = self.w12(x) + x1, x2 = x12.chunk(2, dim=-1) + hidden = F.silu(x1) * x2 + return self.w3(hidden) + + +XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None +# try: +# if XFORMERS_ENABLED: +# from xformers.ops import SwiGLU + +# XFORMERS_AVAILABLE = True +# warnings.warn("xFormers is available (SwiGLU)") +# else: +# warnings.warn("xFormers is disabled (SwiGLU)") +# raise ImportError +# except ImportError: +SwiGLU = SwiGLUFFN +XFORMERS_AVAILABLE = False + +# warnings.warn("xFormers is not available (SwiGLU)") + + +class SwiGLUFFNFused(SwiGLU): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = None, + drop: float = 0.0, + bias: bool = True, + ) -> None: + out_features = out_features or in_features + hidden_features = hidden_features or in_features + hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 + super().__init__( + in_features=in_features, + hidden_features=hidden_features, + out_features=out_features, + bias=bias, + ) diff --git a/src/model/encoder/vggt/layers/vision_transformer.py b/src/model/encoder/vggt/layers/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..793aa6cee0edd7610a700dd1cf52f1cba9bcaff1 --- /dev/null +++ b/src/model/encoder/vggt/layers/vision_transformer.py @@ -0,0 +1,408 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +# References: +# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py +# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py + +from functools import partial +import math +import logging +from typing import Sequence, Tuple, Union, Callable + +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint +from torch.nn.init import trunc_normal_ +from . import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block + +logger = logging.getLogger("dinov2") + + +def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module: + if not depth_first and include_root: + fn(module=module, name=name) + for child_name, child_module in module.named_children(): + child_name = ".".join((name, child_name)) if name else child_name + named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True) + if depth_first and include_root: + fn(module=module, name=name) + return module + + +class BlockChunk(nn.ModuleList): + def forward(self, x): + for b in self: + x = b(x) + return x + + +class DinoVisionTransformer(nn.Module): + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + ffn_bias=True, + proj_bias=True, + drop_path_rate=0.0, + drop_path_uniform=False, + init_values=None, # for layerscale: None or 0 => no layerscale + embed_layer=PatchEmbed, + act_layer=nn.GELU, + block_fn=Block, + ffn_layer="mlp", + block_chunks=1, + num_register_tokens=0, + interpolate_antialias=False, + interpolate_offset=0.1, + qk_norm=False, + ): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + proj_bias (bool): enable bias for proj in attn if True + ffn_bias (bool): enable bias for ffn if True + drop_path_rate (float): stochastic depth rate + drop_path_uniform (bool): apply uniform drop rate across blocks + weight_init (str): weight init scheme + init_values (float): layer-scale init values + embed_layer (nn.Module): patch embedding layer + act_layer (nn.Module): MLP activation layer + block_fn (nn.Module): transformer block class + ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" + block_chunks: (int) split block sequence into block_chunks units for FSDP wrap + num_register_tokens: (int) number of extra cls tokens (so-called "registers") + interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings + interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings + """ + super().__init__() + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + # tricky but makes it work + self.use_checkpoint = True + self.use_reentrant = False + # + + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + self.num_tokens = 1 + self.n_blocks = depth + self.num_heads = num_heads + self.patch_size = patch_size + self.num_register_tokens = num_register_tokens + self.interpolate_antialias = interpolate_antialias + self.interpolate_offset = interpolate_offset + + self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) + assert num_register_tokens >= 0 + self.register_tokens = ( + nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None + ) + + if drop_path_uniform is True: + dpr = [drop_path_rate] * depth + else: + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + if ffn_layer == "mlp": + logger.info("using MLP layer as FFN") + ffn_layer = Mlp + elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": + logger.info("using SwiGLU layer as FFN") + ffn_layer = SwiGLUFFNFused + elif ffn_layer == "identity": + logger.info("using Identity layer as FFN") + + def f(*args, **kwargs): + return nn.Identity() + + ffn_layer = f + else: + raise NotImplementedError + + blocks_list = [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + drop_path=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + ffn_layer=ffn_layer, + init_values=init_values, + qk_norm=qk_norm, + ) + for i in range(depth) + ] + if block_chunks > 0: + self.chunked_blocks = True + chunked_blocks = [] + chunksize = depth // block_chunks + for i in range(0, depth, chunksize): + # this is to keep the block index consistent if we chunk the block list + chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) + self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) + else: + self.chunked_blocks = False + self.blocks = nn.ModuleList(blocks_list) + + self.norm = norm_layer(embed_dim) + self.head = nn.Identity() + + self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) + + self.init_weights() + + def init_weights(self): + trunc_normal_(self.pos_embed, std=0.02) + nn.init.normal_(self.cls_token, std=1e-6) + if self.register_tokens is not None: + nn.init.normal_(self.register_tokens, std=1e-6) + named_apply(init_weights_vit_timm, self) + + def interpolate_pos_encoding(self, x, w, h): + previous_dtype = x.dtype + npatch = x.shape[1] - 1 + N = self.pos_embed.shape[1] - 1 + if npatch == N and w == h: + return self.pos_embed + pos_embed = self.pos_embed.float() + class_pos_embed = pos_embed[:, 0] + patch_pos_embed = pos_embed[:, 1:] + dim = x.shape[-1] + w0 = w // self.patch_size + h0 = h // self.patch_size + M = int(math.sqrt(N)) # Recover the number of patches in each dimension + assert N == M * M + kwargs = {} + if self.interpolate_offset: + # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8 + # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors + sx = float(w0 + self.interpolate_offset) / M + sy = float(h0 + self.interpolate_offset) / M + kwargs["scale_factor"] = (sx, sy) + else: + # Simply specify an output size instead of a scale factor + kwargs["size"] = (w0, h0) + patch_pos_embed = nn.functional.interpolate( + patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2), + mode="bicubic", + antialias=self.interpolate_antialias, + **kwargs, + ) + assert (w0, h0) == patch_pos_embed.shape[-2:] + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype) + + def prepare_tokens_with_masks(self, x, masks=None): + B, nc, w, h = x.shape + x = self.patch_embed(x) + if masks is not None: + x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x) + + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + x = x + self.interpolate_pos_encoding(x, w, h) + + if self.register_tokens is not None: + x = torch.cat( + ( + x[:, :1], + self.register_tokens.expand(x.shape[0], -1, -1), + x[:, 1:], + ), + dim=1, + ) + + return x + + def forward_features_list(self, x_list, masks_list): + x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)] + + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint(blk, x, use_reentrant=self.use_reentrant) + else: + x = blk(x) + + all_x = x + output = [] + for x, masks in zip(all_x, masks_list): + x_norm = self.norm(x) + output.append( + { + "x_norm_clstoken": x_norm[:, 0], + "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], + "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], + "x_prenorm": x, + "masks": masks, + } + ) + return output + + def forward_features(self, x, masks=None): + if isinstance(x, list): + return self.forward_features_list(x, masks) + + x = self.prepare_tokens_with_masks(x, masks) + + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint(blk, x, use_reentrant=self.use_reentrant) + else: + x = blk(x) + + x_norm = self.norm(x) + return { + "x_norm_clstoken": x_norm[:, 0], + "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], + "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], + "x_prenorm": x, + "masks": masks, + } + + def _get_intermediate_layers_not_chunked(self, x, n=1): + x = self.prepare_tokens_with_masks(x) + # If n is an int, take the n last blocks. If it's a list, take them + output, total_block_len = [], len(self.blocks) + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for i, blk in enumerate(self.blocks): + x = blk(x) + if i in blocks_to_take: + output.append(x) + assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" + return output + + def _get_intermediate_layers_chunked(self, x, n=1): + x = self.prepare_tokens_with_masks(x) + output, i, total_block_len = [], 0, len(self.blocks[-1]) + # If n is an int, take the n last blocks. If it's a list, take them + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for block_chunk in self.blocks: + for blk in block_chunk[i:]: # Passing the nn.Identity() + x = blk(x) + if i in blocks_to_take: + output.append(x) + i += 1 + assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" + return output + + def get_intermediate_layers( + self, + x: torch.Tensor, + n: Union[int, Sequence] = 1, # Layers or n last layers to take + reshape: bool = False, + return_class_token: bool = False, + norm=True, + ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: + if self.chunked_blocks: + outputs = self._get_intermediate_layers_chunked(x, n) + else: + outputs = self._get_intermediate_layers_not_chunked(x, n) + if norm: + outputs = [self.norm(out) for out in outputs] + class_tokens = [out[:, 0] for out in outputs] + outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs] + if reshape: + B, _, w, h = x.shape + outputs = [ + out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() + for out in outputs + ] + if return_class_token: + return tuple(zip(outputs, class_tokens)) + return tuple(outputs) + + def forward(self, *args, is_training=True, **kwargs): + ret = self.forward_features(*args, **kwargs) + if is_training: + return ret + else: + return self.head(ret["x_norm_clstoken"]) + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility)""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + +def vit_small(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_base(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_large(patch_size=16, num_register_tokens=0, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model + + +def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): + """ + Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 + """ + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1536, + depth=40, + num_heads=24, + mlp_ratio=4, + block_fn=partial(Block, attn_class=MemEffAttention), + num_register_tokens=num_register_tokens, + **kwargs, + ) + return model diff --git a/src/model/encoder/vggt/models/aggregator.py b/src/model/encoder/vggt/models/aggregator.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c0c44eb1cae5457c30abda3f456bfa83d56b59 --- /dev/null +++ b/src/model/encoder/vggt/models/aggregator.py @@ -0,0 +1,365 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, Tuple, Union, List, Dict, Any + +from src.model.encoder.vggt.layers import PatchEmbed +from src.model.encoder.vggt.layers.block import Block +from src.model.encoder.vggt.layers.rope import RotaryPositionEmbedding2D, PositionGetter +from src.model.encoder.vggt.layers.vision_transformer import vit_small, vit_base, vit_large, vit_giant2 + +logger = logging.getLogger(__name__) + +_RESNET_MEAN = [0.485, 0.456, 0.406] +_RESNET_STD = [0.229, 0.224, 0.225] + + +class Aggregator(nn.Module): + """ + The Aggregator applies alternating-attention over input frames, + as described in VGGT: Visual Geometry Grounded Transformer. + + + Args: + img_size (int): Image size in pixels. + patch_size (int): Size of each patch for PatchEmbed. + embed_dim (int): Dimension of the token embeddings. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + mlp_ratio (float): Ratio of MLP hidden dim to embedding dim. + num_register_tokens (int): Number of register tokens. + block_fn (nn.Module): The block type used for attention (Block by default). + qkv_bias (bool): Whether to include bias in QKV projections. + proj_bias (bool): Whether to include bias in the output projection. + ffn_bias (bool): Whether to include bias in MLP layers. + patch_embed (str): Type of patch embed. e.g., "conv" or "dinov2_vitl14_reg". + aa_order (list[str]): The order of alternating attention, e.g. ["frame", "global"]. + aa_block_size (int): How many blocks to group under each attention type before switching. If not necessary, set to 1. + qk_norm (bool): Whether to apply QK normalization. + rope_freq (int): Base frequency for rotary embedding. -1 to disable. + init_values (float): Init scale for layer scale. + """ + + def __init__( + self, + img_size=518, + patch_size=14, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4.0, + num_register_tokens=4, + block_fn=Block, + qkv_bias=True, + proj_bias=True, + ffn_bias=True, + patch_embed="dinov2_vitl14_reg", + aa_order=["frame", "global"], + aa_block_size=1, + qk_norm=True, + rope_freq=100, + init_values=0.01, + ): + super().__init__() + self.use_checkpoint = True + self.__build_patch_embed__(patch_embed, img_size, patch_size, num_register_tokens, embed_dim=embed_dim) + + # Initialize rotary position embedding if frequency > 0 + self.rope = RotaryPositionEmbedding2D(frequency=rope_freq) if rope_freq > 0 else None + self.position_getter = PositionGetter() if self.rope is not None else None + + self.frame_blocks = nn.ModuleList( + [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + init_values=init_values, + qk_norm=qk_norm, + rope=self.rope, + ) + for _ in range(depth) + ] + ) + + self.global_blocks = nn.ModuleList( + [ + block_fn( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + init_values=init_values, + qk_norm=qk_norm, + rope=self.rope, + ) + for _ in range(depth) + ] + ) + + self.depth = depth + self.aa_order = aa_order + self.patch_size = patch_size + self.aa_block_size = aa_block_size + + # Validate that depth is divisible by aa_block_size + if self.depth % self.aa_block_size != 0: + raise ValueError(f"depth ({depth}) must be divisible by aa_block_size ({aa_block_size})") + + self.aa_block_num = self.depth // self.aa_block_size + + # Note: We have two camera tokens, one for the first frame and one for the rest + # The same applies for register tokens + self.camera_token = nn.Parameter(torch.randn(1, 2, 1, embed_dim)) + self.register_token = nn.Parameter(torch.randn(1, 2, num_register_tokens, embed_dim)) + + # The patch tokens start after the camera and register tokens + self.patch_start_idx = 1 + num_register_tokens + + # Initialize parameters with small values + nn.init.normal_(self.camera_token, std=1e-6) + nn.init.normal_(self.register_token, std=1e-6) + + # Register normalization constants as buffers + for name, value in ( + ("_resnet_mean", _RESNET_MEAN), + ("_resnet_std", _RESNET_STD), + ): + self.register_buffer( + name, + torch.FloatTensor(value).view(1, 1, 3, 1, 1), + persistent=False, + ) + + def __build_patch_embed__( + self, + patch_embed, + img_size, + patch_size, + num_register_tokens, + interpolate_antialias=True, + interpolate_offset=0.0, + block_chunks=0, + init_values=1.0, + embed_dim=1024, + ): + """ + Build the patch embed layer. If 'conv', we use a + simple PatchEmbed conv layer. Otherwise, we use a vision transformer. + """ + + if "conv" in patch_embed: + self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=3, embed_dim=embed_dim) + else: + vit_models = { + "dinov2_vitl14_reg": vit_large, + "dinov2_vitb14_reg": vit_base, + "dinov2_vits14_reg": vit_small, + "dinov2_vitg2_reg": vit_giant2, + } + + self.patch_embed = vit_models[patch_embed]( + img_size=img_size, + patch_size=patch_size, + num_register_tokens=num_register_tokens, + interpolate_antialias=interpolate_antialias, + interpolate_offset=interpolate_offset, + block_chunks=block_chunks, + init_values=init_values, + ) + + # Disable gradient updates for mask token + if hasattr(self.patch_embed, "mask_token"): + self.patch_embed.mask_token.requires_grad_(False) + + def forward( + self, + images: torch.Tensor, + intermediate_layer_idx: Optional[List[int]] = None + ) -> Tuple[List[torch.Tensor], int]: + """ + Args: + images (torch.Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. + B: batch size, S: sequence length, 3: RGB channels, H: height, W: width + + Returns: + (list[torch.Tensor], int): + The list of outputs from the attention blocks, + and the patch_start_idx indicating where patch tokens begin. + """ + B, S, C_in, H, W = images.shape + + if C_in != 3: + raise ValueError(f"Expected 3 input channels, got {C_in}") + + # Normalize images and reshape for patch embed + images = (images - self._resnet_mean) / self._resnet_std + + # Reshape to [B*S, C, H, W] for patch embedding + images = images.view(B * S, C_in, H, W) + patch_tokens = self.patch_embed(images) + + if isinstance(patch_tokens, dict): + patch_tokens = patch_tokens["x_norm_patchtokens"] + + _, P, C = patch_tokens.shape + + # Expand camera and register tokens to match batch size and sequence length + camera_token = slice_expand_and_flatten(self.camera_token, B, S) + register_token = slice_expand_and_flatten(self.register_token, B, S) + + # Concatenate special tokens with patch tokens + tokens = torch.cat([camera_token, register_token, patch_tokens], dim=1) + + pos = None + if self.rope is not None: + pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=images.device) + + if self.patch_start_idx > 0: + # do not use position embedding for special tokens (camera and register tokens) + # so set pos to 0 for the special tokens + pos = pos + 1 + pos_special = torch.zeros(B * S, self.patch_start_idx, 2).to(images.device).to(pos.dtype) + pos = torch.cat([pos_special, pos], dim=1) + + # update P because we added special tokens + _, P, C = tokens.shape + + frame_idx = 0 + global_idx = 0 + output_list = [] + layer_idx = 0 + + # Convert intermediate_layer_idx to a set for O(1) lookup + if intermediate_layer_idx is not None: + required_layers = set(intermediate_layer_idx) + # Always include the last layer for camera_head + required_layers.add(self.depth - 1) + + for _ in range(self.aa_block_num): + for attn_type in self.aa_order: + if attn_type == "frame": + tokens, frame_idx, frame_intermediates = self._process_frame_attention( + tokens, B, S, P, C, frame_idx, pos=pos + ) + elif attn_type == "global": + tokens, global_idx, global_intermediates = self._process_global_attention( + tokens, B, S, P, C, global_idx, pos=pos + ) + else: + raise ValueError(f"Unknown attention type: {attn_type}") + + if intermediate_layer_idx is not None: + for i in range(len(frame_intermediates)): + current_layer = layer_idx + i + if current_layer in required_layers: + # concat frame and global intermediates, [B x S x P x 2C] + concat_inter = torch.cat([frame_intermediates[i], global_intermediates[i]], dim=-1) + output_list.append(concat_inter) + layer_idx += self.aa_block_size + + else: + for i in range(len(frame_intermediates)): + # concat frame and global intermediates, [B x S x P x 2C] + concat_inter = torch.cat([frame_intermediates[i], global_intermediates[i]], dim=-1) + output_list.append(concat_inter) + + del concat_inter + del frame_intermediates + del global_intermediates + return output_list, self.patch_start_idx + + def _process_frame_attention(self, tokens, B, S, P, C, frame_idx, pos=None): + """ + Process frame attention blocks. We keep tokens in shape (B*S, P, C). + """ + # If needed, reshape tokens or positions: + if tokens.shape != (B * S, P, C): + tokens = tokens.view(B, S, P, C).view(B * S, P, C) + + if pos is not None and pos.shape != (B * S, P, 2): + pos = pos.view(B, S, P, 2).view(B * S, P, 2) + + intermediates = [] + + # by default, self.aa_block_size=1, which processes one block at a time + for _ in range(self.aa_block_size): + if self.use_checkpoint: + tokens = torch.utils.checkpoint.checkpoint( + self.frame_blocks[frame_idx], + tokens, + pos, + use_reentrant=False, + ) + else: + tokens = self.frame_blocks[frame_idx](tokens, pos=pos) + frame_idx += 1 + intermediates.append(tokens.view(B, S, P, C)) + + return tokens, frame_idx, intermediates + + def _process_global_attention(self, tokens, B, S, P, C, global_idx, pos=None): + """ + Process global attention blocks. We keep tokens in shape (B, S*P, C). + """ + if tokens.shape != (B, S * P, C): + tokens = tokens.view(B, S, P, C).view(B, S * P, C) + + if pos is not None and pos.shape != (B, S * P, 2): + pos = pos.view(B, S, P, 2).view(B, S * P, 2) + + intermediates = [] + + # by default, self.aa_block_size=1, which processes one block at a time + for _ in range(self.aa_block_size): + if self.use_checkpoint: + tokens = torch.utils.checkpoint.checkpoint( + self.global_blocks[global_idx], + tokens, + pos, + use_reentrant=False, + ) + else: + tokens = self.global_blocks[global_idx](tokens, pos=pos) + global_idx += 1 + intermediates.append(tokens.view(B, S, P, C)) + + return tokens, global_idx, intermediates + + +def slice_expand_and_flatten(token_tensor, B, S): + """ + Processes specialized tokens with shape (1, 2, X, C) for multi-frame processing: + 1) Uses the first position (index=0) for the first frame only + 2) Uses the second position (index=1) for all remaining frames (S-1 frames) + 3) Expands both to match batch size B + 4) Concatenates to form (B, S, X, C) where each sequence has 1 first-position token + followed by (S-1) second-position tokens + 5) Flattens to (B*S, X, C) for processing + + Returns: + torch.Tensor: Processed tokens with shape (B*S, X, C) + """ + + # Slice out the "query" tokens => shape (1, 1, ...) + query = token_tensor[:, 0:1, ...].expand(B, 1, *token_tensor.shape[2:]) + # Slice out the "other" tokens => shape (1, S-1, ...) + others = token_tensor[:, 1:, ...].expand(B, S - 1, *token_tensor.shape[2:]) + # Concatenate => shape (B, S, ...) + combined = torch.cat([query, others], dim=1) + + # Finally flatten => shape (B*S, ...) + combined = combined.view(B * S, *combined.shape[2:]) + return combined diff --git a/src/model/encoder/vggt/models/vggt.py b/src/model/encoder/vggt/models/vggt.py new file mode 100644 index 0000000000000000000000000000000000000000..8f2c05fa157469c9b122cb8d64168b4a2b6c4f0b --- /dev/null +++ b/src/model/encoder/vggt/models/vggt.py @@ -0,0 +1,96 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from huggingface_hub import PyTorchModelHubMixin # used for model hub + +from src.model.encoder.vggt.models.aggregator import Aggregator +from src.model.encoder.vggt.heads.camera_head import CameraHead +from src.model.encoder.vggt.heads.dpt_head import DPTHead +from src.model.encoder.vggt.heads.track_head import TrackHead + + +class VGGT(nn.Module, PyTorchModelHubMixin): + def __init__(self, img_size=518, patch_size=14, embed_dim=1024): + super().__init__() + + self.aggregator = Aggregator(img_size=img_size, patch_size=patch_size, embed_dim=embed_dim) + self.camera_head = CameraHead(dim_in=2 * embed_dim) + self.point_head = DPTHead(dim_in=2 * embed_dim, output_dim=4, activation="inv_log", conf_activation="expp1") + self.depth_head = DPTHead(dim_in=2 * embed_dim, output_dim=2, activation="exp", conf_activation="expp1") + self.track_head = TrackHead(dim_in=2 * embed_dim, patch_size=patch_size) + + def forward( + self, + images: torch.Tensor, + query_points: torch.Tensor = None, + ): + """ + Forward pass of the VGGT model. + + Args: + images (torch.Tensor): Input images with shape [S, 3, H, W] or [B, S, 3, H, W], in range [0, 1]. + B: batch size, S: sequence length, 3: RGB channels, H: height, W: width + query_points (torch.Tensor, optional): Query points for tracking, in pixel coordinates. + Shape: [N, 2] or [B, N, 2], where N is the number of query points. + Default: None + + Returns: + dict: A dictionary containing the following predictions: + - pose_enc (torch.Tensor): Camera pose encoding with shape [B, S, 9] (from the last iteration) + - depth (torch.Tensor): Predicted depth maps with shape [B, S, H, W, 1] + - depth_conf (torch.Tensor): Confidence scores for depth predictions with shape [B, S, H, W] + - world_points (torch.Tensor): 3D world coordinates for each pixel with shape [B, S, H, W, 3] + - world_points_conf (torch.Tensor): Confidence scores for world points with shape [B, S, H, W] + - images (torch.Tensor): Original input images, preserved for visualization + + If query_points is provided, also includes: + - track (torch.Tensor): Point tracks with shape [B, S, N, 2] (from the last iteration), in pixel coordinates + - vis (torch.Tensor): Visibility scores for tracked points with shape [B, S, N] + - conf (torch.Tensor): Confidence scores for tracked points with shape [B, S, N] + """ + + # If without batch dimension, add it + if len(images.shape) == 4: + images = images.unsqueeze(0) + if query_points is not None and len(query_points.shape) == 2: + query_points = query_points.unsqueeze(0) + + aggregated_tokens_list, patch_start_idx = self.aggregator(images) + + predictions = {} + + with torch.cuda.amp.autocast(enabled=False): + if self.camera_head is not None: + pose_enc_list = self.camera_head(aggregated_tokens_list) + predictions["pose_enc"] = pose_enc_list[-1] # pose encoding of the last iteration + + if self.depth_head is not None: + depth, depth_conf = self.depth_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx + ) + predictions["depth"] = depth + predictions["depth_conf"] = depth_conf + + if self.point_head is not None: + pts3d, pts3d_conf = self.point_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx + ) + predictions["world_points"] = pts3d + predictions["world_points_conf"] = pts3d_conf + + if self.track_head is not None and query_points is not None: + track_list, vis, conf = self.track_head( + aggregated_tokens_list, images=images, patch_start_idx=patch_start_idx, query_points=query_points + ) + predictions["track"] = track_list[-1] # track of the last iteration + predictions["vis"] = vis + predictions["conf"] = conf + + predictions["images"] = images + + return predictions diff --git a/src/model/encoder/vggt/utils/geometry.py b/src/model/encoder/vggt/utils/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0f2e4e75dc5e4f0cb3180dcd66100da130bf70 --- /dev/null +++ b/src/model/encoder/vggt/utils/geometry.py @@ -0,0 +1,198 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import os +import torch + +def batchify_unproject_depth_map_to_point_map( + depth_map: torch.Tensor, extrinsics_cam: torch.Tensor, intrinsics_cam: torch.Tensor +) -> torch.Tensor: + """ + Unproject a batch of depth maps to 3D world coordinates. + + Args: + depth_map (torch.Tensor): Batch of depth maps of shape (B, V, H, W, 1) or (B, V, H, W) + extrinsics_cam (torch.Tensor): Batch of camera extrinsic matrices of shape (B, V, 3, 4) + intrinsics_cam (torch.Tensor): Batch of camera intrinsic matrices of shape (B, V, 3, 3) + + Returns: + torch.Tensor: Batch of 3D world coordinates of shape (S, H, W, 3) + """ + + # Handle both (S, H, W, 1) and (S, H, W) cases + if depth_map.dim() == 5: + depth_map = depth_map.squeeze(-1) # (S, H, W) + + # Generate batched camera coordinates + H, W = depth_map.shape[2:] + batch_size, num_views = depth_map.shape[0], depth_map.shape[1] + + # Intrinsic parameters (S, 3, 3) + intrinsics_cam, extrinsics_cam, depth_map = intrinsics_cam.flatten(0, 1), extrinsics_cam.flatten(0, 1), depth_map.flatten(0, 1) + fu = intrinsics_cam[:, 0, 0] # (S,) + fv = intrinsics_cam[:, 1, 1] # (S,) + cu = intrinsics_cam[:, 0, 2] # (S,) + cv = intrinsics_cam[:, 1, 2] # (S,) + + # Generate grid of pixel coordinates + u = torch.arange(W, device=depth_map.device)[None, None, :].expand(batch_size * num_views, H, W) # (S, H, W) + v = torch.arange(H, device=depth_map.device)[None, :, None].expand(batch_size * num_views, H, W) # (S, H, W) + + # Unproject to camera coordinates (S, H, W, 3) + x_cam = (u - cu[:, None, None]) * depth_map / fu[:, None, None] + y_cam = (v - cv[:, None, None]) * depth_map / fv[:, None, None] + z_cam = depth_map + + cam_coords = torch.stack((x_cam, y_cam, z_cam), dim=-1) # (S, H, W, 3) + + # Transform to world coordinates + cam_to_world = closed_form_inverse_se3(extrinsics_cam) # (S, 4, 4) + + # homo transformation + homo_pts = torch.cat((cam_coords, torch.ones_like(cam_coords[..., :1])), dim=-1).flatten(1, 2) + world_coords = torch.bmm(cam_to_world, homo_pts.transpose(1, 2)).transpose(1, 2)[:, :, :3].view(batch_size*num_views, H, W, 3) + + return world_coords.view(batch_size, num_views, H, W, 3) + +def unproject_depth_map_to_point_map( + depth_map: torch.Tensor, extrinsics_cam: torch.Tensor, intrinsics_cam: torch.Tensor +) -> torch.Tensor: + """ + Unproject a batch of depth maps to 3D world coordinates. + + Args: + depth_map (torch.Tensor): Batch of depth maps of shape (S, H, W, 1) or (S, H, W) + extrinsics_cam (torch.Tensor): Batch of camera extrinsic matrices of shape (S, 3, 4) + intrinsics_cam (torch.Tensor): Batch of camera intrinsic matrices of shape (S, 3, 3) + + Returns: + torch.Tensor: Batch of 3D world coordinates of shape (S, H, W, 3) + """ + world_points_list = [] + for frame_idx in range(depth_map.shape[0]): + cur_world_points, _, _ = depth_to_world_coords_points( + depth_map[frame_idx].squeeze(-1), extrinsics_cam[frame_idx], intrinsics_cam[frame_idx] + ) + world_points_list.append(cur_world_points) + world_points_array = torch.stack(world_points_list, dim=0) + + return world_points_array + + +def depth_to_world_coords_points( + depth_map: torch.Tensor, + extrinsic: torch.Tensor, + intrinsic: torch.Tensor, + eps=1e-8, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Convert a depth map to world coordinates. + + Args: + depth_map (torch.Tensor): Depth map of shape (H, W). + intrinsic (torch.Tensor): Camera intrinsic matrix of shape (3, 3). + extrinsic (torch.Tensor): Camera extrinsic matrix of shape (3, 4). OpenCV camera coordinate convention, cam from world. + + Returns: + tuple[torch.Tensor, torch.Tensor]: World coordinates (H, W, 3) and valid depth mask (H, W). + """ + if depth_map is None: + return None, None, None + + # Valid depth mask + point_mask = depth_map > eps + + # Convert depth map to camera coordinates + cam_coords_points = depth_to_cam_coords_points(depth_map, intrinsic) + + # Multiply with the inverse of extrinsic matrix to transform to world coordinates + # extrinsic_inv is 4x4 (note closed_form_inverse_OpenCV is batched, the output is (N, 4, 4)) + cam_to_world_extrinsic = closed_form_inverse_se3(extrinsic[None])[0] + + R_cam_to_world = cam_to_world_extrinsic[:3, :3] + t_cam_to_world = cam_to_world_extrinsic[:3, 3] + + # Apply the rotation and translation to the camera coordinates + world_coords_points = torch.matmul(cam_coords_points, R_cam_to_world.T) + t_cam_to_world # HxWx3, 3x3 -> HxWx3 + + return world_coords_points, cam_coords_points, point_mask + + +def depth_to_cam_coords_points(depth_map: torch.Tensor, intrinsic: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """ + Convert a depth map to camera coordinates. + + Args: + depth_map (torch.Tensor): Depth map of shape (H, W). + intrinsic (torch.Tensor): Camera intrinsic matrix of shape (3, 3). + + Returns: + tuple[torch.Tensor, torch.Tensor]: Camera coordinates (H, W, 3) + """ + H, W = depth_map.shape + assert intrinsic.shape == (3, 3), "Intrinsic matrix must be 3x3" + assert intrinsic[0, 1] == 0 and intrinsic[1, 0] == 0, "Intrinsic matrix must have zero skew" + + # Intrinsic parameters + fu, fv = intrinsic[0, 0], intrinsic[1, 1] + cu, cv = intrinsic[0, 2], intrinsic[1, 2] + + # Generate grid of pixel coordinates + u, v = torch.meshgrid(torch.arange(W, device=depth_map.device), + torch.arange(H, device=depth_map.device), + indexing='xy') + + # Unproject to camera coordinates + x_cam = (u - cu) * depth_map / fu + y_cam = (v - cv) * depth_map / fv + z_cam = depth_map + + # Stack to form camera coordinates + cam_coords = torch.stack((x_cam, y_cam, z_cam), dim=-1).to(dtype=torch.float32) + + return cam_coords + + +def closed_form_inverse_se3(se3, R=None, T=None): + """ + Compute the inverse of each 4x4 (or 3x4) SE3 matrix in a batch. + + If `R` and `T` are provided, they must correspond to the rotation and translation + components of `se3`. Otherwise, they will be extracted from `se3`. + + Args: + se3: Nx4x4 or Nx3x4 array or tensor of SE3 matrices. + R (optional): Nx3x3 array or tensor of rotation matrices. + T (optional): Nx3x1 array or tensor of translation vectors. + + Returns: + Inverted SE3 matrices with the same type and device as `se3`. + + Shapes: + se3: (N, 4, 4) + R: (N, 3, 3) + T: (N, 3, 1) + """ + # Validate shapes + if se3.shape[-2:] != (4, 4) and se3.shape[-2:] != (3, 4): + raise ValueError(f"se3 must be of shape (N,4,4), got {se3.shape}.") + + # Extract R and T if not provided + if R is None: + R = se3[:, :3, :3] # (N,3,3) + if T is None: + T = se3[:, :3, 3:] # (N,3,1) + + # Transpose R + R_transposed = R.transpose(1, 2) # (N,3,3) + top_right = -torch.bmm(R_transposed, T) # (N,3,1) + inverted_matrix = torch.eye(4, 4, device=R.device)[None].repeat(len(R), 1, 1) + inverted_matrix = inverted_matrix.to(R.dtype) + + inverted_matrix[:, :3, :3] = R_transposed + inverted_matrix[:, :3, 3:] = top_right + + return inverted_matrix diff --git a/src/model/encoder/vggt/utils/load_fn.py b/src/model/encoder/vggt/utils/load_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..580010be26f9792b65ec58f3fdfb859bfc795ee5 --- /dev/null +++ b/src/model/encoder/vggt/utils/load_fn.py @@ -0,0 +1,145 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from PIL import Image +from torchvision import transforms as TF + +def load_and_preprocess_images(image_path_list, mode="crop"): + """ + A quick start function to load and preprocess images for model input. + This assumes the images should have the same shape for easier batching, but our model can also work well with different shapes. + + Args: + image_path_list (list): List of paths to image files + mode (str, optional): Preprocessing mode, either "crop" or "pad". + - "crop" (default): Sets width to 518px and center crops height if needed. + - "pad": Preserves all pixels by making the largest dimension 518px + and padding the smaller dimension to reach a square shape. + + Returns: + torch.Tensor: Batched tensor of preprocessed images with shape (N, 3, H, W) + + Raises: + ValueError: If the input list is empty or if mode is invalid + + Notes: + - Images with different dimensions will be padded with white (value=1.0) + - A warning is printed when images have different shapes + - When mode="crop": The function ensures width=518px while maintaining aspect ratio + and height is center-cropped if larger than 518px + - When mode="pad": The function ensures the largest dimension is 518px while maintaining aspect ratio + and the smaller dimension is padded to reach a square shape (518x518) + - Dimensions are adjusted to be divisible by 14 for compatibility with model requirements + """ + # Check for empty list + if len(image_path_list) == 0: + raise ValueError("At least 1 image is required") + + # Validate mode + if mode not in ["crop", "pad"]: + raise ValueError("Mode must be either 'crop' or 'pad'") + + images = [] + shapes = set() + to_tensor = TF.ToTensor() + target_size = 448 + + # First process all images and collect their shapes + for image_path in image_path_list: + + # Open image + img = Image.open(image_path) + + # If there's an alpha channel, blend onto white background: + if img.mode == "RGBA": + # Create white background + background = Image.new("RGBA", img.size, (255, 255, 255, 255)) + # Alpha composite onto the white background + img = Image.alpha_composite(background, img) + + # Now convert to "RGB" (this step assigns white for transparent areas) + img = img.convert("RGB") + + width, height = img.size + + if mode == "pad": + # Make the largest dimension 518px while maintaining aspect ratio + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 # Make divisible by 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 # Make divisible by 14 + else: # mode == "crop" + # Original behavior: set width to 518px + new_width = target_size + # Calculate height maintaining aspect ratio, divisible by 14 + new_height = round(height * (new_width / width) / 14) * 14 + + # Resize with new dimensions (width, height) + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img = to_tensor(img) # Convert to tensor (0, 1) + + # Center crop height if it's larger than 518 (only in crop mode) + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img = img[:, start_y : start_y + target_size, :] + + # For pad mode, pad to make a square of target_size x target_size + if mode == "pad": + h_padding = target_size - img.shape[1] + w_padding = target_size - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + # Pad with white (value=1.0) + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + + shapes.add((img.shape[1], img.shape[2])) + images.append(img) + + # Check if we have different shapes + # In theory our model can also work well with different shapes + if len(shapes) > 1: + print(f"Warning: Found images with different shapes: {shapes}") + # Find maximum dimensions + max_height = max(shape[0] for shape in shapes) + max_width = max(shape[1] for shape in shapes) + + # Pad images if necessary + padded_images = [] + for img in images: + h_padding = max_height - img.shape[1] + w_padding = max_width - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + padded_images.append(img) + images = padded_images + + images = torch.stack(images) # concatenate images + + # Ensure correct shape when single image + if len(image_path_list) == 1: + # Verify shape is (1, C, H, W) + if images.dim() == 3: + images = images.unsqueeze(0) + + return images diff --git a/src/model/encoder/vggt/utils/pose_enc.py b/src/model/encoder/vggt/utils/pose_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..b1c8d20b778786f4d8c35226eebb586fe46da94c --- /dev/null +++ b/src/model/encoder/vggt/utils/pose_enc.py @@ -0,0 +1,130 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from .rotation import quat_to_mat, mat_to_quat + + +def extri_intri_to_pose_encoding( + extrinsics, + intrinsics, + image_size_hw=None, # e.g., (256, 512) + pose_encoding_type="absT_quaR_FoV", +): + """Convert camera extrinsics and intrinsics to a compact pose encoding. + + This function transforms camera parameters into a unified pose encoding format, + which can be used for various downstream tasks like pose prediction or representation. + + Args: + extrinsics (torch.Tensor): Camera extrinsic parameters with shape BxSx3x4, + where B is batch size and S is sequence length. + In OpenCV coordinate system (x-right, y-down, z-forward), representing camera from world transformation. + The format is [R|t] where R is a 3x3 rotation matrix and t is a 3x1 translation vector. + intrinsics (torch.Tensor): Camera intrinsic parameters with shape BxSx3x3. + Defined in pixels, with format: + [[fx, 0, cx], + [0, fy, cy], + [0, 0, 1]] + where fx, fy are focal lengths and (cx, cy) is the principal point + image_size_hw (tuple): Tuple of (height, width) of the image in pixels. + Required for computing field of view values. For example: (256, 512). + pose_encoding_type (str): Type of pose encoding to use. Currently only + supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view). + + Returns: + torch.Tensor: Encoded camera pose parameters with shape BxSx9. + For "absT_quaR_FoV" type, the 9 dimensions are: + - [:3] = absolute translation vector T (3D) + - [3:7] = rotation as quaternion quat (4D) + - [7:] = field of view (2D) + """ + + # extrinsics: BxSx3x4 + # intrinsics: BxSx3x3 + + if pose_encoding_type == "absT_quaR_FoV": + R = extrinsics[:, :, :3, :3] # BxSx3x3 + T = extrinsics[:, :, :3, 3] # BxSx3 + + quat = mat_to_quat(R) + # Note the order of h and w here + H, W = image_size_hw + fov_h = 2 * torch.atan((H / 2) / intrinsics[..., 1, 1]) + fov_w = 2 * torch.atan((W / 2) / intrinsics[..., 0, 0]) + pose_encoding = torch.cat([T, quat, fov_h[..., None], fov_w[..., None]], dim=-1).float() + else: + raise NotImplementedError + + return pose_encoding + + +def pose_encoding_to_extri_intri( + pose_encoding, + image_size_hw=None, # e.g., (256, 512) + pose_encoding_type="absT_quaR_FoV", + build_intrinsics=True, +): + """Convert a pose encoding back to camera extrinsics and intrinsics. + + This function performs the inverse operation of extri_intri_to_pose_encoding, + reconstructing the full camera parameters from the compact encoding. + + Args: + pose_encoding (torch.Tensor): Encoded camera pose parameters with shape BxSx9, + where B is batch size and S is sequence length. + For "absT_quaR_FoV" type, the 9 dimensions are: + - [:3] = absolute translation vector T (3D) + - [3:7] = rotation as quaternion quat (4D) + - [7:] = field of view (2D) + image_size_hw (tuple): Tuple of (height, width) of the image in pixels. + Required for reconstructing intrinsics from field of view values. + For example: (256, 512). + pose_encoding_type (str): Type of pose encoding used. Currently only + supports "absT_quaR_FoV" (absolute translation, quaternion rotation, field of view). + build_intrinsics (bool): Whether to reconstruct the intrinsics matrix. + If False, only extrinsics are returned and intrinsics will be None. + + Returns: + tuple: (extrinsics, intrinsics) + - extrinsics (torch.Tensor): Camera extrinsic parameters with shape BxSx3x4. + In OpenCV coordinate system (x-right, y-down, z-forward), representing camera from world + transformation. The format is [R|t] where R is a 3x3 rotation matrix and t is + a 3x1 translation vector. + - intrinsics (torch.Tensor or None): Camera intrinsic parameters with shape BxSx3x3, + or None if build_intrinsics is False. Defined in pixels, with format: + [[fx, 0, cx], + [0, fy, cy], + [0, 0, 1]] + where fx, fy are focal lengths and (cx, cy) is the principal point, + assumed to be at the center of the image (W/2, H/2). + """ + + intrinsics = None + + if pose_encoding_type == "absT_quaR_FoV": + T = pose_encoding[..., :3] + quat = pose_encoding[..., 3:7] + fov_h = pose_encoding[..., 7] + fov_w = pose_encoding[..., 8] + + R = quat_to_mat(quat) + extrinsics = torch.cat([R, T[..., None]], dim=-1) + + if build_intrinsics: + H, W = image_size_hw + fy = (H / 2.0) / (torch.tan(fov_h / 2.0) + 1e-3) + fx = (W / 2.0) / (torch.tan(fov_w / 2.0) + 1e-3) + intrinsics = torch.zeros(pose_encoding.shape[:2] + (3, 3), device=pose_encoding.device, dtype=pose_encoding.dtype) + intrinsics[..., 0, 0] = fx + intrinsics[..., 1, 1] = fy + intrinsics[..., 0, 2] = W / 2 + intrinsics[..., 1, 2] = H / 2 + intrinsics[..., 2, 2] = 1.0 # Set the homogeneous coordinate to 1 + else: + raise NotImplementedError + + return extrinsics, intrinsics diff --git a/src/model/encoder/vggt/utils/rotation.py b/src/model/encoder/vggt/utils/rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..bd3830c098a59ed4590b56c0dbbcc2c0ee4fa6f8 --- /dev/null +++ b/src/model/encoder/vggt/utils/rotation.py @@ -0,0 +1,138 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Modified from PyTorch3D, https://github.com/facebookresearch/pytorch3d + +import torch +import numpy as np +import torch.nn.functional as F + + +def quat_to_mat(quaternions: torch.Tensor) -> torch.Tensor: + """ + Quaternion Order: XYZW or say ijkr, scalar-last + + Convert rotations given as quaternions to rotation matrices. + Args: + quaternions: quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + i, j, k, r = torch.unbind(quaternions, -1) + # pyre-fixme[58]: `/` is not supported for operand types `float` and `Tensor`. + two_s = 2.0 / (quaternions * quaternions).sum(-1) + + o = torch.stack( + ( + 1 - two_s * (j * j + k * k), + two_s * (i * j - k * r), + two_s * (i * k + j * r), + two_s * (i * j + k * r), + 1 - two_s * (i * i + k * k), + two_s * (j * k - i * r), + two_s * (i * k - j * r), + two_s * (j * k + i * r), + 1 - two_s * (i * i + j * j), + ), + -1, + ) + return o.reshape(quaternions.shape[:-1] + (3, 3)) + + +def mat_to_quat(matrix: torch.Tensor) -> torch.Tensor: + """ + Convert rotations given as rotation matrices to quaternions. + + Args: + matrix: Rotation matrices as tensor of shape (..., 3, 3). + + Returns: + quaternions with real part last, as tensor of shape (..., 4). + Quaternion Order: XYZW or say ijkr, scalar-last + """ + if matrix.size(-1) != 3 or matrix.size(-2) != 3: + raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.") + + batch_dim = matrix.shape[:-2] + m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9,)), dim=-1) + + q_abs = _sqrt_positive_part( + torch.stack( + [ + 1.0 + m00 + m11 + m22, + 1.0 + m00 - m11 - m22, + 1.0 - m00 + m11 - m22, + 1.0 - m00 - m11 + m22, + ], + dim=-1, + ) + ) + + # we produce the desired quaternion multiplied by each of r, i, j, k + quat_by_rijk = torch.stack( + [ + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1), + # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and + # `int`. + torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1), + ], + dim=-2, + ) + + # We floor here at 0.1 but the exact level is not important; if q_abs is small, + # the candidate won't be picked. + flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device) + quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr)) + + # if not for numerical problems, quat_candidates[i] should be same (up to a sign), + # forall i; we pick the best-conditioned one (with the largest denominator) + out = quat_candidates[F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :].reshape(batch_dim + (4,)) + + # Convert from rijk to ijkr + out = out[..., [1, 2, 3, 0]] + + out = standardize_quaternion(out) + + return out + + +def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor: + """ + Returns torch.sqrt(torch.max(0, x)) + but with a zero subgradient where x is 0. + """ + ret = torch.zeros_like(x) + positive_mask = x > 0 + if torch.is_grad_enabled(): + ret[positive_mask] = torch.sqrt(x[positive_mask]) + else: + ret = torch.where(positive_mask, torch.sqrt(x), ret) + return ret + + +def standardize_quaternion(quaternions: torch.Tensor) -> torch.Tensor: + """ + Convert a unit quaternion to a standard form: one in which the real + part is non negative. + + Args: + quaternions: Quaternions with real part last, + as tensor of shape (..., 4). + + Returns: + Standardized quaternions as tensor of shape (..., 4). + """ + return torch.where(quaternions[..., 3:4] < 0, -quaternions, quaternions) diff --git a/src/model/encoder/vggt/utils/visual_track.py b/src/model/encoder/vggt/utils/visual_track.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e0a27dedb261173ccd5f87d04fbe472657bb96 --- /dev/null +++ b/src/model/encoder/vggt/utils/visual_track.py @@ -0,0 +1,239 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import cv2 +import torch +import numpy as np +import os + + +def color_from_xy(x, y, W, H, cmap_name="hsv"): + """ + Map (x, y) -> color in (R, G, B). + 1) Normalize x,y to [0,1]. + 2) Combine them into a single scalar c in [0,1]. + 3) Use matplotlib's colormap to convert c -> (R,G,B). + + You can customize step 2, e.g., c = (x + y)/2, or some function of (x, y). + """ + import matplotlib.cm + import matplotlib.colors + + x_norm = x / max(W - 1, 1) + y_norm = y / max(H - 1, 1) + # Simple combination: + c = (x_norm + y_norm) / 2.0 + + cmap = matplotlib.cm.get_cmap(cmap_name) + # cmap(c) -> (r,g,b,a) in [0,1] + rgba = cmap(c) + r, g, b = rgba[0], rgba[1], rgba[2] + return (r, g, b) # in [0,1], RGB order + + +def get_track_colors_by_position(tracks_b, vis_mask_b=None, image_width=None, image_height=None, cmap_name="hsv"): + """ + Given all tracks in one sample (b), compute a (N,3) array of RGB color values + in [0,255]. The color is determined by the (x,y) position in the first + visible frame for each track. + + Args: + tracks_b: Tensor of shape (S, N, 2). (x,y) for each track in each frame. + vis_mask_b: (S, N) boolean mask; if None, assume all are visible. + image_width, image_height: used for normalizing (x, y). + cmap_name: for matplotlib (e.g., 'hsv', 'rainbow', 'jet'). + + Returns: + track_colors: np.ndarray of shape (N, 3), each row is (R,G,B) in [0,255]. + """ + S, N, _ = tracks_b.shape + track_colors = np.zeros((N, 3), dtype=np.uint8) + + if vis_mask_b is None: + # treat all as visible + vis_mask_b = torch.ones(S, N, dtype=torch.bool, device=tracks_b.device) + + for i in range(N): + # Find first visible frame for track i + visible_frames = torch.where(vis_mask_b[:, i])[0] + if len(visible_frames) == 0: + # track is never visible; just assign black or something + track_colors[i] = (0, 0, 0) + continue + + first_s = int(visible_frames[0].item()) + # use that frame's (x,y) + x, y = tracks_b[first_s, i].tolist() + + # map (x,y) -> (R,G,B) in [0,1] + r, g, b = color_from_xy(x, y, W=image_width, H=image_height, cmap_name=cmap_name) + # scale to [0,255] + r, g, b = int(r * 255), int(g * 255), int(b * 255) + track_colors[i] = (r, g, b) + + return track_colors + + +def visualize_tracks_on_images( + images, + tracks, + track_vis_mask=None, + out_dir="track_visuals_concat_by_xy", + image_format="CHW", # "CHW" or "HWC" + normalize_mode="[0,1]", + cmap_name="hsv", # e.g. "hsv", "rainbow", "jet" + frames_per_row=4, # New parameter for grid layout + save_grid=True, # Flag to control whether to save the grid image +): + """ + Visualizes frames in a grid layout with specified frames per row. + Each track's color is determined by its (x,y) position + in the first visible frame (or frame 0 if always visible). + Finally convert the BGR result to RGB before saving. + Also saves each individual frame as a separate PNG file. + + Args: + images: torch.Tensor (S, 3, H, W) if CHW or (S, H, W, 3) if HWC. + tracks: torch.Tensor (S, N, 2), last dim = (x, y). + track_vis_mask: torch.Tensor (S, N) or None. + out_dir: folder to save visualizations. + image_format: "CHW" or "HWC". + normalize_mode: "[0,1]", "[-1,1]", or None for direct raw -> 0..255 + cmap_name: a matplotlib colormap name for color_from_xy. + frames_per_row: number of frames to display in each row of the grid. + save_grid: whether to save all frames in one grid image. + + Returns: + None (saves images in out_dir). + """ + + if len(tracks.shape) == 4: + tracks = tracks.squeeze(0) + images = images.squeeze(0) + if track_vis_mask is not None: + track_vis_mask = track_vis_mask.squeeze(0) + + import matplotlib + + matplotlib.use("Agg") # for non-interactive (optional) + + os.makedirs(out_dir, exist_ok=True) + + S = images.shape[0] + _, N, _ = tracks.shape # (S, N, 2) + + # Move to CPU + images = images.cpu().clone() + tracks = tracks.cpu().clone() + if track_vis_mask is not None: + track_vis_mask = track_vis_mask.cpu().clone() + + # Infer H, W from images shape + if image_format == "CHW": + # e.g. images[s].shape = (3, H, W) + H, W = images.shape[2], images.shape[3] + else: + # e.g. images[s].shape = (H, W, 3) + H, W = images.shape[1], images.shape[2] + + # Pre-compute the color for each track i based on first visible position + track_colors_rgb = get_track_colors_by_position( + tracks, # shape (S, N, 2) + vis_mask_b=track_vis_mask if track_vis_mask is not None else None, + image_width=W, + image_height=H, + cmap_name=cmap_name, + ) + + # We'll accumulate each frame's drawn image in a list + frame_images = [] + + for s in range(S): + # shape => either (3, H, W) or (H, W, 3) + img = images[s] + + # Convert to (H, W, 3) + if image_format == "CHW": + img = img.permute(1, 2, 0) # (H, W, 3) + # else "HWC", do nothing + + img = img.numpy().astype(np.float32) + + # Scale to [0,255] if needed + if normalize_mode == "[0,1]": + img = np.clip(img, 0, 1) * 255.0 + elif normalize_mode == "[-1,1]": + img = (img + 1.0) * 0.5 * 255.0 + img = np.clip(img, 0, 255.0) + # else no normalization + + # Convert to uint8 + img = img.astype(np.uint8) + + # For drawing in OpenCV, convert to BGR + img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + + # Draw each visible track + cur_tracks = tracks[s] # shape (N, 2) + if track_vis_mask is not None: + valid_indices = torch.where(track_vis_mask[s])[0] + else: + valid_indices = range(N) + + cur_tracks_np = cur_tracks.numpy() + for i in valid_indices: + x, y = cur_tracks_np[i] + pt = (int(round(x)), int(round(y))) + + # track_colors_rgb[i] is (R,G,B). For OpenCV circle, we need BGR + R, G, B = track_colors_rgb[i] + color_bgr = (int(B), int(G), int(R)) + cv2.circle(img_bgr, pt, radius=3, color=color_bgr, thickness=-1) + + # Convert back to RGB for consistent final saving: + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + + # Save individual frame + frame_path = os.path.join(out_dir, f"frame_{s:04d}.png") + # Convert to BGR for OpenCV imwrite + frame_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(frame_path, frame_bgr) + + frame_images.append(img_rgb) + + # Only create and save the grid image if save_grid is True + if save_grid: + # Calculate grid dimensions + num_rows = (S + frames_per_row - 1) // frames_per_row # Ceiling division + + # Create a grid of images + grid_img = None + for row in range(num_rows): + start_idx = row * frames_per_row + end_idx = min(start_idx + frames_per_row, S) + + # Concatenate this row horizontally + row_img = np.concatenate(frame_images[start_idx:end_idx], axis=1) + + # If this row has fewer than frames_per_row images, pad with black + if end_idx - start_idx < frames_per_row: + padding_width = (frames_per_row - (end_idx - start_idx)) * W + padding = np.zeros((H, padding_width, 3), dtype=np.uint8) + row_img = np.concatenate([row_img, padding], axis=1) + + # Add this row to the grid + if grid_img is None: + grid_img = row_img + else: + grid_img = np.concatenate([grid_img, row_img], axis=0) + + out_path = os.path.join(out_dir, "tracks_grid.png") + # Convert back to BGR for OpenCV imwrite + grid_img_bgr = cv2.cvtColor(grid_img, cv2.COLOR_RGB2BGR) + cv2.imwrite(out_path, grid_img_bgr) + print(f"[INFO] Saved color-by-XY track visualization grid -> {out_path}") + + print(f"[INFO] Saved {S} individual frames to {out_dir}/frame_*.png") diff --git a/src/model/encoder/visualization/encoder_visualizer.py b/src/model/encoder/visualization/encoder_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..038a25b0903044b63405f12ac9906aff3de81e5f --- /dev/null +++ b/src/model/encoder/visualization/encoder_visualizer.py @@ -0,0 +1,25 @@ +from abc import ABC, abstractmethod +from typing import Generic, TypeVar + +from jaxtyping import Float +from torch import Tensor + +T_cfg = TypeVar("T_cfg") +T_encoder = TypeVar("T_encoder") + + +class EncoderVisualizer(ABC, Generic[T_cfg, T_encoder]): + cfg: T_cfg + encoder: T_encoder + + def __init__(self, cfg: T_cfg, encoder: T_encoder) -> None: + self.cfg = cfg + self.encoder = encoder + + @abstractmethod + def visualize( + self, + context: dict, + global_step: int, + ) -> dict[str, Float[Tensor, "3 _ _"]]: + pass diff --git a/src/model/encoder/visualization/encoder_visualizer_epipolar.py b/src/model/encoder/visualization/encoder_visualizer_epipolar.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f5c4372eb29c7a884621746ed73a2b85eede5e --- /dev/null +++ b/src/model/encoder/visualization/encoder_visualizer_epipolar.py @@ -0,0 +1,526 @@ +from pathlib import Path +from random import randrange +from typing import Optional + +import numpy as np +import torch +import wandb +from einops import rearrange, reduce, repeat +from jaxtyping import Bool, Float +from torch import Tensor + +from ....dataset.types import BatchedViews +from ....misc.heterogeneous_pairings import generate_heterogeneous_index +from ....visualization.annotation import add_label +from ....visualization.color_map import apply_color_map, apply_color_map_to_image +from ....visualization.colors import get_distinct_color +from ....visualization.drawing.lines import draw_lines +from ....visualization.drawing.points import draw_points +from ....visualization.layout import add_border, hcat, vcat +from ...ply_export import export_ply +from .encoder_visualizer import EncoderVisualizer +from .encoder_visualizer_epipolar_cfg import EncoderVisualizerEpipolarCfg + + +def box( + image: Float[Tensor, "3 height width"], +) -> Float[Tensor, "3 new_height new_width"]: + return add_border(add_border(image), 1, 0) + + +class EncoderVisualizerEpipolar( + EncoderVisualizer[EncoderVisualizerEpipolarCfg, EncoderEpipolar] +): + def visualize( + self, + context: BatchedViews, + global_step: int, + ) -> dict[str, Float[Tensor, "3 _ _"]]: + # Short-circuit execution when ablating the epipolar transformer. + if self.encoder.epipolar_transformer is None: + return {} + + visualization_dump = {} + + softmax_weights = [] + + def hook(module, input, output): + softmax_weights.append(output) + + # Register hooks to grab attention. + handles = [ + layer[0].fn.attend.register_forward_hook(hook) + for layer in self.encoder.epipolar_transformer.transformer.layers + ] + + result = self.encoder.forward( + context, + global_step, + visualization_dump=visualization_dump, + deterministic=True, + ) + + # De-register hooks. + for handle in handles: + handle.remove() + + softmax_weights = torch.stack(softmax_weights) + + # Generate high-resolution context images that can be drawn on. + context_images = context["image"] + _, _, _, h, w = context_images.shape + length = min(h, w) + min_resolution = self.cfg.min_resolution + scale_multiplier = (min_resolution + length - 1) // length + if scale_multiplier > 1: + context_images = repeat( + context_images, + "b v c h w -> b v c (h rh) (w rw)", + rh=scale_multiplier, + rw=scale_multiplier, + ) + + # This is kind of hacky for now, since we're using it for short experiments. + if self.cfg.export_ply and wandb.run is not None: + name = wandb.run._name.split(" ")[0] + ply_path = Path(f"outputs/gaussians/{name}/{global_step:0>6}.ply") + export_ply( + context["extrinsics"][0, 0], + result.means[0], + visualization_dump["scales"][0], + visualization_dump["rotations"][0], + result.harmonics[0], + result.opacities[0], + ply_path, + ) + + return { + # "attention": self.visualize_attention( + # context_images, + # visualization_dump["sampling"], + # softmax_weights, + # ), + "epipolar_samples": self.visualize_epipolar_samples( + context_images, + visualization_dump["sampling"], + ), + "epipolar_color_samples": self.visualize_epipolar_color_samples( + context_images, + context, + ), + "gaussians": self.visualize_gaussians( + context["image"], + result.opacities, + result.covariances, + result.harmonics[..., 0], # Just visualize DC component. + ), + "overlaps": self.visualize_overlaps( + context["image"], + visualization_dump["sampling"], + visualization_dump.get("is_monocular", None), + ), + "depth": self.visualize_depth( + context, + visualization_dump["depth"], + ), + } + + def visualize_attention( + self, + context_images: Float[Tensor, "batch view 3 height width"], + sampling: EpipolarSampling, + attention: Float[Tensor, "layer bvr head 1 sample"], + ) -> Float[Tensor, "3 vis_height vis_width"]: + device = context_images.device + + # Pick a random batch element, view, and other view. + b, v, ov, r, s, _ = sampling.xy_sample.shape + rb = randrange(b) + rv = randrange(v) + rov = randrange(ov) + num_samples = self.cfg.num_samples + rr = np.random.choice(r, num_samples, replace=False) + rr = torch.tensor(rr, dtype=torch.int64, device=device) + + # Visualize the rays in the ray view. + ray_view = draw_points( + context_images[rb, rv], + sampling.xy_ray[rb, rv, rr], + 0, + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + ray_view = draw_points( + ray_view, + sampling.xy_ray[rb, rv, rr], + [get_distinct_color(i) for i, _ in enumerate(rr)], + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + # Visualize attention in the sample view. + attention = rearrange( + attention, "l (b v r) hd () s -> l b v r hd s", b=b, v=v, r=r + ) + attention = attention[:, rb, rv, rr, :, :] + num_layers, _, hd, _ = attention.shape + + vis = [] + for il in range(num_layers): + vis_layer = [] + for ihd in range(hd): + # Create colors according to attention. + color = [get_distinct_color(i) for i, _ in enumerate(rr)] + color = torch.tensor(color, device=attention.device) + color = rearrange(color, "r c -> r () c") + attn = rearrange(attention[il, :, ihd], "r s -> r s ()") + color = rearrange(attn * color, "r s c -> (r s ) c") + + # Draw the alternating bucket lines. + vis_layer_head = draw_lines( + context_images[rb, self.encoder.sampler.index_v[rv, rov]], + rearrange( + sampling.xy_sample_near[rb, rv, rov, rr], "r s xy -> (r s) xy" + ), + rearrange( + sampling.xy_sample_far[rb, rv, rov, rr], "r s xy -> (r s) xy" + ), + color, + 3, + cap="butt", + x_range=(0, 1), + y_range=(0, 1), + ) + vis_layer.append(vis_layer_head) + vis.append(add_label(vcat(*vis_layer), f"Layer {il}")) + vis = add_label(add_border(add_border(hcat(*vis)), 1, 0), "Keys & Values") + vis = add_border(hcat(add_label(ray_view), vis, align="top")) + return vis + + def visualize_depth( + self, + context: BatchedViews, + multi_depth: Float[Tensor, "batch view height width surface spp"], + ) -> Float[Tensor, "3 vis_width vis_height"]: + multi_vis = [] + *_, srf, _ = multi_depth.shape + for i in range(srf): + depth = multi_depth[..., i, :] + depth = depth.mean(dim=-1) + + # Compute relative depth and disparity. + near = rearrange(context["near"], "b v -> b v () ()") + far = rearrange(context["far"], "b v -> b v () ()") + relative_depth = (depth - near) / (far - near) + relative_disparity = 1 - (1 / depth - 1 / far) / (1 / near - 1 / far) + + relative_depth = apply_color_map_to_image(relative_depth, "turbo") + relative_depth = vcat(*[hcat(*x) for x in relative_depth]) + relative_depth = add_label(relative_depth, "Depth") + relative_disparity = apply_color_map_to_image(relative_disparity, "turbo") + relative_disparity = vcat(*[hcat(*x) for x in relative_disparity]) + relative_disparity = add_label(relative_disparity, "Disparity") + multi_vis.append(add_border(hcat(relative_depth, relative_disparity))) + + return add_border(vcat(*multi_vis)) + + def visualize_overlaps( + self, + context_images: Float[Tensor, "batch view 3 height width"], + sampling: EpipolarSampling, + is_monocular: Optional[Bool[Tensor, "batch view height width"]] = None, + ) -> Float[Tensor, "3 vis_width vis_height"]: + device = context_images.device + b, v, _, h, w = context_images.shape + green = torch.tensor([0.235, 0.706, 0.294], device=device)[..., None, None] + rb = randrange(b) + valid = sampling.valid[rb].float() + ds = self.encoder.cfg.epipolar_transformer.downscale + valid = repeat( + valid, + "v ov (h w) -> v ov c (h rh) (w rw)", + c=3, + h=h // ds, + w=w // ds, + rh=ds, + rw=ds, + ) + + if is_monocular is not None: + is_monocular = is_monocular[rb].float() + is_monocular = repeat(is_monocular, "v h w -> v c h w", c=3, h=h, w=w) + + # Select context images in grid. + context_images = context_images[rb] + index, _ = generate_heterogeneous_index(v) + valid = valid * (green + context_images[index]) / 2 + + vis = vcat(*(hcat(im, hcat(*v)) for im, v in zip(context_images, valid))) + vis = add_label(vis, "Context Overlaps") + + if is_monocular is not None: + vis = hcat(vis, add_label(vcat(*is_monocular), "Monocular?")) + + return add_border(vis) + + def visualize_gaussians( + self, + context_images: Float[Tensor, "batch view 3 height width"], + opacities: Float[Tensor, "batch vrspp"], + covariances: Float[Tensor, "batch vrspp 3 3"], + colors: Float[Tensor, "batch vrspp 3"], + ) -> Float[Tensor, "3 vis_height vis_width"]: + b, v, _, h, w = context_images.shape + rb = randrange(b) + context_images = context_images[rb] + opacities = repeat( + opacities[rb], "(v h w spp) -> spp v c h w", v=v, c=3, h=h, w=w + ) + colors = rearrange(colors[rb], "(v h w spp) c -> spp v c h w", v=v, h=h, w=w) + + # Color-map Gaussian covariawnces. + det = covariances[rb].det() + det = apply_color_map(det / det.max(), "inferno") + det = rearrange(det, "(v h w spp) c -> spp v c h w", v=v, h=h, w=w) + + return add_border( + hcat( + add_label(box(hcat(*context_images)), "Context"), + add_label(box(vcat(*[hcat(*x) for x in opacities])), "Opacities"), + add_label( + box(vcat(*[hcat(*x) for x in (colors * opacities)])), "Colors" + ), + add_label(box(vcat(*[hcat(*x) for x in colors])), "Colors (Raw)"), + add_label(box(vcat(*[hcat(*x) for x in det])), "Determinant"), + ) + ) + + def visualize_probabilities( + self, + context_images: Float[Tensor, "batch view 3 height width"], + sampling: EpipolarSampling, + pdf: Float[Tensor, "batch view ray sample"], + ) -> Float[Tensor, "3 vis_height vis_width"]: + device = context_images.device + + # Pick a random batch element, view, and other view. + b, v, ov, r, _, _ = sampling.xy_sample.shape + rb = randrange(b) + rv = randrange(v) + rov = randrange(ov) + num_samples = self.cfg.num_samples + rr = np.random.choice(r, num_samples, replace=False) + rr = torch.tensor(rr, dtype=torch.int64, device=device) + colors = [get_distinct_color(i) for i, _ in enumerate(rr)] + colors = torch.tensor(colors, dtype=torch.float32, device=device) + + # Visualize the rays in the ray view. + ray_view = draw_points( + context_images[rb, rv], + sampling.xy_ray[rb, rv, rr], + 0, + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + ray_view = draw_points( + ray_view, + sampling.xy_ray[rb, rv, rr], + colors, + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + # Visualize probabilities in the sample view. + pdf = pdf[rb, rv, rr] + pdf = rearrange(pdf, "r s -> r s ()") + colors = rearrange(colors, "r c -> r () c") + sample_view = draw_lines( + context_images[rb, self.encoder.sampler.index_v[rv, rov]], + rearrange(sampling.xy_sample_near[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(sampling.xy_sample_far[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(pdf * colors, "r s c -> (r s) c"), + 6, + cap="butt", + x_range=(0, 1), + y_range=(0, 1), + ) + + # Visualize rescaled probabilities in the sample view. + pdf_magnified = pdf / reduce(pdf, "r s () -> r () ()", "max") + sample_view_magnified = draw_lines( + context_images[rb, self.encoder.sampler.index_v[rv, rov]], + rearrange(sampling.xy_sample_near[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(sampling.xy_sample_far[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(pdf_magnified * colors, "r s c -> (r s) c"), + 6, + cap="butt", + x_range=(0, 1), + y_range=(0, 1), + ) + + return add_border( + hcat( + add_label(ray_view, "Rays"), + add_label(sample_view, "Samples"), + add_label(sample_view_magnified, "Samples (Magnified PDF)"), + ) + ) + + def visualize_epipolar_samples( + self, + context_images: Float[Tensor, "batch view 3 height width"], + sampling: EpipolarSampling, + ) -> Float[Tensor, "3 vis_height vis_width"]: + device = context_images.device + + # Pick a random batch element, view, and other view. + b, v, ov, r, s, _ = sampling.xy_sample.shape + rb = randrange(b) + rv = randrange(v) + rov = randrange(ov) + num_samples = self.cfg.num_samples + rr = np.random.choice(r, num_samples, replace=False) + rr = torch.tensor(rr, dtype=torch.int64, device=device) + + # Visualize the rays in the ray view. + ray_view = draw_points( + context_images[rb, rv], + sampling.xy_ray[rb, rv, rr], + 0, + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + ray_view = draw_points( + ray_view, + sampling.xy_ray[rb, rv, rr], + [get_distinct_color(i) for i, _ in enumerate(rr)], + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + # Visualize the samples and epipolar lines in the sample view. + # First, draw the epipolar line in black. + sample_view = draw_lines( + context_images[rb, self.encoder.sampler.index_v[rv, rov]], + sampling.xy_sample_near[rb, rv, rov, rr, 0], + sampling.xy_sample_far[rb, rv, rov, rr, -1], + 0, + 5, + cap="butt", + x_range=(0, 1), + y_range=(0, 1), + ) + + # Create an alternating line color for the buckets. + color = repeat( + torch.tensor([0, 1], device=device), + "ab -> r (s ab) c", + r=len(rr), + s=(s + 1) // 2, + c=3, + ) + color = rearrange(color[:, :s], "r s c -> (r s) c") + + # Draw the alternating bucket lines. + sample_view = draw_lines( + sample_view, + rearrange(sampling.xy_sample_near[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(sampling.xy_sample_far[rb, rv, rov, rr], "r s xy -> (r s) xy"), + color, + 3, + cap="butt", + x_range=(0, 1), + y_range=(0, 1), + ) + + # Draw the sample points. + sample_view = draw_points( + sample_view, + rearrange(sampling.xy_sample[rb, rv, rov, rr], "r s xy -> (r s) xy"), + 0, + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + sample_view = draw_points( + sample_view, + rearrange(sampling.xy_sample[rb, rv, rov, rr], "r s xy -> (r s) xy"), + [get_distinct_color(i // s) for i in range(s * len(rr))], + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + return add_border( + hcat(add_label(ray_view, "Ray View"), add_label(sample_view, "Sample View")) + ) + + def visualize_epipolar_color_samples( + self, + context_images: Float[Tensor, "batch view 3 height width"], + context: BatchedViews, + ) -> Float[Tensor, "3 vis_height vis_width"]: + device = context_images.device + + sampling = self.encoder.sampler( + context["image"], + context["extrinsics"], + context["intrinsics"], + context["near"], + context["far"], + ) + + # Pick a random batch element, view, and other view. + b, v, ov, r, s, _ = sampling.xy_sample.shape + rb = randrange(b) + rv = randrange(v) + rov = randrange(ov) + num_samples = self.cfg.num_samples + rr = np.random.choice(r, num_samples, replace=False) + rr = torch.tensor(rr, dtype=torch.int64, device=device) + + # Visualize the rays in the ray view. + ray_view = draw_points( + context_images[rb, rv], + sampling.xy_ray[rb, rv, rr], + 0, + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + ray_view = draw_points( + ray_view, + sampling.xy_ray[rb, rv, rr], + [get_distinct_color(i) for i, _ in enumerate(rr)], + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + # Visualize the samples and in the sample view. + sample_view = draw_points( + context_images[rb, self.encoder.sampler.index_v[rv, rov]], + rearrange(sampling.xy_sample[rb, rv, rov, rr], "r s xy -> (r s) xy"), + [get_distinct_color(i // s) for i in range(s * len(rr))], + radius=4, + x_range=(0, 1), + y_range=(0, 1), + ) + sample_view = draw_points( + sample_view, + rearrange(sampling.xy_sample[rb, rv, rov, rr], "r s xy -> (r s) xy"), + rearrange(sampling.features[rb, rv, rov, rr], "r s c -> (r s) c"), + radius=3, + x_range=(0, 1), + y_range=(0, 1), + ) + + return add_border( + hcat(add_label(ray_view, "Ray View"), add_label(sample_view, "Sample View")) + )