Spaces:
Sleeping
Sleeping
Initial commit for brand new AnySplat ZeroGPU Space (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- src/misc/LocalLogger.py +48 -0
- src/misc/image_io.py +211 -0
- src/misc/nn_module_tools.py +16 -0
- src/misc/sh_rotation.py +111 -0
- src/misc/sht.py +1637 -0
- src/misc/step_tracker.py +23 -0
- src/misc/utils.py +73 -0
- src/misc/wandb_tools.py +62 -0
- src/misc/weight_modify.py +197 -0
- src/model/decoder/__init__.py +12 -0
- src/model/decoder/cuda_splatting.py +244 -0
- src/model/decoder/decoder.py +46 -0
- src/model/decoder/decoder_splatting_cuda.py +111 -0
- src/model/encoder/__init__.py +19 -0
- src/model/encoder/anysplat.py +590 -0
- src/model/encoder/backbone/__init__.py +21 -0
- src/model/encoder/backbone/backbone.py +29 -0
- src/model/encoder/backbone/backbone_croco.py +281 -0
- src/model/encoder/backbone/backbone_croco_multiview.py +245 -0
- src/model/encoder/backbone/backbone_dino.py +79 -0
- src/model/encoder/backbone/backbone_resnet.py +100 -0
- src/model/encoder/backbone/croco/README.md +7 -0
- src/model/encoder/backbone/croco/__init__.py +0 -0
- src/model/encoder/backbone/croco/blocks.py +241 -0
- src/model/encoder/backbone/croco/croco.py +249 -0
- src/model/encoder/backbone/croco/curope/__init__.py +4 -0
- src/model/encoder/backbone/croco/curope/curope.cpp +69 -0
- src/model/encoder/backbone/croco/curope/curope2d.py +40 -0
- src/model/encoder/backbone/croco/curope/kernels.cu +108 -0
- src/model/encoder/backbone/croco/curope/setup.py +34 -0
- src/model/encoder/backbone/croco/masking.py +25 -0
- src/model/encoder/backbone/croco/misc.py +138 -0
- src/model/encoder/backbone/croco/patch_embed.py +70 -0
- src/model/encoder/backbone/croco/pos_embed.py +159 -0
- src/model/encoder/common/gaussian_adapter.py +180 -0
- src/model/encoder/common/gaussians.py +44 -0
- src/model/encoder/encoder.py +38 -0
- src/model/encoder/heads/__init__.py +27 -0
- src/model/encoder/heads/dpt_block.py +459 -0
- src/model/encoder/heads/dpt_gs_head.py +284 -0
- src/model/encoder/heads/dpt_head.py +119 -0
- src/model/encoder/heads/head_modules.py +322 -0
- src/model/encoder/heads/linear_gs_head.py +383 -0
- src/model/encoder/heads/linear_head.py +73 -0
- src/model/encoder/heads/postprocess.py +77 -0
- src/model/encoder/heads/vggt_dpt_gs_head.py +195 -0
- src/model/encoder/vggt/heads/camera_head.py +168 -0
- src/model/encoder/vggt/heads/dpt_head.py +503 -0
- src/model/encoder/vggt/heads/head_act.py +125 -0
- src/model/encoder/vggt/heads/track_head.py +108 -0
src/misc/LocalLogger.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any, Optional
|
| 4 |
+
|
| 5 |
+
from lightning.pytorch.loggers.logger import Logger
|
| 6 |
+
from lightning.pytorch.utilities import rank_zero_only
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
LOG_PATH = Path("outputs/local")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LocalLogger(Logger):
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.experiment = None
|
| 16 |
+
os.system(f"rm -r {LOG_PATH}")
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def name(self):
|
| 20 |
+
return "LocalLogger"
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def version(self):
|
| 24 |
+
return 0
|
| 25 |
+
|
| 26 |
+
@rank_zero_only
|
| 27 |
+
def log_hyperparams(self, params):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
@rank_zero_only
|
| 31 |
+
def log_metrics(self, metrics, step):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
@rank_zero_only
|
| 35 |
+
def log_image(
|
| 36 |
+
self,
|
| 37 |
+
key: str,
|
| 38 |
+
images: list[Any],
|
| 39 |
+
step: Optional[int] = None,
|
| 40 |
+
**kwargs,
|
| 41 |
+
):
|
| 42 |
+
# The function signature is the same as the wandb logger's, but the step is
|
| 43 |
+
# actually required.
|
| 44 |
+
assert step is not None
|
| 45 |
+
for index, image in enumerate(images):
|
| 46 |
+
path = LOG_PATH / f"{key}/{index:0>2}_{step:0>6}.jpg"
|
| 47 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 48 |
+
Image.fromarray(image).save(path)
|
src/misc/image_io.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Union
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
import skvideo
|
| 9 |
+
import torch
|
| 10 |
+
import torchvision.transforms as tf
|
| 11 |
+
from einops import rearrange, repeat
|
| 12 |
+
from jaxtyping import Float, UInt8
|
| 13 |
+
|
| 14 |
+
from matplotlib import pyplot as plt
|
| 15 |
+
from matplotlib.figure import Figure
|
| 16 |
+
from PIL import Image
|
| 17 |
+
from torch import Tensor
|
| 18 |
+
|
| 19 |
+
FloatImage = Union[
|
| 20 |
+
Float[Tensor, "height width"],
|
| 21 |
+
Float[Tensor, "channel height width"],
|
| 22 |
+
Float[Tensor, "batch channel height width"],
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fig_to_image(
|
| 27 |
+
fig: Figure,
|
| 28 |
+
dpi: int = 100,
|
| 29 |
+
device: torch.device = torch.device("cpu"),
|
| 30 |
+
) -> Float[Tensor, "3 height width"]:
|
| 31 |
+
buffer = io.BytesIO()
|
| 32 |
+
fig.savefig(buffer, format="raw", dpi=dpi)
|
| 33 |
+
buffer.seek(0)
|
| 34 |
+
data = np.frombuffer(buffer.getvalue(), dtype=np.uint8)
|
| 35 |
+
h = int(fig.bbox.bounds[3])
|
| 36 |
+
w = int(fig.bbox.bounds[2])
|
| 37 |
+
data = rearrange(data, "(h w c) -> c h w", h=h, w=w, c=4)
|
| 38 |
+
buffer.close()
|
| 39 |
+
return (torch.tensor(data, device=device, dtype=torch.float32) / 255)[:3]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def prep_image(image: FloatImage) -> UInt8[np.ndarray, "height width channel"]:
|
| 43 |
+
# Handle batched images.
|
| 44 |
+
if image.ndim == 4:
|
| 45 |
+
image = rearrange(image, "b c h w -> c h (b w)")
|
| 46 |
+
|
| 47 |
+
# Handle single-channel images.
|
| 48 |
+
if image.ndim == 2:
|
| 49 |
+
image = rearrange(image, "h w -> () h w")
|
| 50 |
+
|
| 51 |
+
# Ensure that there are 3 or 4 channels.
|
| 52 |
+
channel, _, _ = image.shape
|
| 53 |
+
if channel == 1:
|
| 54 |
+
image = repeat(image, "() h w -> c h w", c=3)
|
| 55 |
+
assert image.shape[0] in (3, 4)
|
| 56 |
+
|
| 57 |
+
image = (image.detach().clip(min=0, max=1) * 255).type(torch.uint8)
|
| 58 |
+
return rearrange(image, "c h w -> h w c").cpu().numpy()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def save_image(
|
| 62 |
+
image: FloatImage,
|
| 63 |
+
path: Union[Path, str],
|
| 64 |
+
) -> None:
|
| 65 |
+
"""Save an image. Assumed to be in range 0-1."""
|
| 66 |
+
|
| 67 |
+
# Create the parent directory if it doesn't already exist.
|
| 68 |
+
path = Path(path)
|
| 69 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 70 |
+
|
| 71 |
+
# Save the image.
|
| 72 |
+
Image.fromarray(prep_image(image)).save(path)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_image(
|
| 76 |
+
path: Union[Path, str],
|
| 77 |
+
) -> Float[Tensor, "3 height width"]:
|
| 78 |
+
return tf.ToTensor()(Image.open(path))[:3]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def save_video(tensor, save_path, fps=10):
|
| 82 |
+
"""
|
| 83 |
+
Save a tensor of shape (N, C, H, W) as a video file using imageio.
|
| 84 |
+
Args:
|
| 85 |
+
tensor: Tensor of shape (N, C, H, W) in range [0, 1]
|
| 86 |
+
save_path: Path to save the video file
|
| 87 |
+
fps: Frames per second for the video
|
| 88 |
+
"""
|
| 89 |
+
# Convert tensor to numpy array and adjust dimensions
|
| 90 |
+
video = tensor.cpu().detach().numpy() # (N, C, H, W)
|
| 91 |
+
video = np.transpose(video, (0, 2, 3, 1)) # (N, H, W, C)
|
| 92 |
+
|
| 93 |
+
# Scale to [0, 255] and convert to uint8
|
| 94 |
+
video = (video * 255).astype(np.uint8)
|
| 95 |
+
|
| 96 |
+
# Ensure the directory exists
|
| 97 |
+
import os
|
| 98 |
+
|
| 99 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
| 100 |
+
|
| 101 |
+
# Use imageio to write video (handles codec compatibility automatically)
|
| 102 |
+
import imageio
|
| 103 |
+
|
| 104 |
+
writer = imageio.get_writer(save_path, fps=fps)
|
| 105 |
+
|
| 106 |
+
for frame in video:
|
| 107 |
+
writer.append_data(frame)
|
| 108 |
+
|
| 109 |
+
writer.close()
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def save_interpolated_video(
|
| 113 |
+
pred_extrinsics, pred_intrinsics, b, h, w, gaussians, save_path, decoder_func, t=10
|
| 114 |
+
):
|
| 115 |
+
# Interpolate between neighboring frames
|
| 116 |
+
# t: Number of extra views to interpolate between each pair
|
| 117 |
+
interpolated_extrinsics = []
|
| 118 |
+
interpolated_intrinsics = []
|
| 119 |
+
|
| 120 |
+
# For each pair of neighboring frame
|
| 121 |
+
for i in range(pred_extrinsics.shape[1] - 1):
|
| 122 |
+
# Add the current frame
|
| 123 |
+
interpolated_extrinsics.append(pred_extrinsics[:, i : i + 1])
|
| 124 |
+
interpolated_intrinsics.append(pred_intrinsics[:, i : i + 1])
|
| 125 |
+
|
| 126 |
+
# Interpolate between current and next frame
|
| 127 |
+
for j in range(1, t + 1):
|
| 128 |
+
alpha = j / (t + 1)
|
| 129 |
+
|
| 130 |
+
# Interpolate extrinsics
|
| 131 |
+
start_extrinsic = pred_extrinsics[:, i]
|
| 132 |
+
end_extrinsic = pred_extrinsics[:, i + 1]
|
| 133 |
+
|
| 134 |
+
# Separate rotation and translation
|
| 135 |
+
start_rot = start_extrinsic[:, :3, :3]
|
| 136 |
+
end_rot = end_extrinsic[:, :3, :3]
|
| 137 |
+
start_trans = start_extrinsic[:, :3, 3]
|
| 138 |
+
end_trans = end_extrinsic[:, :3, 3]
|
| 139 |
+
|
| 140 |
+
# Interpolate translation (linear)
|
| 141 |
+
interp_trans = (1 - alpha) * start_trans + alpha * end_trans
|
| 142 |
+
|
| 143 |
+
# Interpolate rotation (spherical)
|
| 144 |
+
start_rot_flat = start_rot.reshape(b, 9)
|
| 145 |
+
end_rot_flat = end_rot.reshape(b, 9)
|
| 146 |
+
interp_rot_flat = (1 - alpha) * start_rot_flat + alpha * end_rot_flat
|
| 147 |
+
interp_rot = interp_rot_flat.reshape(b, 3, 3)
|
| 148 |
+
|
| 149 |
+
# Normalize rotation matrix to ensure it's orthogonal
|
| 150 |
+
u, _, v = torch.svd(interp_rot)
|
| 151 |
+
interp_rot = torch.bmm(u, v.transpose(1, 2))
|
| 152 |
+
|
| 153 |
+
# Combine interpolated rotation and translation
|
| 154 |
+
interp_extrinsic = (
|
| 155 |
+
torch.eye(4, device=pred_extrinsics.device).unsqueeze(0).repeat(b, 1, 1)
|
| 156 |
+
)
|
| 157 |
+
interp_extrinsic[:, :3, :3] = interp_rot
|
| 158 |
+
interp_extrinsic[:, :3, 3] = interp_trans
|
| 159 |
+
|
| 160 |
+
# Interpolate intrinsics (linear)
|
| 161 |
+
start_intrinsic = pred_intrinsics[:, i]
|
| 162 |
+
end_intrinsic = pred_intrinsics[:, i + 1]
|
| 163 |
+
interp_intrinsic = (1 - alpha) * start_intrinsic + alpha * end_intrinsic
|
| 164 |
+
|
| 165 |
+
# Add interpolated frame
|
| 166 |
+
interpolated_extrinsics.append(interp_extrinsic.unsqueeze(1))
|
| 167 |
+
interpolated_intrinsics.append(interp_intrinsic.unsqueeze(1))
|
| 168 |
+
|
| 169 |
+
# Concatenate all frames
|
| 170 |
+
pred_all_extrinsic = torch.cat(interpolated_extrinsics, dim=1)
|
| 171 |
+
pred_all_intrinsic = torch.cat(interpolated_intrinsics, dim=1)
|
| 172 |
+
|
| 173 |
+
# Add the last frame
|
| 174 |
+
interpolated_extrinsics.append(pred_all_extrinsic[:, -1:])
|
| 175 |
+
interpolated_intrinsics.append(pred_all_intrinsic[:, -1:])
|
| 176 |
+
|
| 177 |
+
# Update K to reflect the new number of frames
|
| 178 |
+
num_frames = pred_all_extrinsic.shape[1]
|
| 179 |
+
|
| 180 |
+
# Render interpolated views
|
| 181 |
+
interpolated_output = decoder_func.forward(
|
| 182 |
+
gaussians,
|
| 183 |
+
pred_all_extrinsic,
|
| 184 |
+
pred_all_intrinsic.float(),
|
| 185 |
+
torch.ones(1, num_frames, device=pred_all_extrinsic.device) * 0.1,
|
| 186 |
+
torch.ones(1, num_frames, device=pred_all_extrinsic.device) * 100,
|
| 187 |
+
(h, w),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# Convert to video format
|
| 191 |
+
video = interpolated_output.color[0].clip(min=0, max=1)
|
| 192 |
+
depth = interpolated_output.depth[0]
|
| 193 |
+
|
| 194 |
+
# Normalize depth for visualization
|
| 195 |
+
# to avoid `quantile() input tensor is too large`
|
| 196 |
+
num_views = pred_extrinsics.shape[1]
|
| 197 |
+
depth_norm = (depth - depth[::num_views].quantile(0.01)) / (
|
| 198 |
+
depth[::num_views].quantile(0.99) - depth[::num_views].quantile(0.01)
|
| 199 |
+
)
|
| 200 |
+
depth_norm = plt.cm.turbo(depth_norm.cpu().numpy())
|
| 201 |
+
depth_colored = (
|
| 202 |
+
torch.from_numpy(depth_norm[..., :3]).permute(0, 3, 1, 2).to(depth.device)
|
| 203 |
+
)
|
| 204 |
+
depth_colored = depth_colored.clip(min=0, max=1)
|
| 205 |
+
|
| 206 |
+
# Save depth video
|
| 207 |
+
save_video(depth_colored, os.path.join(save_path, f"depth.mp4"))
|
| 208 |
+
# Save video
|
| 209 |
+
save_video(video, os.path.join(save_path, f"rgb.mp4"))
|
| 210 |
+
|
| 211 |
+
return os.path.join(save_path, f"rgb.mp4"), os.path.join(save_path, f"depth.mp4")
|
src/misc/nn_module_tools.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch import nn
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def convert_to_buffer(module: nn.Module, persistent: bool = True):
|
| 5 |
+
# Recurse over child modules.
|
| 6 |
+
for name, child in list(module.named_children()):
|
| 7 |
+
convert_to_buffer(child, persistent)
|
| 8 |
+
|
| 9 |
+
# Also re-save buffers to change persistence.
|
| 10 |
+
for name, parameter_or_buffer in (
|
| 11 |
+
*module.named_parameters(recurse=False),
|
| 12 |
+
*module.named_buffers(recurse=False),
|
| 13 |
+
):
|
| 14 |
+
value = parameter_or_buffer.detach().clone()
|
| 15 |
+
delattr(module, name)
|
| 16 |
+
module.register_buffer(name, value, persistent=persistent)
|
src/misc/sh_rotation.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import isqrt
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from e3nn.o3 import matrix_to_angles, wigner_D
|
| 5 |
+
from einops import einsum
|
| 6 |
+
from jaxtyping import Float
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def rotate_sh(
|
| 11 |
+
sh_coefficients: Float[Tensor, "*#batch n"],
|
| 12 |
+
rotations: Float[Tensor, "*#batch 3 3"],
|
| 13 |
+
) -> Float[Tensor, "*batch n"]:
|
| 14 |
+
device = sh_coefficients.device
|
| 15 |
+
dtype = sh_coefficients.dtype
|
| 16 |
+
|
| 17 |
+
# change the basis from YZX -> XYZ to fit the convention of e3nn
|
| 18 |
+
P = torch.tensor([[0, 0, 1], [1, 0, 0], [0, 1, 0]],
|
| 19 |
+
dtype=sh_coefficients.dtype, device=sh_coefficients.device)
|
| 20 |
+
inversed_P = torch.tensor([[0, 1, 0], [0, 0, 1], [1, 0, 0], ],
|
| 21 |
+
dtype=sh_coefficients.dtype, device=sh_coefficients.device)
|
| 22 |
+
permuted_rotation_matrix = inversed_P @ rotations @ P
|
| 23 |
+
|
| 24 |
+
*_, n = sh_coefficients.shape
|
| 25 |
+
alpha, beta, gamma = matrix_to_angles(permuted_rotation_matrix)
|
| 26 |
+
result = []
|
| 27 |
+
for degree in range(isqrt(n)):
|
| 28 |
+
with torch.device(device):
|
| 29 |
+
sh_rotations = wigner_D(degree, alpha, -beta, gamma).type(dtype)
|
| 30 |
+
sh_rotated = einsum(
|
| 31 |
+
sh_rotations,
|
| 32 |
+
sh_coefficients[..., degree**2 : (degree + 1) ** 2],
|
| 33 |
+
"... i j, ... j -> ... i",
|
| 34 |
+
)
|
| 35 |
+
result.append(sh_rotated)
|
| 36 |
+
|
| 37 |
+
return torch.cat(result, dim=-1)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# def rotate_sh(
|
| 41 |
+
# sh_coefficients: Float[Tensor, "*#batch n"],
|
| 42 |
+
# rotations: Float[Tensor, "*#batch 3 3"],
|
| 43 |
+
# ) -> Float[Tensor, "*batch n"]:
|
| 44 |
+
# device = sh_coefficients.device
|
| 45 |
+
# dtype = sh_coefficients.dtype
|
| 46 |
+
#
|
| 47 |
+
# *_, n = sh_coefficients.shape
|
| 48 |
+
# alpha, beta, gamma = matrix_to_angles(rotations)
|
| 49 |
+
# result = []
|
| 50 |
+
# for degree in range(isqrt(n)):
|
| 51 |
+
# with torch.device(device):
|
| 52 |
+
# sh_rotations = wigner_D(degree, alpha, beta, gamma).type(dtype)
|
| 53 |
+
# sh_rotated = einsum(
|
| 54 |
+
# sh_rotations,
|
| 55 |
+
# sh_coefficients[..., degree**2 : (degree + 1) ** 2],
|
| 56 |
+
# "... i j, ... j -> ... i",
|
| 57 |
+
# )
|
| 58 |
+
# result.append(sh_rotated)
|
| 59 |
+
#
|
| 60 |
+
# return torch.cat(result, dim=-1)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
from pathlib import Path
|
| 65 |
+
|
| 66 |
+
import matplotlib.pyplot as plt
|
| 67 |
+
from e3nn.o3 import spherical_harmonics
|
| 68 |
+
from matplotlib import cm
|
| 69 |
+
from scipy.spatial.transform.rotation import Rotation as R
|
| 70 |
+
|
| 71 |
+
device = torch.device("cuda")
|
| 72 |
+
|
| 73 |
+
# Generate random spherical harmonics coefficients.
|
| 74 |
+
degree = 4
|
| 75 |
+
coefficients = torch.rand((degree + 1) ** 2, dtype=torch.float32, device=device)
|
| 76 |
+
|
| 77 |
+
def plot_sh(sh_coefficients, path: Path) -> None:
|
| 78 |
+
phi = torch.linspace(0, torch.pi, 100, device=device)
|
| 79 |
+
theta = torch.linspace(0, 2 * torch.pi, 100, device=device)
|
| 80 |
+
phi, theta = torch.meshgrid(phi, theta, indexing="xy")
|
| 81 |
+
x = torch.sin(phi) * torch.cos(theta)
|
| 82 |
+
y = torch.sin(phi) * torch.sin(theta)
|
| 83 |
+
z = torch.cos(phi)
|
| 84 |
+
xyz = torch.stack([x, y, z], dim=-1)
|
| 85 |
+
sh = spherical_harmonics(list(range(degree + 1)), xyz, True)
|
| 86 |
+
result = einsum(sh, sh_coefficients, "... n, n -> ...")
|
| 87 |
+
result = (result - result.min()) / (result.max() - result.min())
|
| 88 |
+
|
| 89 |
+
# Set the aspect ratio to 1 so our sphere looks spherical
|
| 90 |
+
fig = plt.figure(figsize=plt.figaspect(1.0))
|
| 91 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 92 |
+
ax.plot_surface(
|
| 93 |
+
x.cpu().numpy(),
|
| 94 |
+
y.cpu().numpy(),
|
| 95 |
+
z.cpu().numpy(),
|
| 96 |
+
rstride=1,
|
| 97 |
+
cstride=1,
|
| 98 |
+
facecolors=cm.seismic(result.cpu().numpy()),
|
| 99 |
+
)
|
| 100 |
+
# Turn off the axis planes
|
| 101 |
+
ax.set_axis_off()
|
| 102 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 103 |
+
plt.savefig(path)
|
| 104 |
+
|
| 105 |
+
for i, angle in enumerate(torch.linspace(0, 2 * torch.pi, 30)):
|
| 106 |
+
rotation = torch.tensor(
|
| 107 |
+
R.from_euler("x", angle.item()).as_matrix(), device=device
|
| 108 |
+
)
|
| 109 |
+
plot_sh(rotate_sh(coefficients, rotation), Path(f"sh_rotation/{i:0>3}.png"))
|
| 110 |
+
|
| 111 |
+
print("Done!")
|
src/misc/sht.py
ADDED
|
@@ -0,0 +1,1637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real spherical harmonics in Cartesian form for PyTorch.
|
| 2 |
+
|
| 3 |
+
This is an autogenerated file. See
|
| 4 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 5 |
+
for more information.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def rsh_cart_0(xyz: torch.Tensor):
|
| 12 |
+
"""Computes all real spherical harmonics up to degree 0.
|
| 13 |
+
|
| 14 |
+
This is an autogenerated method. See
|
| 15 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 16 |
+
for more information.
|
| 17 |
+
|
| 18 |
+
Params:
|
| 19 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
rsh: (N,...,1) real spherical harmonics
|
| 23 |
+
projections of input. Ynm is found at index
|
| 24 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 25 |
+
`-n <= m <= n`.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
return torch.stack(
|
| 29 |
+
[
|
| 30 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 31 |
+
],
|
| 32 |
+
-1,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def rsh_cart_1(xyz: torch.Tensor):
|
| 37 |
+
"""Computes all real spherical harmonics up to degree 1.
|
| 38 |
+
|
| 39 |
+
This is an autogenerated method. See
|
| 40 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 41 |
+
for more information.
|
| 42 |
+
|
| 43 |
+
Params:
|
| 44 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
rsh: (N,...,4) real spherical harmonics
|
| 48 |
+
projections of input. Ynm is found at index
|
| 49 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 50 |
+
`-n <= m <= n`.
|
| 51 |
+
"""
|
| 52 |
+
x = xyz[..., 0]
|
| 53 |
+
y = xyz[..., 1]
|
| 54 |
+
z = xyz[..., 2]
|
| 55 |
+
|
| 56 |
+
return torch.stack(
|
| 57 |
+
[
|
| 58 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 59 |
+
-0.48860251190292 * y,
|
| 60 |
+
0.48860251190292 * z,
|
| 61 |
+
-0.48860251190292 * x,
|
| 62 |
+
],
|
| 63 |
+
-1,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rsh_cart_2(xyz: torch.Tensor):
|
| 68 |
+
"""Computes all real spherical harmonics up to degree 2.
|
| 69 |
+
|
| 70 |
+
This is an autogenerated method. See
|
| 71 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 72 |
+
for more information.
|
| 73 |
+
|
| 74 |
+
Params:
|
| 75 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
rsh: (N,...,9) real spherical harmonics
|
| 79 |
+
projections of input. Ynm is found at index
|
| 80 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 81 |
+
`-n <= m <= n`.
|
| 82 |
+
"""
|
| 83 |
+
x = xyz[..., 0]
|
| 84 |
+
y = xyz[..., 1]
|
| 85 |
+
z = xyz[..., 2]
|
| 86 |
+
|
| 87 |
+
x2 = x**2
|
| 88 |
+
y2 = y**2
|
| 89 |
+
z2 = z**2
|
| 90 |
+
xy = x * y
|
| 91 |
+
xz = x * z
|
| 92 |
+
yz = y * z
|
| 93 |
+
|
| 94 |
+
return torch.stack(
|
| 95 |
+
[
|
| 96 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 97 |
+
-0.48860251190292 * y,
|
| 98 |
+
0.48860251190292 * z,
|
| 99 |
+
-0.48860251190292 * x,
|
| 100 |
+
1.09254843059208 * xy,
|
| 101 |
+
-1.09254843059208 * yz,
|
| 102 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 103 |
+
-1.09254843059208 * xz,
|
| 104 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 105 |
+
],
|
| 106 |
+
-1,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def rsh_cart_3(xyz: torch.Tensor):
|
| 111 |
+
"""Computes all real spherical harmonics up to degree 3.
|
| 112 |
+
|
| 113 |
+
This is an autogenerated method. See
|
| 114 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 115 |
+
for more information.
|
| 116 |
+
|
| 117 |
+
Params:
|
| 118 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
rsh: (N,...,16) real spherical harmonics
|
| 122 |
+
projections of input. Ynm is found at index
|
| 123 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 124 |
+
`-n <= m <= n`.
|
| 125 |
+
"""
|
| 126 |
+
x = xyz[..., 0]
|
| 127 |
+
y = xyz[..., 1]
|
| 128 |
+
z = xyz[..., 2]
|
| 129 |
+
|
| 130 |
+
x2 = x**2
|
| 131 |
+
y2 = y**2
|
| 132 |
+
z2 = z**2
|
| 133 |
+
xy = x * y
|
| 134 |
+
xz = x * z
|
| 135 |
+
yz = y * z
|
| 136 |
+
|
| 137 |
+
return torch.stack(
|
| 138 |
+
[
|
| 139 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 140 |
+
-0.48860251190292 * y,
|
| 141 |
+
0.48860251190292 * z,
|
| 142 |
+
-0.48860251190292 * x,
|
| 143 |
+
1.09254843059208 * xy,
|
| 144 |
+
-1.09254843059208 * yz,
|
| 145 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 146 |
+
-1.09254843059208 * xz,
|
| 147 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 148 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 149 |
+
2.89061144264055 * xy * z,
|
| 150 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 151 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 152 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 153 |
+
1.44530572132028 * z * (x2 - y2),
|
| 154 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 155 |
+
],
|
| 156 |
+
-1,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def rsh_cart_4(xyz: torch.Tensor):
|
| 161 |
+
"""Computes all real spherical harmonics up to degree 4.
|
| 162 |
+
|
| 163 |
+
This is an autogenerated method. See
|
| 164 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 165 |
+
for more information.
|
| 166 |
+
|
| 167 |
+
Params:
|
| 168 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
rsh: (N,...,25) real spherical harmonics
|
| 172 |
+
projections of input. Ynm is found at index
|
| 173 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 174 |
+
`-n <= m <= n`.
|
| 175 |
+
"""
|
| 176 |
+
x = xyz[..., 0]
|
| 177 |
+
y = xyz[..., 1]
|
| 178 |
+
z = xyz[..., 2]
|
| 179 |
+
|
| 180 |
+
x2 = x**2
|
| 181 |
+
y2 = y**2
|
| 182 |
+
z2 = z**2
|
| 183 |
+
xy = x * y
|
| 184 |
+
xz = x * z
|
| 185 |
+
yz = y * z
|
| 186 |
+
x4 = x2**2
|
| 187 |
+
y4 = y2**2
|
| 188 |
+
z4 = z2**2
|
| 189 |
+
|
| 190 |
+
return torch.stack(
|
| 191 |
+
[
|
| 192 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 193 |
+
-0.48860251190292 * y,
|
| 194 |
+
0.48860251190292 * z,
|
| 195 |
+
-0.48860251190292 * x,
|
| 196 |
+
1.09254843059208 * xy,
|
| 197 |
+
-1.09254843059208 * yz,
|
| 198 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 199 |
+
-1.09254843059208 * xz,
|
| 200 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 201 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 202 |
+
2.89061144264055 * xy * z,
|
| 203 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 204 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 205 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 206 |
+
1.44530572132028 * z * (x2 - y2),
|
| 207 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 208 |
+
2.5033429417967 * xy * (x2 - y2),
|
| 209 |
+
-1.77013076977993 * yz * (3.0 * x2 - y2),
|
| 210 |
+
0.126156626101008 * xy * (52.5 * z2 - 7.5),
|
| 211 |
+
0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 212 |
+
1.48099765681286
|
| 213 |
+
* z
|
| 214 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 215 |
+
- 0.952069922236839 * z2
|
| 216 |
+
+ 0.317356640745613,
|
| 217 |
+
0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 218 |
+
0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5),
|
| 219 |
+
-1.77013076977993 * xz * (x2 - 3.0 * y2),
|
| 220 |
+
-3.75501441269506 * x2 * y2
|
| 221 |
+
+ 0.625835735449176 * x4
|
| 222 |
+
+ 0.625835735449176 * y4,
|
| 223 |
+
],
|
| 224 |
+
-1,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def rsh_cart_5(xyz: torch.Tensor):
|
| 229 |
+
"""Computes all real spherical harmonics up to degree 5.
|
| 230 |
+
|
| 231 |
+
This is an autogenerated method. See
|
| 232 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 233 |
+
for more information.
|
| 234 |
+
|
| 235 |
+
Params:
|
| 236 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 237 |
+
|
| 238 |
+
Returns:
|
| 239 |
+
rsh: (N,...,36) real spherical harmonics
|
| 240 |
+
projections of input. Ynm is found at index
|
| 241 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 242 |
+
`-n <= m <= n`.
|
| 243 |
+
"""
|
| 244 |
+
x = xyz[..., 0]
|
| 245 |
+
y = xyz[..., 1]
|
| 246 |
+
z = xyz[..., 2]
|
| 247 |
+
|
| 248 |
+
x2 = x**2
|
| 249 |
+
y2 = y**2
|
| 250 |
+
z2 = z**2
|
| 251 |
+
xy = x * y
|
| 252 |
+
xz = x * z
|
| 253 |
+
yz = y * z
|
| 254 |
+
x4 = x2**2
|
| 255 |
+
y4 = y2**2
|
| 256 |
+
z4 = z2**2
|
| 257 |
+
|
| 258 |
+
return torch.stack(
|
| 259 |
+
[
|
| 260 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 261 |
+
-0.48860251190292 * y,
|
| 262 |
+
0.48860251190292 * z,
|
| 263 |
+
-0.48860251190292 * x,
|
| 264 |
+
1.09254843059208 * xy,
|
| 265 |
+
-1.09254843059208 * yz,
|
| 266 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 267 |
+
-1.09254843059208 * xz,
|
| 268 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 269 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 270 |
+
2.89061144264055 * xy * z,
|
| 271 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 272 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 273 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 274 |
+
1.44530572132028 * z * (x2 - y2),
|
| 275 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 276 |
+
2.5033429417967 * xy * (x2 - y2),
|
| 277 |
+
-1.77013076977993 * yz * (3.0 * x2 - y2),
|
| 278 |
+
0.126156626101008 * xy * (52.5 * z2 - 7.5),
|
| 279 |
+
0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 280 |
+
1.48099765681286
|
| 281 |
+
* z
|
| 282 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 283 |
+
- 0.952069922236839 * z2
|
| 284 |
+
+ 0.317356640745613,
|
| 285 |
+
0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 286 |
+
0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5),
|
| 287 |
+
-1.77013076977993 * xz * (x2 - 3.0 * y2),
|
| 288 |
+
-3.75501441269506 * x2 * y2
|
| 289 |
+
+ 0.625835735449176 * x4
|
| 290 |
+
+ 0.625835735449176 * y4,
|
| 291 |
+
-0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 292 |
+
8.30264925952416 * xy * z * (x2 - y2),
|
| 293 |
+
0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2),
|
| 294 |
+
0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 295 |
+
0.241571547304372
|
| 296 |
+
* y
|
| 297 |
+
* (
|
| 298 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 299 |
+
+ 9.375 * z2
|
| 300 |
+
- 1.875
|
| 301 |
+
),
|
| 302 |
+
-1.24747010616985 * z * (1.5 * z2 - 0.5)
|
| 303 |
+
+ 1.6840846433293
|
| 304 |
+
* z
|
| 305 |
+
* (
|
| 306 |
+
1.75
|
| 307 |
+
* z
|
| 308 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 309 |
+
- 1.125 * z2
|
| 310 |
+
+ 0.375
|
| 311 |
+
)
|
| 312 |
+
+ 0.498988042467941 * z,
|
| 313 |
+
0.241571547304372
|
| 314 |
+
* x
|
| 315 |
+
* (
|
| 316 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 317 |
+
+ 9.375 * z2
|
| 318 |
+
- 1.875
|
| 319 |
+
),
|
| 320 |
+
0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 321 |
+
0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2),
|
| 322 |
+
2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4),
|
| 323 |
+
-0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 324 |
+
],
|
| 325 |
+
-1,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def rsh_cart_6(xyz: torch.Tensor):
|
| 330 |
+
"""Computes all real spherical harmonics up to degree 6.
|
| 331 |
+
|
| 332 |
+
This is an autogenerated method. See
|
| 333 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 334 |
+
for more information.
|
| 335 |
+
|
| 336 |
+
Params:
|
| 337 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
rsh: (N,...,49) real spherical harmonics
|
| 341 |
+
projections of input. Ynm is found at index
|
| 342 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 343 |
+
`-n <= m <= n`.
|
| 344 |
+
"""
|
| 345 |
+
x = xyz[..., 0]
|
| 346 |
+
y = xyz[..., 1]
|
| 347 |
+
z = xyz[..., 2]
|
| 348 |
+
|
| 349 |
+
x2 = x**2
|
| 350 |
+
y2 = y**2
|
| 351 |
+
z2 = z**2
|
| 352 |
+
xy = x * y
|
| 353 |
+
xz = x * z
|
| 354 |
+
yz = y * z
|
| 355 |
+
x4 = x2**2
|
| 356 |
+
y4 = y2**2
|
| 357 |
+
z4 = z2**2
|
| 358 |
+
|
| 359 |
+
return torch.stack(
|
| 360 |
+
[
|
| 361 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 362 |
+
-0.48860251190292 * y,
|
| 363 |
+
0.48860251190292 * z,
|
| 364 |
+
-0.48860251190292 * x,
|
| 365 |
+
1.09254843059208 * xy,
|
| 366 |
+
-1.09254843059208 * yz,
|
| 367 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 368 |
+
-1.09254843059208 * xz,
|
| 369 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 370 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 371 |
+
2.89061144264055 * xy * z,
|
| 372 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 373 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 374 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 375 |
+
1.44530572132028 * z * (x2 - y2),
|
| 376 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 377 |
+
2.5033429417967 * xy * (x2 - y2),
|
| 378 |
+
-1.77013076977993 * yz * (3.0 * x2 - y2),
|
| 379 |
+
0.126156626101008 * xy * (52.5 * z2 - 7.5),
|
| 380 |
+
0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 381 |
+
1.48099765681286
|
| 382 |
+
* z
|
| 383 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 384 |
+
- 0.952069922236839 * z2
|
| 385 |
+
+ 0.317356640745613,
|
| 386 |
+
0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 387 |
+
0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5),
|
| 388 |
+
-1.77013076977993 * xz * (x2 - 3.0 * y2),
|
| 389 |
+
-3.75501441269506 * x2 * y2
|
| 390 |
+
+ 0.625835735449176 * x4
|
| 391 |
+
+ 0.625835735449176 * y4,
|
| 392 |
+
-0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 393 |
+
8.30264925952416 * xy * z * (x2 - y2),
|
| 394 |
+
0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2),
|
| 395 |
+
0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 396 |
+
0.241571547304372
|
| 397 |
+
* y
|
| 398 |
+
* (
|
| 399 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 400 |
+
+ 9.375 * z2
|
| 401 |
+
- 1.875
|
| 402 |
+
),
|
| 403 |
+
-1.24747010616985 * z * (1.5 * z2 - 0.5)
|
| 404 |
+
+ 1.6840846433293
|
| 405 |
+
* z
|
| 406 |
+
* (
|
| 407 |
+
1.75
|
| 408 |
+
* z
|
| 409 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 410 |
+
- 1.125 * z2
|
| 411 |
+
+ 0.375
|
| 412 |
+
)
|
| 413 |
+
+ 0.498988042467941 * z,
|
| 414 |
+
0.241571547304372
|
| 415 |
+
* x
|
| 416 |
+
* (
|
| 417 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 418 |
+
+ 9.375 * z2
|
| 419 |
+
- 1.875
|
| 420 |
+
),
|
| 421 |
+
0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 422 |
+
0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2),
|
| 423 |
+
2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4),
|
| 424 |
+
-0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 425 |
+
4.09910463115149 * x**4 * xy
|
| 426 |
+
- 13.6636821038383 * xy**3
|
| 427 |
+
+ 4.09910463115149 * xy * y**4,
|
| 428 |
+
-2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 429 |
+
0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5),
|
| 430 |
+
0.00584892228263444
|
| 431 |
+
* y
|
| 432 |
+
* (3.0 * x2 - y2)
|
| 433 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 434 |
+
0.0701870673916132
|
| 435 |
+
* xy
|
| 436 |
+
* (
|
| 437 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 438 |
+
- 91.875 * z2
|
| 439 |
+
+ 13.125
|
| 440 |
+
),
|
| 441 |
+
0.221950995245231
|
| 442 |
+
* y
|
| 443 |
+
* (
|
| 444 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 445 |
+
+ 2.2
|
| 446 |
+
* z
|
| 447 |
+
* (
|
| 448 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 449 |
+
+ 9.375 * z2
|
| 450 |
+
- 1.875
|
| 451 |
+
)
|
| 452 |
+
- 4.8 * z
|
| 453 |
+
),
|
| 454 |
+
-1.48328138624466
|
| 455 |
+
* z
|
| 456 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 457 |
+
+ 1.86469659985043
|
| 458 |
+
* z
|
| 459 |
+
* (
|
| 460 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 461 |
+
+ 1.8
|
| 462 |
+
* z
|
| 463 |
+
* (
|
| 464 |
+
1.75
|
| 465 |
+
* z
|
| 466 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 467 |
+
- 1.125 * z2
|
| 468 |
+
+ 0.375
|
| 469 |
+
)
|
| 470 |
+
+ 0.533333333333333 * z
|
| 471 |
+
)
|
| 472 |
+
+ 0.953538034014426 * z2
|
| 473 |
+
- 0.317846011338142,
|
| 474 |
+
0.221950995245231
|
| 475 |
+
* x
|
| 476 |
+
* (
|
| 477 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 478 |
+
+ 2.2
|
| 479 |
+
* z
|
| 480 |
+
* (
|
| 481 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 482 |
+
+ 9.375 * z2
|
| 483 |
+
- 1.875
|
| 484 |
+
)
|
| 485 |
+
- 4.8 * z
|
| 486 |
+
),
|
| 487 |
+
0.0350935336958066
|
| 488 |
+
* (x2 - y2)
|
| 489 |
+
* (
|
| 490 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 491 |
+
- 91.875 * z2
|
| 492 |
+
+ 13.125
|
| 493 |
+
),
|
| 494 |
+
0.00584892228263444
|
| 495 |
+
* x
|
| 496 |
+
* (x2 - 3.0 * y2)
|
| 497 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 498 |
+
0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4),
|
| 499 |
+
-2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 500 |
+
0.683184105191914 * x2**3
|
| 501 |
+
+ 10.2477615778787 * x2 * y4
|
| 502 |
+
- 10.2477615778787 * x4 * y2
|
| 503 |
+
- 0.683184105191914 * y2**3,
|
| 504 |
+
],
|
| 505 |
+
-1,
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def rsh_cart_7(xyz: torch.Tensor):
|
| 510 |
+
"""Computes all real spherical harmonics up to degree 7.
|
| 511 |
+
|
| 512 |
+
This is an autogenerated method. See
|
| 513 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 514 |
+
for more information.
|
| 515 |
+
|
| 516 |
+
Params:
|
| 517 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 518 |
+
|
| 519 |
+
Returns:
|
| 520 |
+
rsh: (N,...,64) real spherical harmonics
|
| 521 |
+
projections of input. Ynm is found at index
|
| 522 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 523 |
+
`-n <= m <= n`.
|
| 524 |
+
"""
|
| 525 |
+
x = xyz[..., 0]
|
| 526 |
+
y = xyz[..., 1]
|
| 527 |
+
z = xyz[..., 2]
|
| 528 |
+
|
| 529 |
+
x2 = x**2
|
| 530 |
+
y2 = y**2
|
| 531 |
+
z2 = z**2
|
| 532 |
+
xy = x * y
|
| 533 |
+
xz = x * z
|
| 534 |
+
yz = y * z
|
| 535 |
+
x4 = x2**2
|
| 536 |
+
y4 = y2**2
|
| 537 |
+
z4 = z2**2
|
| 538 |
+
|
| 539 |
+
return torch.stack(
|
| 540 |
+
[
|
| 541 |
+
xyz.new_tensor(0.282094791773878).expand(xyz.shape[:-1]),
|
| 542 |
+
-0.48860251190292 * y,
|
| 543 |
+
0.48860251190292 * z,
|
| 544 |
+
-0.48860251190292 * x,
|
| 545 |
+
1.09254843059208 * xy,
|
| 546 |
+
-1.09254843059208 * yz,
|
| 547 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 548 |
+
-1.09254843059208 * xz,
|
| 549 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 550 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 551 |
+
2.89061144264055 * xy * z,
|
| 552 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 553 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 554 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 555 |
+
1.44530572132028 * z * (x2 - y2),
|
| 556 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 557 |
+
2.5033429417967 * xy * (x2 - y2),
|
| 558 |
+
-1.77013076977993 * yz * (3.0 * x2 - y2),
|
| 559 |
+
0.126156626101008 * xy * (52.5 * z2 - 7.5),
|
| 560 |
+
0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 561 |
+
1.48099765681286
|
| 562 |
+
* z
|
| 563 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 564 |
+
- 0.952069922236839 * z2
|
| 565 |
+
+ 0.317356640745613,
|
| 566 |
+
0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 567 |
+
0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5),
|
| 568 |
+
-1.77013076977993 * xz * (x2 - 3.0 * y2),
|
| 569 |
+
-3.75501441269506 * x2 * y2
|
| 570 |
+
+ 0.625835735449176 * x4
|
| 571 |
+
+ 0.625835735449176 * y4,
|
| 572 |
+
-0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 573 |
+
8.30264925952416 * xy * z * (x2 - y2),
|
| 574 |
+
0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2),
|
| 575 |
+
0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 576 |
+
0.241571547304372
|
| 577 |
+
* y
|
| 578 |
+
* (
|
| 579 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 580 |
+
+ 9.375 * z2
|
| 581 |
+
- 1.875
|
| 582 |
+
),
|
| 583 |
+
-1.24747010616985 * z * (1.5 * z2 - 0.5)
|
| 584 |
+
+ 1.6840846433293
|
| 585 |
+
* z
|
| 586 |
+
* (
|
| 587 |
+
1.75
|
| 588 |
+
* z
|
| 589 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 590 |
+
- 1.125 * z2
|
| 591 |
+
+ 0.375
|
| 592 |
+
)
|
| 593 |
+
+ 0.498988042467941 * z,
|
| 594 |
+
0.241571547304372
|
| 595 |
+
* x
|
| 596 |
+
* (
|
| 597 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 598 |
+
+ 9.375 * z2
|
| 599 |
+
- 1.875
|
| 600 |
+
),
|
| 601 |
+
0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 602 |
+
0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2),
|
| 603 |
+
2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4),
|
| 604 |
+
-0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 605 |
+
4.09910463115149 * x**4 * xy
|
| 606 |
+
- 13.6636821038383 * xy**3
|
| 607 |
+
+ 4.09910463115149 * xy * y**4,
|
| 608 |
+
-2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 609 |
+
0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5),
|
| 610 |
+
0.00584892228263444
|
| 611 |
+
* y
|
| 612 |
+
* (3.0 * x2 - y2)
|
| 613 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 614 |
+
0.0701870673916132
|
| 615 |
+
* xy
|
| 616 |
+
* (
|
| 617 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 618 |
+
- 91.875 * z2
|
| 619 |
+
+ 13.125
|
| 620 |
+
),
|
| 621 |
+
0.221950995245231
|
| 622 |
+
* y
|
| 623 |
+
* (
|
| 624 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 625 |
+
+ 2.2
|
| 626 |
+
* z
|
| 627 |
+
* (
|
| 628 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 629 |
+
+ 9.375 * z2
|
| 630 |
+
- 1.875
|
| 631 |
+
)
|
| 632 |
+
- 4.8 * z
|
| 633 |
+
),
|
| 634 |
+
-1.48328138624466
|
| 635 |
+
* z
|
| 636 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 637 |
+
+ 1.86469659985043
|
| 638 |
+
* z
|
| 639 |
+
* (
|
| 640 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 641 |
+
+ 1.8
|
| 642 |
+
* z
|
| 643 |
+
* (
|
| 644 |
+
1.75
|
| 645 |
+
* z
|
| 646 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 647 |
+
- 1.125 * z2
|
| 648 |
+
+ 0.375
|
| 649 |
+
)
|
| 650 |
+
+ 0.533333333333333 * z
|
| 651 |
+
)
|
| 652 |
+
+ 0.953538034014426 * z2
|
| 653 |
+
- 0.317846011338142,
|
| 654 |
+
0.221950995245231
|
| 655 |
+
* x
|
| 656 |
+
* (
|
| 657 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 658 |
+
+ 2.2
|
| 659 |
+
* z
|
| 660 |
+
* (
|
| 661 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 662 |
+
+ 9.375 * z2
|
| 663 |
+
- 1.875
|
| 664 |
+
)
|
| 665 |
+
- 4.8 * z
|
| 666 |
+
),
|
| 667 |
+
0.0350935336958066
|
| 668 |
+
* (x2 - y2)
|
| 669 |
+
* (
|
| 670 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 671 |
+
- 91.875 * z2
|
| 672 |
+
+ 13.125
|
| 673 |
+
),
|
| 674 |
+
0.00584892228263444
|
| 675 |
+
* x
|
| 676 |
+
* (x2 - 3.0 * y2)
|
| 677 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 678 |
+
0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4),
|
| 679 |
+
-2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 680 |
+
0.683184105191914 * x2**3
|
| 681 |
+
+ 10.2477615778787 * x2 * y4
|
| 682 |
+
- 10.2477615778787 * x4 * y2
|
| 683 |
+
- 0.683184105191914 * y2**3,
|
| 684 |
+
-0.707162732524596
|
| 685 |
+
* y
|
| 686 |
+
* (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3),
|
| 687 |
+
2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4),
|
| 688 |
+
9.98394571852353e-5
|
| 689 |
+
* y
|
| 690 |
+
* (5197.5 - 67567.5 * z2)
|
| 691 |
+
* (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 692 |
+
0.00239614697244565
|
| 693 |
+
* xy
|
| 694 |
+
* (x2 - y2)
|
| 695 |
+
* (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z),
|
| 696 |
+
0.00397356022507413
|
| 697 |
+
* y
|
| 698 |
+
* (3.0 * x2 - y2)
|
| 699 |
+
* (
|
| 700 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 701 |
+
+ 1063.125 * z2
|
| 702 |
+
- 118.125
|
| 703 |
+
),
|
| 704 |
+
0.0561946276120613
|
| 705 |
+
* xy
|
| 706 |
+
* (
|
| 707 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 708 |
+
+ 2.6
|
| 709 |
+
* z
|
| 710 |
+
* (
|
| 711 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 712 |
+
- 91.875 * z2
|
| 713 |
+
+ 13.125
|
| 714 |
+
)
|
| 715 |
+
+ 48.0 * z
|
| 716 |
+
),
|
| 717 |
+
0.206472245902897
|
| 718 |
+
* y
|
| 719 |
+
* (
|
| 720 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 721 |
+
+ 2.16666666666667
|
| 722 |
+
* z
|
| 723 |
+
* (
|
| 724 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 725 |
+
+ 2.2
|
| 726 |
+
* z
|
| 727 |
+
* (
|
| 728 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 729 |
+
+ 9.375 * z2
|
| 730 |
+
- 1.875
|
| 731 |
+
)
|
| 732 |
+
- 4.8 * z
|
| 733 |
+
)
|
| 734 |
+
- 10.9375 * z2
|
| 735 |
+
+ 2.1875
|
| 736 |
+
),
|
| 737 |
+
1.24862677781952 * z * (1.5 * z2 - 0.5)
|
| 738 |
+
- 1.68564615005635
|
| 739 |
+
* z
|
| 740 |
+
* (
|
| 741 |
+
1.75
|
| 742 |
+
* z
|
| 743 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 744 |
+
- 1.125 * z2
|
| 745 |
+
+ 0.375
|
| 746 |
+
)
|
| 747 |
+
+ 2.02901851395672
|
| 748 |
+
* z
|
| 749 |
+
* (
|
| 750 |
+
-1.45833333333333
|
| 751 |
+
* z
|
| 752 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 753 |
+
+ 1.83333333333333
|
| 754 |
+
* z
|
| 755 |
+
* (
|
| 756 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 757 |
+
+ 1.8
|
| 758 |
+
* z
|
| 759 |
+
* (
|
| 760 |
+
1.75
|
| 761 |
+
* z
|
| 762 |
+
* (
|
| 763 |
+
1.66666666666667 * z * (1.5 * z2 - 0.5)
|
| 764 |
+
- 0.666666666666667 * z
|
| 765 |
+
)
|
| 766 |
+
- 1.125 * z2
|
| 767 |
+
+ 0.375
|
| 768 |
+
)
|
| 769 |
+
+ 0.533333333333333 * z
|
| 770 |
+
)
|
| 771 |
+
+ 0.9375 * z2
|
| 772 |
+
- 0.3125
|
| 773 |
+
)
|
| 774 |
+
- 0.499450711127808 * z,
|
| 775 |
+
0.206472245902897
|
| 776 |
+
* x
|
| 777 |
+
* (
|
| 778 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 779 |
+
+ 2.16666666666667
|
| 780 |
+
* z
|
| 781 |
+
* (
|
| 782 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 783 |
+
+ 2.2
|
| 784 |
+
* z
|
| 785 |
+
* (
|
| 786 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 787 |
+
+ 9.375 * z2
|
| 788 |
+
- 1.875
|
| 789 |
+
)
|
| 790 |
+
- 4.8 * z
|
| 791 |
+
)
|
| 792 |
+
- 10.9375 * z2
|
| 793 |
+
+ 2.1875
|
| 794 |
+
),
|
| 795 |
+
0.0280973138060306
|
| 796 |
+
* (x2 - y2)
|
| 797 |
+
* (
|
| 798 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 799 |
+
+ 2.6
|
| 800 |
+
* z
|
| 801 |
+
* (
|
| 802 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 803 |
+
- 91.875 * z2
|
| 804 |
+
+ 13.125
|
| 805 |
+
)
|
| 806 |
+
+ 48.0 * z
|
| 807 |
+
),
|
| 808 |
+
0.00397356022507413
|
| 809 |
+
* x
|
| 810 |
+
* (x2 - 3.0 * y2)
|
| 811 |
+
* (
|
| 812 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 813 |
+
+ 1063.125 * z2
|
| 814 |
+
- 118.125
|
| 815 |
+
),
|
| 816 |
+
0.000599036743111412
|
| 817 |
+
* (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z)
|
| 818 |
+
* (-6.0 * x2 * y2 + x4 + y4),
|
| 819 |
+
9.98394571852353e-5
|
| 820 |
+
* x
|
| 821 |
+
* (5197.5 - 67567.5 * z2)
|
| 822 |
+
* (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 823 |
+
2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3),
|
| 824 |
+
-0.707162732524596
|
| 825 |
+
* x
|
| 826 |
+
* (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3),
|
| 827 |
+
],
|
| 828 |
+
-1,
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
# @torch.jit.script
|
| 833 |
+
def rsh_cart_8(xyz: torch.Tensor):
|
| 834 |
+
"""Computes all real spherical harmonics up to degree 8.
|
| 835 |
+
|
| 836 |
+
This is an autogenerated method. See
|
| 837 |
+
https://github.com/cheind/torch-spherical-harmonics
|
| 838 |
+
for more information.
|
| 839 |
+
|
| 840 |
+
Params:
|
| 841 |
+
xyz: (N,...,3) tensor of points on the unit sphere
|
| 842 |
+
|
| 843 |
+
Returns:
|
| 844 |
+
rsh: (N,...,81) real spherical harmonics
|
| 845 |
+
projections of input. Ynm is found at index
|
| 846 |
+
`n*(n+1) + m`, with `0 <= n <= degree` and
|
| 847 |
+
`-n <= m <= n`.
|
| 848 |
+
"""
|
| 849 |
+
x = xyz[..., 0]
|
| 850 |
+
y = xyz[..., 1]
|
| 851 |
+
z = xyz[..., 2]
|
| 852 |
+
|
| 853 |
+
x2 = x**2
|
| 854 |
+
y2 = y**2
|
| 855 |
+
z2 = z**2
|
| 856 |
+
xy = x * y
|
| 857 |
+
xz = x * z
|
| 858 |
+
yz = y * z
|
| 859 |
+
x4 = x2**2
|
| 860 |
+
y4 = y2**2
|
| 861 |
+
# z4 = z2**2
|
| 862 |
+
return torch.stack(
|
| 863 |
+
[
|
| 864 |
+
0.282094791773878 * torch.ones(1, device=xyz.device).expand(xyz.shape[:-1]),
|
| 865 |
+
-0.48860251190292 * y,
|
| 866 |
+
0.48860251190292 * z,
|
| 867 |
+
-0.48860251190292 * x,
|
| 868 |
+
1.09254843059208 * xy,
|
| 869 |
+
-1.09254843059208 * yz,
|
| 870 |
+
0.94617469575756 * z2 - 0.31539156525252,
|
| 871 |
+
-1.09254843059208 * xz,
|
| 872 |
+
0.54627421529604 * x2 - 0.54627421529604 * y2,
|
| 873 |
+
-0.590043589926644 * y * (3.0 * x2 - y2),
|
| 874 |
+
2.89061144264055 * xy * z,
|
| 875 |
+
0.304697199642977 * y * (1.5 - 7.5 * z2),
|
| 876 |
+
1.24392110863372 * z * (1.5 * z2 - 0.5) - 0.497568443453487 * z,
|
| 877 |
+
0.304697199642977 * x * (1.5 - 7.5 * z2),
|
| 878 |
+
1.44530572132028 * z * (x2 - y2),
|
| 879 |
+
-0.590043589926644 * x * (x2 - 3.0 * y2),
|
| 880 |
+
2.5033429417967 * xy * (x2 - y2),
|
| 881 |
+
-1.77013076977993 * yz * (3.0 * x2 - y2),
|
| 882 |
+
0.126156626101008 * xy * (52.5 * z2 - 7.5),
|
| 883 |
+
0.267618617422916 * y * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 884 |
+
1.48099765681286
|
| 885 |
+
* z
|
| 886 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 887 |
+
- 0.952069922236839 * z2
|
| 888 |
+
+ 0.317356640745613,
|
| 889 |
+
0.267618617422916 * x * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z),
|
| 890 |
+
0.063078313050504 * (x2 - y2) * (52.5 * z2 - 7.5),
|
| 891 |
+
-1.77013076977993 * xz * (x2 - 3.0 * y2),
|
| 892 |
+
-3.75501441269506 * x2 * y2
|
| 893 |
+
+ 0.625835735449176 * x4
|
| 894 |
+
+ 0.625835735449176 * y4,
|
| 895 |
+
-0.65638205684017 * y * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 896 |
+
8.30264925952416 * xy * z * (x2 - y2),
|
| 897 |
+
0.00931882475114763 * y * (52.5 - 472.5 * z2) * (3.0 * x2 - y2),
|
| 898 |
+
0.0913054625709205 * xy * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 899 |
+
0.241571547304372
|
| 900 |
+
* y
|
| 901 |
+
* (
|
| 902 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 903 |
+
+ 9.375 * z2
|
| 904 |
+
- 1.875
|
| 905 |
+
),
|
| 906 |
+
-1.24747010616985 * z * (1.5 * z2 - 0.5)
|
| 907 |
+
+ 1.6840846433293
|
| 908 |
+
* z
|
| 909 |
+
* (
|
| 910 |
+
1.75
|
| 911 |
+
* z
|
| 912 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 913 |
+
- 1.125 * z2
|
| 914 |
+
+ 0.375
|
| 915 |
+
)
|
| 916 |
+
+ 0.498988042467941 * z,
|
| 917 |
+
0.241571547304372
|
| 918 |
+
* x
|
| 919 |
+
* (
|
| 920 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 921 |
+
+ 9.375 * z2
|
| 922 |
+
- 1.875
|
| 923 |
+
),
|
| 924 |
+
0.0456527312854602 * (x2 - y2) * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z),
|
| 925 |
+
0.00931882475114763 * x * (52.5 - 472.5 * z2) * (x2 - 3.0 * y2),
|
| 926 |
+
2.07566231488104 * z * (-6.0 * x2 * y2 + x4 + y4),
|
| 927 |
+
-0.65638205684017 * x * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 928 |
+
4.09910463115149 * x**4 * xy
|
| 929 |
+
- 13.6636821038383 * xy**3
|
| 930 |
+
+ 4.09910463115149 * xy * y**4,
|
| 931 |
+
-2.36661916223175 * yz * (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 932 |
+
0.00427144889505798 * xy * (x2 - y2) * (5197.5 * z2 - 472.5),
|
| 933 |
+
0.00584892228263444
|
| 934 |
+
* y
|
| 935 |
+
* (3.0 * x2 - y2)
|
| 936 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 937 |
+
0.0701870673916132
|
| 938 |
+
* xy
|
| 939 |
+
* (
|
| 940 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 941 |
+
- 91.875 * z2
|
| 942 |
+
+ 13.125
|
| 943 |
+
),
|
| 944 |
+
0.221950995245231
|
| 945 |
+
* y
|
| 946 |
+
* (
|
| 947 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 948 |
+
+ 2.2
|
| 949 |
+
* z
|
| 950 |
+
* (
|
| 951 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 952 |
+
+ 9.375 * z2
|
| 953 |
+
- 1.875
|
| 954 |
+
)
|
| 955 |
+
- 4.8 * z
|
| 956 |
+
),
|
| 957 |
+
-1.48328138624466
|
| 958 |
+
* z
|
| 959 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 960 |
+
+ 1.86469659985043
|
| 961 |
+
* z
|
| 962 |
+
* (
|
| 963 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 964 |
+
+ 1.8
|
| 965 |
+
* z
|
| 966 |
+
* (
|
| 967 |
+
1.75
|
| 968 |
+
* z
|
| 969 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 970 |
+
- 1.125 * z2
|
| 971 |
+
+ 0.375
|
| 972 |
+
)
|
| 973 |
+
+ 0.533333333333333 * z
|
| 974 |
+
)
|
| 975 |
+
+ 0.953538034014426 * z2
|
| 976 |
+
- 0.317846011338142,
|
| 977 |
+
0.221950995245231
|
| 978 |
+
* x
|
| 979 |
+
* (
|
| 980 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 981 |
+
+ 2.2
|
| 982 |
+
* z
|
| 983 |
+
* (
|
| 984 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 985 |
+
+ 9.375 * z2
|
| 986 |
+
- 1.875
|
| 987 |
+
)
|
| 988 |
+
- 4.8 * z
|
| 989 |
+
),
|
| 990 |
+
0.0350935336958066
|
| 991 |
+
* (x2 - y2)
|
| 992 |
+
* (
|
| 993 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 994 |
+
- 91.875 * z2
|
| 995 |
+
+ 13.125
|
| 996 |
+
),
|
| 997 |
+
0.00584892228263444
|
| 998 |
+
* x
|
| 999 |
+
* (x2 - 3.0 * y2)
|
| 1000 |
+
* (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z),
|
| 1001 |
+
0.0010678622237645 * (5197.5 * z2 - 472.5) * (-6.0 * x2 * y2 + x4 + y4),
|
| 1002 |
+
-2.36661916223175 * xz * (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 1003 |
+
0.683184105191914 * x2**3
|
| 1004 |
+
+ 10.2477615778787 * x2 * y4
|
| 1005 |
+
- 10.2477615778787 * x4 * y2
|
| 1006 |
+
- 0.683184105191914 * y2**3,
|
| 1007 |
+
-0.707162732524596
|
| 1008 |
+
* y
|
| 1009 |
+
* (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3),
|
| 1010 |
+
2.6459606618019 * z * (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4),
|
| 1011 |
+
9.98394571852353e-5
|
| 1012 |
+
* y
|
| 1013 |
+
* (5197.5 - 67567.5 * z2)
|
| 1014 |
+
* (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 1015 |
+
0.00239614697244565
|
| 1016 |
+
* xy
|
| 1017 |
+
* (x2 - y2)
|
| 1018 |
+
* (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z),
|
| 1019 |
+
0.00397356022507413
|
| 1020 |
+
* y
|
| 1021 |
+
* (3.0 * x2 - y2)
|
| 1022 |
+
* (
|
| 1023 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 1024 |
+
+ 1063.125 * z2
|
| 1025 |
+
- 118.125
|
| 1026 |
+
),
|
| 1027 |
+
0.0561946276120613
|
| 1028 |
+
* xy
|
| 1029 |
+
* (
|
| 1030 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 1031 |
+
+ 2.6
|
| 1032 |
+
* z
|
| 1033 |
+
* (
|
| 1034 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1035 |
+
- 91.875 * z2
|
| 1036 |
+
+ 13.125
|
| 1037 |
+
)
|
| 1038 |
+
+ 48.0 * z
|
| 1039 |
+
),
|
| 1040 |
+
0.206472245902897
|
| 1041 |
+
* y
|
| 1042 |
+
* (
|
| 1043 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1044 |
+
+ 2.16666666666667
|
| 1045 |
+
* z
|
| 1046 |
+
* (
|
| 1047 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 1048 |
+
+ 2.2
|
| 1049 |
+
* z
|
| 1050 |
+
* (
|
| 1051 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1052 |
+
+ 9.375 * z2
|
| 1053 |
+
- 1.875
|
| 1054 |
+
)
|
| 1055 |
+
- 4.8 * z
|
| 1056 |
+
)
|
| 1057 |
+
- 10.9375 * z2
|
| 1058 |
+
+ 2.1875
|
| 1059 |
+
),
|
| 1060 |
+
1.24862677781952 * z * (1.5 * z2 - 0.5)
|
| 1061 |
+
- 1.68564615005635
|
| 1062 |
+
* z
|
| 1063 |
+
* (
|
| 1064 |
+
1.75
|
| 1065 |
+
* z
|
| 1066 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1067 |
+
- 1.125 * z2
|
| 1068 |
+
+ 0.375
|
| 1069 |
+
)
|
| 1070 |
+
+ 2.02901851395672
|
| 1071 |
+
* z
|
| 1072 |
+
* (
|
| 1073 |
+
-1.45833333333333
|
| 1074 |
+
* z
|
| 1075 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1076 |
+
+ 1.83333333333333
|
| 1077 |
+
* z
|
| 1078 |
+
* (
|
| 1079 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 1080 |
+
+ 1.8
|
| 1081 |
+
* z
|
| 1082 |
+
* (
|
| 1083 |
+
1.75
|
| 1084 |
+
* z
|
| 1085 |
+
* (
|
| 1086 |
+
1.66666666666667 * z * (1.5 * z2 - 0.5)
|
| 1087 |
+
- 0.666666666666667 * z
|
| 1088 |
+
)
|
| 1089 |
+
- 1.125 * z2
|
| 1090 |
+
+ 0.375
|
| 1091 |
+
)
|
| 1092 |
+
+ 0.533333333333333 * z
|
| 1093 |
+
)
|
| 1094 |
+
+ 0.9375 * z2
|
| 1095 |
+
- 0.3125
|
| 1096 |
+
)
|
| 1097 |
+
- 0.499450711127808 * z,
|
| 1098 |
+
0.206472245902897
|
| 1099 |
+
* x
|
| 1100 |
+
* (
|
| 1101 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1102 |
+
+ 2.16666666666667
|
| 1103 |
+
* z
|
| 1104 |
+
* (
|
| 1105 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 1106 |
+
+ 2.2
|
| 1107 |
+
* z
|
| 1108 |
+
* (
|
| 1109 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1110 |
+
+ 9.375 * z2
|
| 1111 |
+
- 1.875
|
| 1112 |
+
)
|
| 1113 |
+
- 4.8 * z
|
| 1114 |
+
)
|
| 1115 |
+
- 10.9375 * z2
|
| 1116 |
+
+ 2.1875
|
| 1117 |
+
),
|
| 1118 |
+
0.0280973138060306
|
| 1119 |
+
* (x2 - y2)
|
| 1120 |
+
* (
|
| 1121 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 1122 |
+
+ 2.6
|
| 1123 |
+
* z
|
| 1124 |
+
* (
|
| 1125 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1126 |
+
- 91.875 * z2
|
| 1127 |
+
+ 13.125
|
| 1128 |
+
)
|
| 1129 |
+
+ 48.0 * z
|
| 1130 |
+
),
|
| 1131 |
+
0.00397356022507413
|
| 1132 |
+
* x
|
| 1133 |
+
* (x2 - 3.0 * y2)
|
| 1134 |
+
* (
|
| 1135 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 1136 |
+
+ 1063.125 * z2
|
| 1137 |
+
- 118.125
|
| 1138 |
+
),
|
| 1139 |
+
0.000599036743111412
|
| 1140 |
+
* (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z)
|
| 1141 |
+
* (-6.0 * x2 * y2 + x4 + y4),
|
| 1142 |
+
9.98394571852353e-5
|
| 1143 |
+
* x
|
| 1144 |
+
* (5197.5 - 67567.5 * z2)
|
| 1145 |
+
* (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 1146 |
+
2.6459606618019 * z * (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3),
|
| 1147 |
+
-0.707162732524596
|
| 1148 |
+
* x
|
| 1149 |
+
* (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3),
|
| 1150 |
+
5.83141328139864 * xy * (x2**3 + 7.0 * x2 * y4 - 7.0 * x4 * y2 - y2**3),
|
| 1151 |
+
-2.91570664069932
|
| 1152 |
+
* yz
|
| 1153 |
+
* (7.0 * x2**3 + 21.0 * x2 * y4 - 35.0 * x4 * y2 - y2**3),
|
| 1154 |
+
7.87853281621404e-6
|
| 1155 |
+
* (1013512.5 * z2 - 67567.5)
|
| 1156 |
+
* (6.0 * x**4 * xy - 20.0 * xy**3 + 6.0 * xy * y**4),
|
| 1157 |
+
5.10587282657803e-5
|
| 1158 |
+
* y
|
| 1159 |
+
* (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z)
|
| 1160 |
+
* (-10.0 * x2 * y2 + 5.0 * x4 + y4),
|
| 1161 |
+
0.00147275890257803
|
| 1162 |
+
* xy
|
| 1163 |
+
* (x2 - y2)
|
| 1164 |
+
* (
|
| 1165 |
+
3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z)
|
| 1166 |
+
- 14293.125 * z2
|
| 1167 |
+
+ 1299.375
|
| 1168 |
+
),
|
| 1169 |
+
0.0028519853513317
|
| 1170 |
+
* y
|
| 1171 |
+
* (3.0 * x2 - y2)
|
| 1172 |
+
* (
|
| 1173 |
+
-7.33333333333333 * z * (52.5 - 472.5 * z2)
|
| 1174 |
+
+ 3.0
|
| 1175 |
+
* z
|
| 1176 |
+
* (
|
| 1177 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 1178 |
+
+ 1063.125 * z2
|
| 1179 |
+
- 118.125
|
| 1180 |
+
)
|
| 1181 |
+
- 560.0 * z
|
| 1182 |
+
),
|
| 1183 |
+
0.0463392770473559
|
| 1184 |
+
* xy
|
| 1185 |
+
* (
|
| 1186 |
+
-4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1187 |
+
+ 2.5
|
| 1188 |
+
* z
|
| 1189 |
+
* (
|
| 1190 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 1191 |
+
+ 2.6
|
| 1192 |
+
* z
|
| 1193 |
+
* (
|
| 1194 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1195 |
+
- 91.875 * z2
|
| 1196 |
+
+ 13.125
|
| 1197 |
+
)
|
| 1198 |
+
+ 48.0 * z
|
| 1199 |
+
)
|
| 1200 |
+
+ 137.8125 * z2
|
| 1201 |
+
- 19.6875
|
| 1202 |
+
),
|
| 1203 |
+
0.193851103820053
|
| 1204 |
+
* y
|
| 1205 |
+
* (
|
| 1206 |
+
3.2 * z * (1.5 - 7.5 * z2)
|
| 1207 |
+
- 2.51428571428571
|
| 1208 |
+
* z
|
| 1209 |
+
* (
|
| 1210 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1211 |
+
+ 9.375 * z2
|
| 1212 |
+
- 1.875
|
| 1213 |
+
)
|
| 1214 |
+
+ 2.14285714285714
|
| 1215 |
+
* z
|
| 1216 |
+
* (
|
| 1217 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1218 |
+
+ 2.16666666666667
|
| 1219 |
+
* z
|
| 1220 |
+
* (
|
| 1221 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 1222 |
+
+ 2.2
|
| 1223 |
+
* z
|
| 1224 |
+
* (
|
| 1225 |
+
2.25
|
| 1226 |
+
* z
|
| 1227 |
+
* (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1228 |
+
+ 9.375 * z2
|
| 1229 |
+
- 1.875
|
| 1230 |
+
)
|
| 1231 |
+
- 4.8 * z
|
| 1232 |
+
)
|
| 1233 |
+
- 10.9375 * z2
|
| 1234 |
+
+ 2.1875
|
| 1235 |
+
)
|
| 1236 |
+
+ 5.48571428571429 * z
|
| 1237 |
+
),
|
| 1238 |
+
1.48417251362228
|
| 1239 |
+
* z
|
| 1240 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1241 |
+
- 1.86581687426801
|
| 1242 |
+
* z
|
| 1243 |
+
* (
|
| 1244 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 1245 |
+
+ 1.8
|
| 1246 |
+
* z
|
| 1247 |
+
* (
|
| 1248 |
+
1.75
|
| 1249 |
+
* z
|
| 1250 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1251 |
+
- 1.125 * z2
|
| 1252 |
+
+ 0.375
|
| 1253 |
+
)
|
| 1254 |
+
+ 0.533333333333333 * z
|
| 1255 |
+
)
|
| 1256 |
+
+ 2.1808249179756
|
| 1257 |
+
* z
|
| 1258 |
+
* (
|
| 1259 |
+
1.14285714285714 * z * (1.5 * z2 - 0.5)
|
| 1260 |
+
- 1.54285714285714
|
| 1261 |
+
* z
|
| 1262 |
+
* (
|
| 1263 |
+
1.75
|
| 1264 |
+
* z
|
| 1265 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1266 |
+
- 1.125 * z2
|
| 1267 |
+
+ 0.375
|
| 1268 |
+
)
|
| 1269 |
+
+ 1.85714285714286
|
| 1270 |
+
* z
|
| 1271 |
+
* (
|
| 1272 |
+
-1.45833333333333
|
| 1273 |
+
* z
|
| 1274 |
+
* (1.66666666666667 * z * (1.5 * z2 - 0.5) - 0.666666666666667 * z)
|
| 1275 |
+
+ 1.83333333333333
|
| 1276 |
+
* z
|
| 1277 |
+
* (
|
| 1278 |
+
-1.33333333333333 * z * (1.5 * z2 - 0.5)
|
| 1279 |
+
+ 1.8
|
| 1280 |
+
* z
|
| 1281 |
+
* (
|
| 1282 |
+
1.75
|
| 1283 |
+
* z
|
| 1284 |
+
* (
|
| 1285 |
+
1.66666666666667 * z * (1.5 * z2 - 0.5)
|
| 1286 |
+
- 0.666666666666667 * z
|
| 1287 |
+
)
|
| 1288 |
+
- 1.125 * z2
|
| 1289 |
+
+ 0.375
|
| 1290 |
+
)
|
| 1291 |
+
+ 0.533333333333333 * z
|
| 1292 |
+
)
|
| 1293 |
+
+ 0.9375 * z2
|
| 1294 |
+
- 0.3125
|
| 1295 |
+
)
|
| 1296 |
+
- 0.457142857142857 * z
|
| 1297 |
+
)
|
| 1298 |
+
- 0.954110901614325 * z2
|
| 1299 |
+
+ 0.318036967204775,
|
| 1300 |
+
0.193851103820053
|
| 1301 |
+
* x
|
| 1302 |
+
* (
|
| 1303 |
+
3.2 * z * (1.5 - 7.5 * z2)
|
| 1304 |
+
- 2.51428571428571
|
| 1305 |
+
* z
|
| 1306 |
+
* (
|
| 1307 |
+
2.25 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1308 |
+
+ 9.375 * z2
|
| 1309 |
+
- 1.875
|
| 1310 |
+
)
|
| 1311 |
+
+ 2.14285714285714
|
| 1312 |
+
* z
|
| 1313 |
+
* (
|
| 1314 |
+
-2.625 * z * (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1315 |
+
+ 2.16666666666667
|
| 1316 |
+
* z
|
| 1317 |
+
* (
|
| 1318 |
+
-2.8 * z * (1.5 - 7.5 * z2)
|
| 1319 |
+
+ 2.2
|
| 1320 |
+
* z
|
| 1321 |
+
* (
|
| 1322 |
+
2.25
|
| 1323 |
+
* z
|
| 1324 |
+
* (2.33333333333333 * z * (1.5 - 7.5 * z2) + 4.0 * z)
|
| 1325 |
+
+ 9.375 * z2
|
| 1326 |
+
- 1.875
|
| 1327 |
+
)
|
| 1328 |
+
- 4.8 * z
|
| 1329 |
+
)
|
| 1330 |
+
- 10.9375 * z2
|
| 1331 |
+
+ 2.1875
|
| 1332 |
+
)
|
| 1333 |
+
+ 5.48571428571429 * z
|
| 1334 |
+
),
|
| 1335 |
+
0.0231696385236779
|
| 1336 |
+
* (x2 - y2)
|
| 1337 |
+
* (
|
| 1338 |
+
-4.125 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1339 |
+
+ 2.5
|
| 1340 |
+
* z
|
| 1341 |
+
* (
|
| 1342 |
+
-4.8 * z * (52.5 * z2 - 7.5)
|
| 1343 |
+
+ 2.6
|
| 1344 |
+
* z
|
| 1345 |
+
* (
|
| 1346 |
+
2.75 * z * (3.0 * z * (52.5 * z2 - 7.5) - 30.0 * z)
|
| 1347 |
+
- 91.875 * z2
|
| 1348 |
+
+ 13.125
|
| 1349 |
+
)
|
| 1350 |
+
+ 48.0 * z
|
| 1351 |
+
)
|
| 1352 |
+
+ 137.8125 * z2
|
| 1353 |
+
- 19.6875
|
| 1354 |
+
),
|
| 1355 |
+
0.0028519853513317
|
| 1356 |
+
* x
|
| 1357 |
+
* (x2 - 3.0 * y2)
|
| 1358 |
+
* (
|
| 1359 |
+
-7.33333333333333 * z * (52.5 - 472.5 * z2)
|
| 1360 |
+
+ 3.0
|
| 1361 |
+
* z
|
| 1362 |
+
* (
|
| 1363 |
+
3.25 * z * (3.66666666666667 * z * (52.5 - 472.5 * z2) + 280.0 * z)
|
| 1364 |
+
+ 1063.125 * z2
|
| 1365 |
+
- 118.125
|
| 1366 |
+
)
|
| 1367 |
+
- 560.0 * z
|
| 1368 |
+
),
|
| 1369 |
+
0.000368189725644507
|
| 1370 |
+
* (-6.0 * x2 * y2 + x4 + y4)
|
| 1371 |
+
* (
|
| 1372 |
+
3.75 * z * (4.33333333333333 * z * (5197.5 * z2 - 472.5) - 3150.0 * z)
|
| 1373 |
+
- 14293.125 * z2
|
| 1374 |
+
+ 1299.375
|
| 1375 |
+
),
|
| 1376 |
+
5.10587282657803e-5
|
| 1377 |
+
* x
|
| 1378 |
+
* (5.0 * z * (5197.5 - 67567.5 * z2) + 41580.0 * z)
|
| 1379 |
+
* (-10.0 * x2 * y2 + x4 + 5.0 * y4),
|
| 1380 |
+
7.87853281621404e-6
|
| 1381 |
+
* (1013512.5 * z2 - 67567.5)
|
| 1382 |
+
* (x2**3 + 15.0 * x2 * y4 - 15.0 * x4 * y2 - y2**3),
|
| 1383 |
+
-2.91570664069932
|
| 1384 |
+
* xz
|
| 1385 |
+
* (x2**3 + 35.0 * x2 * y4 - 21.0 * x4 * y2 - 7.0 * y2**3),
|
| 1386 |
+
-20.4099464848952 * x2**3 * y2
|
| 1387 |
+
- 20.4099464848952 * x2 * y2**3
|
| 1388 |
+
+ 0.72892666017483 * x4**2
|
| 1389 |
+
+ 51.0248662122381 * x4 * y4
|
| 1390 |
+
+ 0.72892666017483 * y4**2,
|
| 1391 |
+
],
|
| 1392 |
+
-1,
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
|
| 1396 |
+
__all__ = [
|
| 1397 |
+
"rsh_cart_0",
|
| 1398 |
+
"rsh_cart_1",
|
| 1399 |
+
"rsh_cart_2",
|
| 1400 |
+
"rsh_cart_3",
|
| 1401 |
+
"rsh_cart_4",
|
| 1402 |
+
"rsh_cart_5",
|
| 1403 |
+
"rsh_cart_6",
|
| 1404 |
+
"rsh_cart_7",
|
| 1405 |
+
"rsh_cart_8",
|
| 1406 |
+
]
|
| 1407 |
+
|
| 1408 |
+
|
| 1409 |
+
from typing import Optional
|
| 1410 |
+
import torch
|
| 1411 |
+
|
| 1412 |
+
|
| 1413 |
+
class SphHarm(torch.nn.Module):
|
| 1414 |
+
def __init__(self, m, n, dtype=torch.float32) -> None:
|
| 1415 |
+
super().__init__()
|
| 1416 |
+
self.dtype = dtype
|
| 1417 |
+
m = torch.tensor(list(range(-m + 1, m)))
|
| 1418 |
+
n = torch.tensor(list(range(n)))
|
| 1419 |
+
self.is_normalized = False
|
| 1420 |
+
vals = torch.cartesian_prod(m, n).T
|
| 1421 |
+
vals = vals[:, vals[0] <= vals[1]]
|
| 1422 |
+
m, n = vals.unbind(0)
|
| 1423 |
+
|
| 1424 |
+
self.register_buffer("m", tensor=m)
|
| 1425 |
+
self.register_buffer("n", tensor=n)
|
| 1426 |
+
self.register_buffer("l_max", tensor=torch.max(self.n))
|
| 1427 |
+
|
| 1428 |
+
f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d = self._init_legendre()
|
| 1429 |
+
self.register_buffer("f_a", tensor=f_a)
|
| 1430 |
+
self.register_buffer("f_b", tensor=f_b)
|
| 1431 |
+
self.register_buffer("d0_mask_3d", tensor=d0_mask_3d)
|
| 1432 |
+
self.register_buffer("d1_mask_3d", tensor=d1_mask_3d)
|
| 1433 |
+
self.register_buffer("initial_value", tensor=initial_value)
|
| 1434 |
+
|
| 1435 |
+
@property
|
| 1436 |
+
def device(self):
|
| 1437 |
+
return next(self.buffers()).device
|
| 1438 |
+
|
| 1439 |
+
def forward(self, points: torch.Tensor) -> torch.Tensor:
|
| 1440 |
+
"""Computes the spherical harmonics."""
|
| 1441 |
+
# Y_l^m = (-1) ^ m c_l^m P_l^m(cos(theta)) exp(i m phi)
|
| 1442 |
+
B, N, D = points.shape
|
| 1443 |
+
dtype = points.dtype
|
| 1444 |
+
theta, phi = points.view(-1, D).to(self.dtype).unbind(-1)
|
| 1445 |
+
cos_colatitude = torch.cos(phi)
|
| 1446 |
+
legendre = self._gen_associated_legendre(cos_colatitude)
|
| 1447 |
+
vals = torch.stack([self.m.abs(), self.n], dim=0)
|
| 1448 |
+
vals = torch.cat(
|
| 1449 |
+
[
|
| 1450 |
+
vals.repeat(1, theta.shape[0]),
|
| 1451 |
+
torch.arange(theta.shape[0], device=theta.device)
|
| 1452 |
+
.unsqueeze(0)
|
| 1453 |
+
.repeat_interleave(vals.shape[1], dim=1),
|
| 1454 |
+
],
|
| 1455 |
+
dim=0,
|
| 1456 |
+
)
|
| 1457 |
+
legendre_vals = legendre[vals[0], vals[1], vals[2]]
|
| 1458 |
+
legendre_vals = legendre_vals.reshape(-1, theta.shape[0])
|
| 1459 |
+
angle = torch.outer(self.m.abs(), theta)
|
| 1460 |
+
vandermonde = torch.complex(torch.cos(angle), torch.sin(angle))
|
| 1461 |
+
harmonics = torch.complex(
|
| 1462 |
+
legendre_vals * torch.real(vandermonde),
|
| 1463 |
+
legendre_vals * torch.imag(vandermonde),
|
| 1464 |
+
)
|
| 1465 |
+
|
| 1466 |
+
# Negative order.
|
| 1467 |
+
m = self.m.unsqueeze(-1)
|
| 1468 |
+
harmonics = torch.where(
|
| 1469 |
+
m < 0, (-1.0) ** m.abs() * torch.conj(harmonics), harmonics
|
| 1470 |
+
)
|
| 1471 |
+
harmonics = harmonics.permute(1, 0).reshape(B, N, -1).to(dtype)
|
| 1472 |
+
return harmonics
|
| 1473 |
+
|
| 1474 |
+
def _gen_recurrence_mask(self) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1475 |
+
"""Generates mask for recurrence relation on the remaining entries.
|
| 1476 |
+
|
| 1477 |
+
The remaining entries are with respect to the diagonal and offdiagonal
|
| 1478 |
+
entries.
|
| 1479 |
+
|
| 1480 |
+
Args:
|
| 1481 |
+
l_max: see `gen_normalized_legendre`.
|
| 1482 |
+
Returns:
|
| 1483 |
+
torch.Tensors representing the mask used by the recurrence relations.
|
| 1484 |
+
"""
|
| 1485 |
+
|
| 1486 |
+
# Computes all coefficients.
|
| 1487 |
+
m_mat, l_mat = torch.meshgrid(
|
| 1488 |
+
torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype),
|
| 1489 |
+
torch.arange(0, self.l_max + 1, device=self.device, dtype=self.dtype),
|
| 1490 |
+
indexing="ij",
|
| 1491 |
+
)
|
| 1492 |
+
if self.is_normalized:
|
| 1493 |
+
c0 = l_mat * l_mat
|
| 1494 |
+
c1 = m_mat * m_mat
|
| 1495 |
+
c2 = 2.0 * l_mat
|
| 1496 |
+
c3 = (l_mat - 1.0) * (l_mat - 1.0)
|
| 1497 |
+
d0 = torch.sqrt((4.0 * c0 - 1.0) / (c0 - c1))
|
| 1498 |
+
d1 = torch.sqrt(((c2 + 1.0) * (c3 - c1)) / ((c2 - 3.0) * (c0 - c1)))
|
| 1499 |
+
else:
|
| 1500 |
+
d0 = (2.0 * l_mat - 1.0) / (l_mat - m_mat)
|
| 1501 |
+
d1 = (l_mat + m_mat - 1.0) / (l_mat - m_mat)
|
| 1502 |
+
|
| 1503 |
+
d0_mask_indices = torch.triu_indices(self.l_max + 1, 1)
|
| 1504 |
+
d1_mask_indices = torch.triu_indices(self.l_max + 1, 2)
|
| 1505 |
+
|
| 1506 |
+
d_zeros = torch.zeros(
|
| 1507 |
+
(self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device
|
| 1508 |
+
)
|
| 1509 |
+
d_zeros[d0_mask_indices] = d0[d0_mask_indices]
|
| 1510 |
+
d0_mask = d_zeros
|
| 1511 |
+
|
| 1512 |
+
d_zeros = torch.zeros(
|
| 1513 |
+
(self.l_max + 1, self.l_max + 1), dtype=self.dtype, device=self.device
|
| 1514 |
+
)
|
| 1515 |
+
d_zeros[d1_mask_indices] = d1[d1_mask_indices]
|
| 1516 |
+
d1_mask = d_zeros
|
| 1517 |
+
|
| 1518 |
+
# Creates a 3D mask that contains 1s on the diagonal plane and 0s elsewhere.
|
| 1519 |
+
i = torch.arange(self.l_max + 1, device=self.device)[:, None, None]
|
| 1520 |
+
j = torch.arange(self.l_max + 1, device=self.device)[None, :, None]
|
| 1521 |
+
k = torch.arange(self.l_max + 1, device=self.device)[None, None, :]
|
| 1522 |
+
mask = (i + j - k == 0).to(self.dtype)
|
| 1523 |
+
d0_mask_3d = torch.einsum("jk,ijk->ijk", d0_mask, mask)
|
| 1524 |
+
d1_mask_3d = torch.einsum("jk,ijk->ijk", d1_mask, mask)
|
| 1525 |
+
return (d0_mask_3d, d1_mask_3d)
|
| 1526 |
+
|
| 1527 |
+
def _recursive(self, i: int, p_val: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
|
| 1528 |
+
coeff_0 = self.d0_mask_3d[i]
|
| 1529 |
+
coeff_1 = self.d1_mask_3d[i]
|
| 1530 |
+
h = torch.einsum(
|
| 1531 |
+
"ij,ijk->ijk",
|
| 1532 |
+
coeff_0,
|
| 1533 |
+
torch.einsum("ijk,k->ijk", torch.roll(p_val, shifts=1, dims=1), x),
|
| 1534 |
+
) - torch.einsum("ij,ijk->ijk", coeff_1, torch.roll(p_val, shifts=2, dims=1))
|
| 1535 |
+
p_val = p_val + h
|
| 1536 |
+
return p_val
|
| 1537 |
+
|
| 1538 |
+
def _init_legendre(self):
|
| 1539 |
+
a_idx = torch.arange(1, self.l_max + 1, dtype=self.dtype, device=self.device)
|
| 1540 |
+
b_idx = torch.arange(self.l_max, dtype=self.dtype, device=self.device)
|
| 1541 |
+
if self.is_normalized:
|
| 1542 |
+
# The initial value p(0,0).
|
| 1543 |
+
initial_value: torch.Tensor = torch.tensor(
|
| 1544 |
+
0.5 / (torch.pi**0.5), device=self.device
|
| 1545 |
+
)
|
| 1546 |
+
f_a = torch.cumprod(-1 * torch.sqrt(1.0 + 0.5 / a_idx), dim=0)
|
| 1547 |
+
f_b = torch.sqrt(2.0 * b_idx + 3.0)
|
| 1548 |
+
else:
|
| 1549 |
+
# The initial value p(0,0).
|
| 1550 |
+
initial_value = torch.tensor(1.0, device=self.device)
|
| 1551 |
+
f_a = torch.cumprod(1.0 - 2.0 * a_idx, dim=0)
|
| 1552 |
+
f_b = 2.0 * b_idx + 1.0
|
| 1553 |
+
|
| 1554 |
+
d0_mask_3d, d1_mask_3d = self._gen_recurrence_mask()
|
| 1555 |
+
return f_a, f_b, initial_value, d0_mask_3d, d1_mask_3d
|
| 1556 |
+
|
| 1557 |
+
def _gen_associated_legendre(self, x: torch.Tensor) -> torch.Tensor:
|
| 1558 |
+
r"""Computes associated Legendre functions (ALFs) of the first kind.
|
| 1559 |
+
|
| 1560 |
+
The ALFs of the first kind are used in spherical harmonics. The spherical
|
| 1561 |
+
harmonic of degree `l` and order `m` can be written as
|
| 1562 |
+
`Y_l^m(θ, φ) = N_l^m * P_l^m(cos(θ)) * exp(i m φ)`, where `N_l^m` is the
|
| 1563 |
+
normalization factor and θ and φ are the colatitude and longitude,
|
| 1564 |
+
repectively. `N_l^m` is chosen in the way that the spherical harmonics form
|
| 1565 |
+
a set of orthonormal basis function of L^2(S^2). For the computational
|
| 1566 |
+
efficiency of spherical harmonics transform, the normalization factor is
|
| 1567 |
+
used in the computation of the ALFs. In addition, normalizing `P_l^m`
|
| 1568 |
+
avoids overflow/underflow and achieves better numerical stability. Three
|
| 1569 |
+
recurrence relations are used in the computation.
|
| 1570 |
+
|
| 1571 |
+
Args:
|
| 1572 |
+
l_max: The maximum degree of the associated Legendre function. Both the
|
| 1573 |
+
degrees and orders are `[0, 1, 2, ..., l_max]`.
|
| 1574 |
+
x: A vector of type `float32`, `float64` containing the sampled points in
|
| 1575 |
+
spherical coordinates, at which the ALFs are computed; `x` is essentially
|
| 1576 |
+
`cos(θ)`. For the numerical integration used by the spherical harmonics
|
| 1577 |
+
transforms, `x` contains the quadrature points in the interval of
|
| 1578 |
+
`[-1, 1]`. There are several approaches to provide the quadrature points:
|
| 1579 |
+
Gauss-Legendre method (`scipy.special.roots_legendre`), Gauss-Chebyshev
|
| 1580 |
+
method (`scipy.special.roots_chebyu`), and Driscoll & Healy
|
| 1581 |
+
method (Driscoll, James R., and Dennis M. Healy. "Computing Fourier
|
| 1582 |
+
transforms and convolutions on the 2-sphere." Advances in applied
|
| 1583 |
+
mathematics 15, no. 2 (1994): 202-250.). The Gauss-Legendre quadrature
|
| 1584 |
+
points are nearly equal-spaced along θ and provide exact discrete
|
| 1585 |
+
orthogonality, (P^m)^T W P_m = I, where `T` represents the transpose
|
| 1586 |
+
operation, `W` is a diagonal matrix containing the quadrature weights,
|
| 1587 |
+
and `I` is the identity matrix. The Gauss-Chebyshev points are equally
|
| 1588 |
+
spaced, which only provide approximate discrete orthogonality. The
|
| 1589 |
+
Driscoll & Healy qudarture points are equally spaced and provide the
|
| 1590 |
+
exact discrete orthogonality. The number of sampling points is required to
|
| 1591 |
+
be twice as the number of frequency points (modes) in the Driscoll & Healy
|
| 1592 |
+
approach, which enables FFT and achieves a fast spherical harmonics
|
| 1593 |
+
transform.
|
| 1594 |
+
is_normalized: True if the associated Legendre functions are normalized.
|
| 1595 |
+
With normalization, `N_l^m` is applied such that the spherical harmonics
|
| 1596 |
+
form a set of orthonormal basis functions of L^2(S^2).
|
| 1597 |
+
|
| 1598 |
+
Returns:
|
| 1599 |
+
The 3D array of shape `(l_max + 1, l_max + 1, len(x))` containing the values
|
| 1600 |
+
of the ALFs at `x`; the dimensions in the sequence of order, degree, and
|
| 1601 |
+
evalution points.
|
| 1602 |
+
"""
|
| 1603 |
+
p = torch.zeros(
|
| 1604 |
+
(self.l_max + 1, self.l_max + 1, x.shape[0]), dtype=x.dtype, device=x.device
|
| 1605 |
+
)
|
| 1606 |
+
p[0, 0] = self.initial_value
|
| 1607 |
+
|
| 1608 |
+
# Compute the diagonal entries p(l,l) with recurrence.
|
| 1609 |
+
y = torch.cumprod(
|
| 1610 |
+
torch.broadcast_to(torch.sqrt(1.0 - x * x), (self.l_max, x.shape[0])), dim=0
|
| 1611 |
+
)
|
| 1612 |
+
p_diag = self.initial_value * torch.einsum("i,ij->ij", self.f_a, y)
|
| 1613 |
+
# torch.diag_indices(l_max + 1)
|
| 1614 |
+
diag_indices = torch.stack(
|
| 1615 |
+
[torch.arange(0, self.l_max + 1, device=x.device)] * 2, dim=0
|
| 1616 |
+
)
|
| 1617 |
+
p[(diag_indices[0][1:], diag_indices[1][1:])] = p_diag
|
| 1618 |
+
|
| 1619 |
+
diag_indices = torch.stack(
|
| 1620 |
+
[torch.arange(0, self.l_max, device=x.device)] * 2, dim=0
|
| 1621 |
+
)
|
| 1622 |
+
|
| 1623 |
+
# Compute the off-diagonal entries with recurrence.
|
| 1624 |
+
p_offdiag = torch.einsum(
|
| 1625 |
+
"ij,ij->ij",
|
| 1626 |
+
torch.einsum("i,j->ij", self.f_b, x),
|
| 1627 |
+
p[(diag_indices[0], diag_indices[1])],
|
| 1628 |
+
) # p[torch.diag_indices(l_max)])
|
| 1629 |
+
p[(diag_indices[0][: self.l_max], diag_indices[1][: self.l_max] + 1)] = (
|
| 1630 |
+
p_offdiag
|
| 1631 |
+
)
|
| 1632 |
+
|
| 1633 |
+
# Compute the remaining entries with recurrence.
|
| 1634 |
+
if self.l_max > 1:
|
| 1635 |
+
for i in range(2, self.l_max + 1):
|
| 1636 |
+
p = self._recursive(i, p, x)
|
| 1637 |
+
return p
|
src/misc/step_tracker.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from multiprocessing import RLock
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from jaxtyping import Int64
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.multiprocessing import Manager
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class StepTracker:
|
| 10 |
+
lock: RLock
|
| 11 |
+
step: Int64[Tensor, ""]
|
| 12 |
+
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self.lock = Manager().RLock()
|
| 15 |
+
self.step = torch.tensor(0, dtype=torch.int64).share_memory_()
|
| 16 |
+
|
| 17 |
+
def set_step(self, step: int) -> None:
|
| 18 |
+
with self.lock:
|
| 19 |
+
self.step.fill_(step)
|
| 20 |
+
|
| 21 |
+
def get_step(self) -> int:
|
| 22 |
+
with self.lock:
|
| 23 |
+
return self.step.item()
|
src/misc/utils.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from src.visualization.color_map import apply_color_map_to_image
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
|
| 6 |
+
def inverse_normalize(tensor, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)):
|
| 7 |
+
mean = torch.as_tensor(mean, dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1)
|
| 8 |
+
std = torch.as_tensor(std, dtype=tensor.dtype, device=tensor.device).view(-1, 1, 1)
|
| 9 |
+
return tensor.mul(std).add(mean)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Color-map the result.
|
| 13 |
+
def vis_depth_map(result, near=None, far=None):
|
| 14 |
+
if near is None and far is None:
|
| 15 |
+
far = result.view(-1)[:16_000_000].quantile(0.99).log()
|
| 16 |
+
try:
|
| 17 |
+
near = result[result > 0][:16_000_000].quantile(0.01).log()
|
| 18 |
+
except:
|
| 19 |
+
print("No valid depth values found.")
|
| 20 |
+
near = torch.zeros_like(far)
|
| 21 |
+
else:
|
| 22 |
+
near = near.log()
|
| 23 |
+
far = far.log()
|
| 24 |
+
|
| 25 |
+
result = result.log()
|
| 26 |
+
result = 1 - (result - near) / (far - near)
|
| 27 |
+
return apply_color_map_to_image(result, "turbo")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def confidence_map(result):
|
| 31 |
+
# far = result.view(-1)[:16_000_000].quantile(0.99).log()
|
| 32 |
+
# try:
|
| 33 |
+
# near = result[result > 0][:16_000_000].quantile(0.01).log()
|
| 34 |
+
# except:
|
| 35 |
+
# print("No valid depth values found.")
|
| 36 |
+
# near = torch.zeros_like(far)
|
| 37 |
+
# result = result.log()
|
| 38 |
+
# result = 1 - (result - near) / (far - near)
|
| 39 |
+
result = result / result.view(-1).max()
|
| 40 |
+
return apply_color_map_to_image(result, "magma")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_overlap_tag(overlap):
|
| 44 |
+
if 0.05 <= overlap <= 0.3:
|
| 45 |
+
overlap_tag = "small"
|
| 46 |
+
elif overlap <= 0.55:
|
| 47 |
+
overlap_tag = "medium"
|
| 48 |
+
elif overlap <= 0.8:
|
| 49 |
+
overlap_tag = "large"
|
| 50 |
+
else:
|
| 51 |
+
overlap_tag = "ignore"
|
| 52 |
+
|
| 53 |
+
return overlap_tag
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def is_dist_avail_and_initialized():
|
| 57 |
+
if not dist.is_available():
|
| 58 |
+
return False
|
| 59 |
+
if not dist.is_initialized():
|
| 60 |
+
return False
|
| 61 |
+
return True
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_world_size():
|
| 65 |
+
if not is_dist_avail_and_initialized():
|
| 66 |
+
return 1
|
| 67 |
+
return dist.get_world_size()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_rank():
|
| 71 |
+
if not is_dist_avail_and_initialized():
|
| 72 |
+
return 0
|
| 73 |
+
return dist.get_rank()
|
src/misc/wandb_tools.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import wandb
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def version_to_int(artifact) -> int:
|
| 7 |
+
"""Convert versions of the form vX to X. For example, v12 to 12."""
|
| 8 |
+
return int(artifact.version[1:])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def download_checkpoint(
|
| 12 |
+
run_id: str,
|
| 13 |
+
download_dir: Path,
|
| 14 |
+
version: str | None,
|
| 15 |
+
) -> Path:
|
| 16 |
+
api = wandb.Api()
|
| 17 |
+
run = api.run(run_id)
|
| 18 |
+
|
| 19 |
+
# Find the latest saved model checkpoint.
|
| 20 |
+
chosen = None
|
| 21 |
+
for artifact in run.logged_artifacts():
|
| 22 |
+
if artifact.type != "model" or artifact.state != "COMMITTED":
|
| 23 |
+
continue
|
| 24 |
+
|
| 25 |
+
# If no version is specified, use the latest.
|
| 26 |
+
if version is None:
|
| 27 |
+
if chosen is None or version_to_int(artifact) > version_to_int(chosen):
|
| 28 |
+
chosen = artifact
|
| 29 |
+
|
| 30 |
+
# If a specific verison is specified, look for it.
|
| 31 |
+
elif version == artifact.version:
|
| 32 |
+
chosen = artifact
|
| 33 |
+
break
|
| 34 |
+
|
| 35 |
+
# Download the checkpoint.
|
| 36 |
+
download_dir.mkdir(exist_ok=True, parents=True)
|
| 37 |
+
root = download_dir / run_id
|
| 38 |
+
chosen.download(root=root)
|
| 39 |
+
return root / "model.ckpt"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def update_checkpoint_path(path: str | None, wandb_cfg: dict) -> Path | None:
|
| 43 |
+
if path is None:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
if not str(path).startswith("wandb://"):
|
| 47 |
+
return Path(path)
|
| 48 |
+
|
| 49 |
+
run_id, *version = path[len("wandb://") :].split(":")
|
| 50 |
+
if len(version) == 0:
|
| 51 |
+
version = None
|
| 52 |
+
elif len(version) == 1:
|
| 53 |
+
version = version[0]
|
| 54 |
+
else:
|
| 55 |
+
raise ValueError("Invalid version specifier!")
|
| 56 |
+
|
| 57 |
+
project = wandb_cfg["project"]
|
| 58 |
+
return download_checkpoint(
|
| 59 |
+
f"{project}/{run_id}",
|
| 60 |
+
Path("checkpoints"),
|
| 61 |
+
version,
|
| 62 |
+
)
|
src/misc/weight_modify.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import List, Dict
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
_logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def resample_patch_embed(
|
| 14 |
+
patch_embed,
|
| 15 |
+
new_size: List[int],
|
| 16 |
+
interpolation: str = 'bicubic',
|
| 17 |
+
antialias: bool = True,
|
| 18 |
+
verbose: bool = False,
|
| 19 |
+
):
|
| 20 |
+
"""Resample the weights of the patch embedding kernel to target resolution.
|
| 21 |
+
We resample the patch embedding kernel by approximately inverting the effect
|
| 22 |
+
of patch resizing.
|
| 23 |
+
|
| 24 |
+
Code based on:
|
| 25 |
+
https://github.com/google-research/big_vision/blob/b00544b81f8694488d5f36295aeb7972f3755ffe/big_vision/models/proj/flexi/vit.py
|
| 26 |
+
|
| 27 |
+
With this resizing, we can for example load a B/8 filter into a B/16 model
|
| 28 |
+
and, on 2x larger input image, the result will match.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
patch_embed: original parameter to be resized.
|
| 32 |
+
new_size (tuple(int, int): target shape (height, width)-only.
|
| 33 |
+
interpolation (str): interpolation for resize
|
| 34 |
+
antialias (bool): use anti-aliasing filter in resize
|
| 35 |
+
verbose (bool): log operation
|
| 36 |
+
Returns:
|
| 37 |
+
Resized patch embedding kernel.
|
| 38 |
+
"""
|
| 39 |
+
import numpy as np
|
| 40 |
+
try:
|
| 41 |
+
import functorch
|
| 42 |
+
vmap = functorch.vmap
|
| 43 |
+
except ImportError:
|
| 44 |
+
if hasattr(torch, 'vmap'):
|
| 45 |
+
vmap = torch.vmap
|
| 46 |
+
else:
|
| 47 |
+
assert False, "functorch or a version of torch with vmap is required for FlexiViT resizing."
|
| 48 |
+
|
| 49 |
+
assert len(patch_embed.shape) == 4, "Four dimensions expected"
|
| 50 |
+
assert len(new_size) == 2, "New shape should only be hw"
|
| 51 |
+
old_size = patch_embed.shape[-2:]
|
| 52 |
+
if tuple(old_size) == tuple(new_size):
|
| 53 |
+
return patch_embed
|
| 54 |
+
|
| 55 |
+
if verbose:
|
| 56 |
+
_logger.info(f"Resize patch embedding {patch_embed.shape} to {new_size}, w/ {interpolation} interpolation.")
|
| 57 |
+
|
| 58 |
+
def resize(x_np, _new_size):
|
| 59 |
+
x_tf = torch.Tensor(x_np)[None, None, ...]
|
| 60 |
+
x_upsampled = F.interpolate(
|
| 61 |
+
x_tf, size=_new_size, mode=interpolation, antialias=antialias)[0, 0, ...].numpy()
|
| 62 |
+
return x_upsampled
|
| 63 |
+
|
| 64 |
+
def get_resize_mat(_old_size, _new_size):
|
| 65 |
+
mat = []
|
| 66 |
+
for i in range(np.prod(_old_size)):
|
| 67 |
+
basis_vec = np.zeros(_old_size)
|
| 68 |
+
basis_vec[np.unravel_index(i, _old_size)] = 1.
|
| 69 |
+
mat.append(resize(basis_vec, _new_size).reshape(-1))
|
| 70 |
+
return np.stack(mat).T
|
| 71 |
+
|
| 72 |
+
resize_mat = get_resize_mat(old_size, new_size)
|
| 73 |
+
resize_mat_pinv = torch.tensor(np.linalg.pinv(resize_mat.T), device=patch_embed.device)
|
| 74 |
+
|
| 75 |
+
def resample_kernel(kernel):
|
| 76 |
+
resampled_kernel = resize_mat_pinv @ kernel.reshape(-1)
|
| 77 |
+
return resampled_kernel.reshape(new_size)
|
| 78 |
+
|
| 79 |
+
v_resample_kernel = vmap(vmap(resample_kernel, 0, 0), 1, 1)
|
| 80 |
+
orig_dtype = patch_embed.dtype
|
| 81 |
+
patch_embed = patch_embed.float()
|
| 82 |
+
patch_embed = v_resample_kernel(patch_embed)
|
| 83 |
+
patch_embed = patch_embed.to(orig_dtype)
|
| 84 |
+
return patch_embed
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def adapt_input_conv(in_chans, conv_weight):
|
| 88 |
+
conv_type = conv_weight.dtype
|
| 89 |
+
conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU
|
| 90 |
+
O, I, J, K = conv_weight.shape
|
| 91 |
+
if in_chans == 1:
|
| 92 |
+
if I > 3:
|
| 93 |
+
assert conv_weight.shape[1] % 3 == 0
|
| 94 |
+
# For models with space2depth stems
|
| 95 |
+
conv_weight = conv_weight.reshape(O, I // 3, 3, J, K)
|
| 96 |
+
conv_weight = conv_weight.sum(dim=2, keepdim=False)
|
| 97 |
+
else:
|
| 98 |
+
conv_weight = conv_weight.sum(dim=1, keepdim=True)
|
| 99 |
+
elif in_chans != 3:
|
| 100 |
+
if I != 3:
|
| 101 |
+
raise NotImplementedError('Weight format not supported by conversion.')
|
| 102 |
+
else:
|
| 103 |
+
# NOTE this strategy should be better than random init, but there could be other combinations of
|
| 104 |
+
# the original RGB input layer weights that'd work better for specific cases.
|
| 105 |
+
repeat = int(math.ceil(in_chans / 3))
|
| 106 |
+
conv_weight = conv_weight.repeat(1, repeat, 1, 1)[:, :in_chans, :, :]
|
| 107 |
+
conv_weight *= (3 / float(in_chans))
|
| 108 |
+
|
| 109 |
+
# instead of assigning the same weight to all channels, we can assign higher weight for original RGB channels
|
| 110 |
+
# conv_weight[:, :3, :, :] = conv_weight[:, :3, :, :] * 0.5
|
| 111 |
+
# conv_weight[:, 3:, :, :] = conv_weight[:, 3:, :, :] * 0.5 * (3 / float(in_chans - 3))
|
| 112 |
+
|
| 113 |
+
conv_weight = conv_weight.to(conv_type)
|
| 114 |
+
return conv_weight
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def adapt_head_conv(conv_weight):
|
| 118 |
+
conv_type = conv_weight.dtype
|
| 119 |
+
conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU
|
| 120 |
+
O, I, J, K = conv_weight.shape
|
| 121 |
+
|
| 122 |
+
conv_weight_new = torch.chunk(conv_weight, 6, dim=1)
|
| 123 |
+
conv_weight_new = [conv_weight_new.mean(dim=1, keepdim=True) for conv_weight_new in conv_weight_new]
|
| 124 |
+
conv_weight_new = torch.cat(conv_weight_new, dim=1) * 0.5
|
| 125 |
+
conv_weight = torch.cat([conv_weight, conv_weight_new], dim=1)
|
| 126 |
+
conv_weight = conv_weight.to(conv_type)
|
| 127 |
+
return conv_weight
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def adapt_linear(conv_weight):
|
| 131 |
+
conv_type = conv_weight.dtype
|
| 132 |
+
conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU
|
| 133 |
+
O, I = conv_weight.shape
|
| 134 |
+
|
| 135 |
+
conv_weight_new = torch.tensor_split(conv_weight, 81, dim=1)
|
| 136 |
+
conv_weight_new = [conv_weight_new.mean(dim=1, keepdim=True) for conv_weight_new in conv_weight_new]
|
| 137 |
+
conv_weight_new = torch.cat(conv_weight_new, dim=1)
|
| 138 |
+
# conv_weight = torch.cat([conv_weight, conv_weight_new], dim=1)
|
| 139 |
+
conv_weight = torch.cat([conv_weight * 0.5, conv_weight_new * 0.5], dim=1)
|
| 140 |
+
conv_weight = conv_weight.to(conv_type)
|
| 141 |
+
return conv_weight
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def checkpoint_filter_fn(
|
| 145 |
+
state_dict: Dict[str, torch.Tensor],
|
| 146 |
+
model: nn.Module,
|
| 147 |
+
interpolation: str = 'bicubic',
|
| 148 |
+
antialias: bool = True,
|
| 149 |
+
) -> Dict[str, torch.Tensor]:
|
| 150 |
+
""" convert patch embedding weight from manual patchify + linear proj to conv"""
|
| 151 |
+
out_dict = {}
|
| 152 |
+
# state_dict = state_dict.get('model', state_dict)
|
| 153 |
+
# state_dict = state_dict.get('state_dict', state_dict)
|
| 154 |
+
prefix = ''
|
| 155 |
+
|
| 156 |
+
if prefix:
|
| 157 |
+
# filter on & remove prefix string from keys
|
| 158 |
+
state_dict = {k[len(prefix):]: v for k, v in state_dict.items() if k.startswith(prefix)}
|
| 159 |
+
|
| 160 |
+
for k, v in state_dict.items():
|
| 161 |
+
if 'patch_embed.proj.weight' in k:
|
| 162 |
+
O, I, H, W = model.backbone.patch_embed.proj.weight.shape
|
| 163 |
+
if len(v.shape) < 4:
|
| 164 |
+
# For old models that I trained prior to conv based patchification
|
| 165 |
+
O, I, H, W = model.backbone.patch_embed.proj.weight.shape
|
| 166 |
+
v = v.reshape(O, -1, H, W)
|
| 167 |
+
if v.shape[-1] != W or v.shape[-2] != H:
|
| 168 |
+
v = resample_patch_embed(
|
| 169 |
+
v,
|
| 170 |
+
(H, W),
|
| 171 |
+
interpolation=interpolation,
|
| 172 |
+
antialias=antialias,
|
| 173 |
+
verbose=True,
|
| 174 |
+
)
|
| 175 |
+
if v.shape[1] != I:
|
| 176 |
+
v = adapt_input_conv(I, v)
|
| 177 |
+
# elif 'downstream_head1.dpt.head.0.weight' in k or 'downstream_head2.dpt.head.0.weight' in k:
|
| 178 |
+
# v = adapt_head_conv(v)
|
| 179 |
+
|
| 180 |
+
elif 'decoder_embed.weight' in k:
|
| 181 |
+
O, I = model.backbone.decoder_embed.weight.shape
|
| 182 |
+
if v.shape[1] != I:
|
| 183 |
+
v = adapt_linear(v)
|
| 184 |
+
|
| 185 |
+
out_dict[k] = v
|
| 186 |
+
|
| 187 |
+
# add prefix to make our model happy
|
| 188 |
+
prefix = 'backbone.'
|
| 189 |
+
out_dict = {prefix + k if 'downstream_head' not in k else k: v for k, v in out_dict.items()}
|
| 190 |
+
|
| 191 |
+
# # remove the conf head weights
|
| 192 |
+
out_dict['downstream_head1.dpt.head.4.weight'] = out_dict['downstream_head1.dpt.head.4.weight'][0:3]
|
| 193 |
+
out_dict['downstream_head1.dpt.head.4.bias'] = out_dict['downstream_head1.dpt.head.4.bias'][0:3]
|
| 194 |
+
out_dict['downstream_head2.dpt.head.4.weight'] = out_dict['downstream_head2.dpt.head.4.weight'][0:3]
|
| 195 |
+
out_dict['downstream_head2.dpt.head.4.bias'] = out_dict['downstream_head2.dpt.head.4.bias'][0:3]
|
| 196 |
+
|
| 197 |
+
return out_dict
|
src/model/decoder/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .decoder import Decoder
|
| 2 |
+
from .decoder_splatting_cuda import DecoderSplattingCUDA, DecoderSplattingCUDACfg
|
| 3 |
+
|
| 4 |
+
DECODERS = {
|
| 5 |
+
"splatting_cuda": DecoderSplattingCUDA,
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
DecoderCfg = DecoderSplattingCUDACfg
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_decoder(decoder_cfg: DecoderCfg) -> Decoder:
|
| 12 |
+
return DECODERS[decoder_cfg.name](decoder_cfg)
|
src/model/decoder/cuda_splatting.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import isqrt
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from diff_gaussian_rasterization import (
|
| 6 |
+
GaussianRasterizationSettings,
|
| 7 |
+
GaussianRasterizer,
|
| 8 |
+
)
|
| 9 |
+
from einops import einsum, rearrange, repeat
|
| 10 |
+
from jaxtyping import Float, Bool
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
|
| 13 |
+
from ...geometry.projection import get_fov, homogenize_points
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_projection_matrix(
|
| 17 |
+
near: Float[Tensor, " batch"],
|
| 18 |
+
far: Float[Tensor, " batch"],
|
| 19 |
+
fov_x: Float[Tensor, " batch"],
|
| 20 |
+
fov_y: Float[Tensor, " batch"],
|
| 21 |
+
) -> Float[Tensor, "batch 4 4"]:
|
| 22 |
+
"""Maps points in the viewing frustum to (-1, 1) on the X/Y axes and (0, 1) on the Z
|
| 23 |
+
axis. Differs from the OpenGL version in that Z doesn't have range (-1, 1) after
|
| 24 |
+
transformation and that Z is flipped.
|
| 25 |
+
"""
|
| 26 |
+
tan_fov_x = (0.5 * fov_x).tan()
|
| 27 |
+
tan_fov_y = (0.5 * fov_y).tan()
|
| 28 |
+
|
| 29 |
+
top = tan_fov_y * near
|
| 30 |
+
bottom = -top
|
| 31 |
+
right = tan_fov_x * near
|
| 32 |
+
left = -right
|
| 33 |
+
|
| 34 |
+
(b,) = near.shape
|
| 35 |
+
result = torch.zeros((b, 4, 4), dtype=torch.float32, device=near.device)
|
| 36 |
+
result[:, 0, 0] = 2 * near / (right - left)
|
| 37 |
+
result[:, 1, 1] = 2 * near / (top - bottom)
|
| 38 |
+
result[:, 0, 2] = (right + left) / (right - left)
|
| 39 |
+
result[:, 1, 2] = (top + bottom) / (top - bottom)
|
| 40 |
+
result[:, 3, 2] = 1
|
| 41 |
+
result[:, 2, 2] = far / (far - near)
|
| 42 |
+
result[:, 2, 3] = -(far * near) / (far - near)
|
| 43 |
+
return result
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def render_cuda(
|
| 47 |
+
extrinsics: Float[Tensor, "batch 4 4"],
|
| 48 |
+
intrinsics: Float[Tensor, "batch 3 3"],
|
| 49 |
+
near: Float[Tensor, " batch"],
|
| 50 |
+
far: Float[Tensor, " batch"],
|
| 51 |
+
image_shape: tuple[int, int],
|
| 52 |
+
background_color: Float[Tensor, "batch 3"],
|
| 53 |
+
gaussian_means: Float[Tensor, "batch gaussian 3"],
|
| 54 |
+
gaussian_covariances: Float[Tensor, "batch gaussian 3 3"],
|
| 55 |
+
gaussian_sh_coefficients: Float[Tensor, "batch gaussian 3 d_sh"],
|
| 56 |
+
gaussian_opacities: Float[Tensor, "batch gaussian"],
|
| 57 |
+
scale_invariant: bool = True,
|
| 58 |
+
use_sh: bool = True,
|
| 59 |
+
cam_rot_delta: Float[Tensor, "batch 3"] | None = None,
|
| 60 |
+
cam_trans_delta: Float[Tensor, "batch 3"] | None = None,
|
| 61 |
+
voxel_masks: Bool[Tensor, "batch gaussian"] | None = None,
|
| 62 |
+
) -> tuple[Float[Tensor, "batch 3 height width"], Float[Tensor, "batch height width"]]:
|
| 63 |
+
assert use_sh or gaussian_sh_coefficients.shape[-1] == 1
|
| 64 |
+
|
| 65 |
+
# Make sure everything is in a range where numerical issues don't appear.
|
| 66 |
+
if scale_invariant:
|
| 67 |
+
scale = 1 / near
|
| 68 |
+
extrinsics = extrinsics.clone()
|
| 69 |
+
extrinsics[..., :3, 3] = extrinsics[..., :3, 3] * scale[:, None]
|
| 70 |
+
gaussian_covariances = gaussian_covariances * (scale[:, None, None, None] ** 2)
|
| 71 |
+
gaussian_means = gaussian_means * scale[:, None, None]
|
| 72 |
+
near = near * scale
|
| 73 |
+
far = far * scale
|
| 74 |
+
|
| 75 |
+
_, _, _, n = gaussian_sh_coefficients.shape
|
| 76 |
+
degree = isqrt(n) - 1
|
| 77 |
+
shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous()
|
| 78 |
+
|
| 79 |
+
b, _, _ = extrinsics.shape
|
| 80 |
+
h, w = image_shape
|
| 81 |
+
|
| 82 |
+
fov_x, fov_y = get_fov(intrinsics).unbind(dim=-1)
|
| 83 |
+
tan_fov_x = (0.5 * fov_x).tan()
|
| 84 |
+
tan_fov_y = (0.5 * fov_y).tan()
|
| 85 |
+
|
| 86 |
+
projection_matrix = get_projection_matrix(near, far, fov_x, fov_y)
|
| 87 |
+
projection_matrix = rearrange(projection_matrix, "b i j -> b j i")
|
| 88 |
+
view_matrix = rearrange(extrinsics.inverse(), "b i j -> b j i")
|
| 89 |
+
full_projection = view_matrix @ projection_matrix
|
| 90 |
+
|
| 91 |
+
all_images = []
|
| 92 |
+
all_radii = []
|
| 93 |
+
all_depths = []
|
| 94 |
+
for i in range(b):
|
| 95 |
+
# Set up a tensor for the gradients of the screen-space means.
|
| 96 |
+
mean_gradients = torch.zeros_like(gaussian_means[i], requires_grad=True)
|
| 97 |
+
try:
|
| 98 |
+
mean_gradients.retain_grad()
|
| 99 |
+
except Exception:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
settings = GaussianRasterizationSettings(
|
| 103 |
+
image_height=h,
|
| 104 |
+
image_width=w,
|
| 105 |
+
tanfovx=tan_fov_x[i].item(),
|
| 106 |
+
tanfovy=tan_fov_y[i].item(),
|
| 107 |
+
bg=background_color[i],
|
| 108 |
+
scale_modifier=1.0,
|
| 109 |
+
viewmatrix=view_matrix[i],
|
| 110 |
+
projmatrix=full_projection[i],
|
| 111 |
+
projmatrix_raw=projection_matrix[i],
|
| 112 |
+
sh_degree=degree,
|
| 113 |
+
campos=extrinsics[i, :3, 3],
|
| 114 |
+
prefiltered=False, # This matches the original usage.
|
| 115 |
+
debug=False,
|
| 116 |
+
)
|
| 117 |
+
rasterizer = GaussianRasterizer(settings)
|
| 118 |
+
|
| 119 |
+
row, col = torch.triu_indices(3, 3)
|
| 120 |
+
|
| 121 |
+
if voxel_masks is not None:
|
| 122 |
+
voxel_mask = voxel_masks[i]
|
| 123 |
+
image, radii, depth, opacity, n_touched = rasterizer(
|
| 124 |
+
means3D=gaussian_means[i][voxel_mask],
|
| 125 |
+
means2D=mean_gradients[voxel_mask],
|
| 126 |
+
shs=shs[i][voxel_mask] if use_sh else None,
|
| 127 |
+
colors_precomp=None if use_sh else shs[i, :, 0, :][voxel_mask],
|
| 128 |
+
opacities=gaussian_opacities[i][voxel_mask, ..., None],
|
| 129 |
+
cov3D_precomp=gaussian_covariances[i, :, row, col][voxel_mask],
|
| 130 |
+
theta=cam_rot_delta[i] if cam_rot_delta is not None else None,
|
| 131 |
+
rho=cam_trans_delta[i] if cam_trans_delta is not None else None,
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
image, radii, depth, opacity, n_touched = rasterizer(
|
| 135 |
+
means3D=gaussian_means[i],
|
| 136 |
+
means2D=mean_gradients,
|
| 137 |
+
shs=shs[i] if use_sh else None,
|
| 138 |
+
colors_precomp=None if use_sh else shs[i, :, 0, :],
|
| 139 |
+
opacities=gaussian_opacities[i, ..., None],
|
| 140 |
+
cov3D_precomp=gaussian_covariances[i, :, row, col],
|
| 141 |
+
theta=cam_rot_delta[i] if cam_rot_delta is not None else None,
|
| 142 |
+
rho=cam_trans_delta[i] if cam_trans_delta is not None else None,
|
| 143 |
+
)
|
| 144 |
+
all_images.append(image)
|
| 145 |
+
all_radii.append(radii)
|
| 146 |
+
all_depths.append(depth.squeeze(0))
|
| 147 |
+
return torch.stack(all_images), torch.stack(all_depths)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def render_cuda_orthographic(
|
| 151 |
+
extrinsics: Float[Tensor, "batch 4 4"],
|
| 152 |
+
width: Float[Tensor, " batch"],
|
| 153 |
+
height: Float[Tensor, " batch"],
|
| 154 |
+
near: Float[Tensor, " batch"],
|
| 155 |
+
far: Float[Tensor, " batch"],
|
| 156 |
+
image_shape: tuple[int, int],
|
| 157 |
+
background_color: Float[Tensor, "batch 3"],
|
| 158 |
+
gaussian_means: Float[Tensor, "batch gaussian 3"],
|
| 159 |
+
gaussian_covariances: Float[Tensor, "batch gaussian 3 3"],
|
| 160 |
+
gaussian_sh_coefficients: Float[Tensor, "batch gaussian 3 d_sh"],
|
| 161 |
+
gaussian_opacities: Float[Tensor, "batch gaussian"],
|
| 162 |
+
fov_degrees: float = 0.1,
|
| 163 |
+
use_sh: bool = True,
|
| 164 |
+
dump: dict | None = None,
|
| 165 |
+
) -> Float[Tensor, "batch 3 height width"]:
|
| 166 |
+
b, _, _ = extrinsics.shape
|
| 167 |
+
h, w = image_shape
|
| 168 |
+
assert use_sh or gaussian_sh_coefficients.shape[-1] == 1
|
| 169 |
+
|
| 170 |
+
_, _, _, n = gaussian_sh_coefficients.shape
|
| 171 |
+
degree = isqrt(n) - 1
|
| 172 |
+
shs = rearrange(gaussian_sh_coefficients, "b g xyz n -> b g n xyz").contiguous()
|
| 173 |
+
|
| 174 |
+
# Create fake "orthographic" projection by moving the camera back and picking a
|
| 175 |
+
# small field of view.
|
| 176 |
+
fov_x = torch.tensor(fov_degrees, device=extrinsics.device).deg2rad()
|
| 177 |
+
tan_fov_x = (0.5 * fov_x).tan()
|
| 178 |
+
distance_to_near = (0.5 * width) / tan_fov_x
|
| 179 |
+
tan_fov_y = 0.5 * height / distance_to_near
|
| 180 |
+
fov_y = (2 * tan_fov_y).atan()
|
| 181 |
+
near = near + distance_to_near
|
| 182 |
+
far = far + distance_to_near
|
| 183 |
+
move_back = torch.eye(4, dtype=torch.float32, device=extrinsics.device)
|
| 184 |
+
move_back[2, 3] = -distance_to_near
|
| 185 |
+
extrinsics = extrinsics @ move_back
|
| 186 |
+
|
| 187 |
+
# Escape hatch for visualization/figures.
|
| 188 |
+
if dump is not None:
|
| 189 |
+
dump["extrinsics"] = extrinsics
|
| 190 |
+
dump["fov_x"] = fov_x
|
| 191 |
+
dump["fov_y"] = fov_y
|
| 192 |
+
dump["near"] = near
|
| 193 |
+
dump["far"] = far
|
| 194 |
+
|
| 195 |
+
projection_matrix = get_projection_matrix(
|
| 196 |
+
near, far, repeat(fov_x, "-> b", b=b), fov_y
|
| 197 |
+
)
|
| 198 |
+
projection_matrix = rearrange(projection_matrix, "b i j -> b j i")
|
| 199 |
+
view_matrix = rearrange(extrinsics.inverse(), "b i j -> b j i")
|
| 200 |
+
full_projection = view_matrix @ projection_matrix
|
| 201 |
+
|
| 202 |
+
all_images = []
|
| 203 |
+
all_radii = []
|
| 204 |
+
for i in range(b):
|
| 205 |
+
# Set up a tensor for the gradients of the screen-space means.
|
| 206 |
+
mean_gradients = torch.zeros_like(gaussian_means[i], requires_grad=True)
|
| 207 |
+
try:
|
| 208 |
+
mean_gradients.retain_grad()
|
| 209 |
+
except Exception:
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
settings = GaussianRasterizationSettings(
|
| 213 |
+
image_height=h,
|
| 214 |
+
image_width=w,
|
| 215 |
+
tanfovx=tan_fov_x,
|
| 216 |
+
tanfovy=tan_fov_y,
|
| 217 |
+
bg=background_color[i],
|
| 218 |
+
scale_modifier=1.0,
|
| 219 |
+
viewmatrix=view_matrix[i],
|
| 220 |
+
projmatrix=full_projection[i],
|
| 221 |
+
projmatrix_raw=projection_matrix[i],
|
| 222 |
+
sh_degree=degree,
|
| 223 |
+
campos=extrinsics[i, :3, 3],
|
| 224 |
+
prefiltered=False, # This matches the original usage.
|
| 225 |
+
debug=False,
|
| 226 |
+
)
|
| 227 |
+
rasterizer = GaussianRasterizer(settings)
|
| 228 |
+
|
| 229 |
+
row, col = torch.triu_indices(3, 3)
|
| 230 |
+
|
| 231 |
+
image, radii, depth, opacity, n_touched = rasterizer(
|
| 232 |
+
means3D=gaussian_means[i],
|
| 233 |
+
means2D=mean_gradients,
|
| 234 |
+
shs=shs[i] if use_sh else None,
|
| 235 |
+
colors_precomp=None if use_sh else shs[i, :, 0, :],
|
| 236 |
+
opacities=gaussian_opacities[i, ..., None],
|
| 237 |
+
cov3D_precomp=gaussian_covariances[i, :, row, col],
|
| 238 |
+
)
|
| 239 |
+
all_images.append(image)
|
| 240 |
+
all_radii.append(radii)
|
| 241 |
+
return torch.stack(all_images)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
DepthRenderingMode = Literal["depth", "disparity", "relative_disparity", "log"]
|
src/model/decoder/decoder.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Generic, Literal, TypeVar
|
| 4 |
+
|
| 5 |
+
from jaxtyping import Float
|
| 6 |
+
from torch import Tensor, nn
|
| 7 |
+
|
| 8 |
+
from ..types import Gaussians
|
| 9 |
+
|
| 10 |
+
DepthRenderingMode = Literal[
|
| 11 |
+
"depth",
|
| 12 |
+
"log",
|
| 13 |
+
"disparity",
|
| 14 |
+
"relative_disparity",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class DecoderOutput:
|
| 20 |
+
color: Float[Tensor, "batch view 3 height width"]
|
| 21 |
+
depth: Float[Tensor, "batch view height width"] | None
|
| 22 |
+
alpha: Float[Tensor, "batch view height width"] | None
|
| 23 |
+
lod_rendering: dict | None
|
| 24 |
+
|
| 25 |
+
T = TypeVar("T")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Decoder(nn.Module, ABC, Generic[T]):
|
| 29 |
+
cfg: T
|
| 30 |
+
|
| 31 |
+
def __init__(self, cfg: T) -> None:
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.cfg = cfg
|
| 34 |
+
|
| 35 |
+
@abstractmethod
|
| 36 |
+
def forward(
|
| 37 |
+
self,
|
| 38 |
+
gaussians: Gaussians,
|
| 39 |
+
extrinsics: Float[Tensor, "batch view 4 4"],
|
| 40 |
+
intrinsics: Float[Tensor, "batch view 3 3"],
|
| 41 |
+
near: Float[Tensor, "batch view"],
|
| 42 |
+
far: Float[Tensor, "batch view"],
|
| 43 |
+
image_shape: tuple[int, int],
|
| 44 |
+
depth_mode: DepthRenderingMode | None = None,
|
| 45 |
+
) -> DecoderOutput:
|
| 46 |
+
pass
|
src/model/decoder/decoder_splatting_cuda.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from einops import rearrange, repeat
|
| 6 |
+
from jaxtyping import Float
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
import torchvision
|
| 9 |
+
|
| 10 |
+
from ..types import Gaussians
|
| 11 |
+
# from .cuda_splatting import DepthRenderingMode, render_cuda
|
| 12 |
+
from .decoder import Decoder, DecoderOutput
|
| 13 |
+
from math import sqrt
|
| 14 |
+
from gsplat import rasterization
|
| 15 |
+
|
| 16 |
+
from ...misc.utils import vis_depth_map
|
| 17 |
+
|
| 18 |
+
DepthRenderingMode = Literal["depth", "disparity", "relative_disparity", "log"]
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class DecoderSplattingCUDACfg:
|
| 22 |
+
name: Literal["splatting_cuda"]
|
| 23 |
+
background_color: list[float]
|
| 24 |
+
make_scale_invariant: bool
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DecoderSplattingCUDA(Decoder[DecoderSplattingCUDACfg]):
|
| 28 |
+
background_color: Float[Tensor, "3"]
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
cfg: DecoderSplattingCUDACfg,
|
| 33 |
+
) -> None:
|
| 34 |
+
super().__init__(cfg)
|
| 35 |
+
self.make_scale_invariant = cfg.make_scale_invariant
|
| 36 |
+
self.register_buffer(
|
| 37 |
+
"background_color",
|
| 38 |
+
torch.tensor(cfg.background_color, dtype=torch.float32),
|
| 39 |
+
persistent=False,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def rendering_fn(
|
| 43 |
+
self,
|
| 44 |
+
gaussians: Gaussians,
|
| 45 |
+
extrinsics: Float[Tensor, "batch view 4 4"],
|
| 46 |
+
intrinsics: Float[Tensor, "batch view 3 3"],
|
| 47 |
+
near: Float[Tensor, "batch view"],
|
| 48 |
+
far: Float[Tensor, "batch view"],
|
| 49 |
+
image_shape: tuple[int, int],
|
| 50 |
+
depth_mode: DepthRenderingMode | None = None,
|
| 51 |
+
cam_rot_delta: Float[Tensor, "batch view 3"] | None = None,
|
| 52 |
+
cam_trans_delta: Float[Tensor, "batch view 3"] | None = None,
|
| 53 |
+
) -> DecoderOutput:
|
| 54 |
+
B, V, _, _ = intrinsics.shape
|
| 55 |
+
H, W = image_shape
|
| 56 |
+
rendered_imgs, rendered_depths, rendered_alphas = [], [], []
|
| 57 |
+
xyzs, opacitys, rotations, scales, features = gaussians.means, gaussians.opacities, gaussians.rotations, gaussians.scales, gaussians.harmonics.permute(0, 1, 3, 2).contiguous()
|
| 58 |
+
covariances = gaussians.covariances
|
| 59 |
+
for i in range(B):
|
| 60 |
+
xyz_i = xyzs[i].float()
|
| 61 |
+
feature_i = features[i].float()
|
| 62 |
+
covar_i = covariances[i].float()
|
| 63 |
+
scale_i = scales[i].float()
|
| 64 |
+
rotation_i = rotations[i].float()
|
| 65 |
+
opacity_i = opacitys[i].squeeze().float()
|
| 66 |
+
test_w2c_i = extrinsics[i].float().inverse() # (V, 4, 4)
|
| 67 |
+
test_intr_i_normalized = intrinsics[i].float()
|
| 68 |
+
# Denormalize the intrinsics into standred format
|
| 69 |
+
test_intr_i = test_intr_i_normalized.clone()
|
| 70 |
+
test_intr_i[:, 0] = test_intr_i_normalized[:, 0] * W
|
| 71 |
+
test_intr_i[:, 1] = test_intr_i_normalized[:, 1] * H
|
| 72 |
+
sh_degree = (int(sqrt(feature_i.shape[-2])) - 1)
|
| 73 |
+
|
| 74 |
+
rendering_list = []
|
| 75 |
+
rendering_depth_list = []
|
| 76 |
+
rendering_alpha_list = []
|
| 77 |
+
for j in range(V):
|
| 78 |
+
rendering, alpha, _ = rasterization(xyz_i, rotation_i, scale_i, opacity_i, feature_i,
|
| 79 |
+
test_w2c_i[j:j+1], test_intr_i[j:j+1], W, H, sh_degree=sh_degree,
|
| 80 |
+
# near_plane=near[i].mean(), far_plane=far[i].mean(),
|
| 81 |
+
render_mode="RGB+D", packed=False,
|
| 82 |
+
near_plane=1e-10,
|
| 83 |
+
backgrounds=self.background_color.unsqueeze(0).repeat(1, 1),
|
| 84 |
+
radius_clip=0.1,
|
| 85 |
+
covars=covar_i,
|
| 86 |
+
rasterize_mode='classic') # (V, H, W, 3)
|
| 87 |
+
rendering_img, rendering_depth = torch.split(rendering, [3, 1], dim=-1)
|
| 88 |
+
rendering_img = rendering_img.clamp(0.0, 1.0)
|
| 89 |
+
rendering_list.append(rendering_img.permute(0, 3, 1, 2))
|
| 90 |
+
rendering_depth_list.append(rendering_depth)
|
| 91 |
+
rendering_alpha_list.append(alpha)
|
| 92 |
+
rendered_depths.append(torch.cat(rendering_depth_list, dim=0).squeeze())
|
| 93 |
+
rendered_imgs.append(torch.cat(rendering_list, dim=0))
|
| 94 |
+
rendered_alphas.append(torch.cat(rendering_alpha_list, dim=0).squeeze())
|
| 95 |
+
return DecoderOutput(torch.stack(rendered_imgs), torch.stack(rendered_depths), torch.stack(rendered_alphas), lod_rendering=None)
|
| 96 |
+
|
| 97 |
+
def forward(
|
| 98 |
+
self,
|
| 99 |
+
gaussians: Gaussians,
|
| 100 |
+
extrinsics: Float[Tensor, "batch view 4 4"],
|
| 101 |
+
intrinsics: Float[Tensor, "batch view 3 3"],
|
| 102 |
+
near: Float[Tensor, "batch view"],
|
| 103 |
+
far: Float[Tensor, "batch view"],
|
| 104 |
+
image_shape: tuple[int, int],
|
| 105 |
+
depth_mode: DepthRenderingMode | None = None,
|
| 106 |
+
cam_rot_delta: Float[Tensor, "batch view 3"] | None = None,
|
| 107 |
+
cam_trans_delta: Float[Tensor, "batch view 3"] | None = None,
|
| 108 |
+
) -> DecoderOutput:
|
| 109 |
+
|
| 110 |
+
return self.rendering_fn(gaussians, extrinsics, intrinsics, near, far, image_shape, depth_mode, cam_rot_delta, cam_trans_delta)
|
| 111 |
+
|
src/model/encoder/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Union
|
| 2 |
+
|
| 3 |
+
from .encoder import Encoder
|
| 4 |
+
from .visualization.encoder_visualizer import EncoderVisualizer
|
| 5 |
+
from .anysplat import EncoderAnySplat, EncoderAnySplatCfg
|
| 6 |
+
|
| 7 |
+
ENCODERS = {
|
| 8 |
+
"anysplat": (EncoderAnySplat, None),
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
EncoderCfg = Union[EncoderAnySplatCfg]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_encoder(cfg: EncoderCfg) -> tuple[Encoder, Optional[EncoderVisualizer]]:
|
| 15 |
+
encoder, visualizer = ENCODERS[cfg.name]
|
| 16 |
+
encoder = encoder(cfg)
|
| 17 |
+
if visualizer is not None:
|
| 18 |
+
visualizer = visualizer(cfg.visualizer, encoder)
|
| 19 |
+
return encoder, visualizer
|
src/model/encoder/anysplat.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
|
| 3 |
+
# VGGT parts
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import List, Literal, Optional
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import torchvision
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 15 |
+
from jaxtyping import Float
|
| 16 |
+
from src.dataset.shims.bounds_shim import apply_bounds_shim
|
| 17 |
+
from src.dataset.shims.normalize_shim import apply_normalize_shim
|
| 18 |
+
from src.dataset.shims.patch_shim import apply_patch_shim
|
| 19 |
+
from src.dataset.types import BatchedExample, DataShim
|
| 20 |
+
from src.geometry.projection import sample_image_grid
|
| 21 |
+
|
| 22 |
+
from src.model.encoder.heads.vggt_dpt_gs_head import VGGT_DPT_GS_Head
|
| 23 |
+
from src.model.encoder.vggt.utils.geometry import (
|
| 24 |
+
batchify_unproject_depth_map_to_point_map,
|
| 25 |
+
unproject_depth_map_to_point_map,
|
| 26 |
+
)
|
| 27 |
+
from src.model.encoder.vggt.utils.pose_enc import pose_encoding_to_extri_intri
|
| 28 |
+
from torch import nn, Tensor
|
| 29 |
+
|
| 30 |
+
from ..types import Gaussians
|
| 31 |
+
from .backbone import Backbone, BackboneCfg, get_backbone
|
| 32 |
+
|
| 33 |
+
from .backbone.croco.misc import transpose_to_landscape
|
| 34 |
+
from .common.gaussian_adapter import (
|
| 35 |
+
GaussianAdapter,
|
| 36 |
+
GaussianAdapterCfg,
|
| 37 |
+
UnifiedGaussianAdapter,
|
| 38 |
+
)
|
| 39 |
+
from .encoder import Encoder, EncoderOutput
|
| 40 |
+
from .heads import head_factory
|
| 41 |
+
from .visualization.encoder_visualizer_epipolar_cfg import EncoderVisualizerEpipolarCfg
|
| 42 |
+
|
| 43 |
+
root_path = os.path.abspath(".")
|
| 44 |
+
sys.path.append(root_path)
|
| 45 |
+
from src.model.encoder.heads.head_modules import TransformerBlockSelfAttn
|
| 46 |
+
from src.model.encoder.vggt.heads.dpt_head import DPTHead
|
| 47 |
+
from src.model.encoder.vggt.layers.mlp import Mlp
|
| 48 |
+
from src.model.encoder.vggt.models.vggt import VGGT
|
| 49 |
+
|
| 50 |
+
inf = float("inf")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class OpacityMappingCfg:
|
| 55 |
+
initial: float
|
| 56 |
+
final: float
|
| 57 |
+
warm_up: int
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
class GSHeadParams:
|
| 62 |
+
dec_depth: int = 23
|
| 63 |
+
patch_size: tuple[int, int] = (14, 14)
|
| 64 |
+
enc_embed_dim: int = 2048
|
| 65 |
+
dec_embed_dim: int = 2048
|
| 66 |
+
feature_dim: int = 256
|
| 67 |
+
depth_mode = ("exp", -inf, inf)
|
| 68 |
+
conf_mode = True
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class EncoderAnySplatCfg:
|
| 73 |
+
name: Literal["anysplat"]
|
| 74 |
+
anchor_feat_dim: int
|
| 75 |
+
voxel_size: float
|
| 76 |
+
n_offsets: int
|
| 77 |
+
d_feature: int
|
| 78 |
+
add_view: bool
|
| 79 |
+
num_monocular_samples: int
|
| 80 |
+
backbone: BackboneCfg
|
| 81 |
+
visualizer: EncoderVisualizerEpipolarCfg
|
| 82 |
+
gaussian_adapter: GaussianAdapterCfg
|
| 83 |
+
apply_bounds_shim: bool
|
| 84 |
+
opacity_mapping: OpacityMappingCfg
|
| 85 |
+
gaussians_per_pixel: int
|
| 86 |
+
num_surfaces: int
|
| 87 |
+
gs_params_head_type: str
|
| 88 |
+
input_mean: tuple[float, float, float] = (0.5, 0.5, 0.5)
|
| 89 |
+
input_std: tuple[float, float, float] = (0.5, 0.5, 0.5)
|
| 90 |
+
pretrained_weights: str = ""
|
| 91 |
+
pose_free: bool = True
|
| 92 |
+
pred_pose: bool = True
|
| 93 |
+
gt_pose_to_pts: bool = False
|
| 94 |
+
gs_prune: bool = False
|
| 95 |
+
opacity_threshold: float = 0.001
|
| 96 |
+
gs_keep_ratio: float = 1.0
|
| 97 |
+
pred_head_type: Literal["depth", "point"] = "point"
|
| 98 |
+
freeze_backbone: bool = False
|
| 99 |
+
freeze_module: Literal[
|
| 100 |
+
"all",
|
| 101 |
+
"global",
|
| 102 |
+
"frame",
|
| 103 |
+
"patch_embed",
|
| 104 |
+
"patch_embed+frame",
|
| 105 |
+
"patch_embed+global",
|
| 106 |
+
"global+frame",
|
| 107 |
+
"None",
|
| 108 |
+
] = "None"
|
| 109 |
+
distill: bool = False
|
| 110 |
+
render_conf: bool = False
|
| 111 |
+
opacity_conf: bool = False
|
| 112 |
+
conf_threshold: float = 0.1
|
| 113 |
+
intermediate_layer_idx: Optional[List[int]] = None
|
| 114 |
+
voxelize: bool = False
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def rearrange_head(feat, patch_size, H, W):
|
| 118 |
+
B = feat.shape[0]
|
| 119 |
+
feat = feat.transpose(-1, -2).view(B, -1, H // patch_size, W // patch_size)
|
| 120 |
+
feat = F.pixel_shuffle(feat, patch_size) # B,D,H,W
|
| 121 |
+
feat = rearrange(feat, "b d h w -> b (h w) d")
|
| 122 |
+
return feat
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class EncoderAnySplat(Encoder[EncoderAnySplatCfg]):
|
| 126 |
+
backbone: nn.Module
|
| 127 |
+
gaussian_adapter: GaussianAdapter
|
| 128 |
+
|
| 129 |
+
def __init__(self, cfg: EncoderAnySplatCfg) -> None:
|
| 130 |
+
super().__init__(cfg)
|
| 131 |
+
model_full = VGGT()
|
| 132 |
+
self.aggregator = model_full.aggregator.to(torch.bfloat16)
|
| 133 |
+
self.freeze_backbone = cfg.freeze_backbone
|
| 134 |
+
self.distill = cfg.distill
|
| 135 |
+
self.pred_pose = cfg.pred_pose
|
| 136 |
+
|
| 137 |
+
self.camera_head = model_full.camera_head
|
| 138 |
+
if self.cfg.pred_head_type == "depth":
|
| 139 |
+
self.depth_head = model_full.depth_head
|
| 140 |
+
else:
|
| 141 |
+
self.point_head = model_full.point_head
|
| 142 |
+
|
| 143 |
+
if self.distill:
|
| 144 |
+
self.distill_aggregator = copy.deepcopy(self.aggregator)
|
| 145 |
+
self.distill_camera_head = copy.deepcopy(self.camera_head)
|
| 146 |
+
self.distill_depth_head = copy.deepcopy(self.depth_head)
|
| 147 |
+
for module in [
|
| 148 |
+
self.distill_aggregator,
|
| 149 |
+
self.distill_camera_head,
|
| 150 |
+
self.distill_depth_head,
|
| 151 |
+
]:
|
| 152 |
+
for param in module.parameters():
|
| 153 |
+
param.requires_grad = False
|
| 154 |
+
param.data = param.data.cpu()
|
| 155 |
+
|
| 156 |
+
if self.freeze_backbone:
|
| 157 |
+
# Freeze backbone components
|
| 158 |
+
if self.cfg.pred_head_type == "depth":
|
| 159 |
+
for module in [self.aggregator, self.camera_head, self.depth_head]:
|
| 160 |
+
for param in module.parameters():
|
| 161 |
+
param.requires_grad = False
|
| 162 |
+
else:
|
| 163 |
+
for module in [self.aggregator, self.camera_head, self.point_head]:
|
| 164 |
+
for param in module.parameters():
|
| 165 |
+
param.requires_grad = False
|
| 166 |
+
else:
|
| 167 |
+
# aggregator freeze
|
| 168 |
+
freeze_module = self.cfg.freeze_module
|
| 169 |
+
if freeze_module == "None":
|
| 170 |
+
pass
|
| 171 |
+
|
| 172 |
+
elif freeze_module == "all":
|
| 173 |
+
for param in self.aggregator.parameters():
|
| 174 |
+
param.requires_grad = False
|
| 175 |
+
|
| 176 |
+
else:
|
| 177 |
+
module_pairs = {
|
| 178 |
+
"patch_embed+frame": ["patch_embed", "frame"],
|
| 179 |
+
"patch_embed+global": ["patch_embed", "global"],
|
| 180 |
+
"global+frame": ["global", "frame"],
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if freeze_module in module_pairs:
|
| 184 |
+
for name, param in self.aggregator.named_parameters():
|
| 185 |
+
if any(m in name for m in module_pairs[freeze_module]):
|
| 186 |
+
param.requires_grad = False
|
| 187 |
+
else:
|
| 188 |
+
for name, param in self.named_parameters():
|
| 189 |
+
param.requires_grad = (
|
| 190 |
+
freeze_module not in name and "distill" not in name
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
self.pose_free = cfg.pose_free
|
| 194 |
+
if self.pose_free:
|
| 195 |
+
self.gaussian_adapter = UnifiedGaussianAdapter(cfg.gaussian_adapter)
|
| 196 |
+
else:
|
| 197 |
+
self.gaussian_adapter = GaussianAdapter(cfg.gaussian_adapter)
|
| 198 |
+
|
| 199 |
+
self.raw_gs_dim = 1 + self.gaussian_adapter.d_in # 1 for opacity
|
| 200 |
+
self.voxel_size = cfg.voxel_size
|
| 201 |
+
self.gs_params_head_type = cfg.gs_params_head_type
|
| 202 |
+
# fake backbone for head parameters
|
| 203 |
+
head_params = GSHeadParams()
|
| 204 |
+
self.gaussian_param_head = VGGT_DPT_GS_Head(
|
| 205 |
+
dim_in=2048,
|
| 206 |
+
patch_size=head_params.patch_size,
|
| 207 |
+
output_dim=self.raw_gs_dim + 1,
|
| 208 |
+
activation="norm_exp",
|
| 209 |
+
conf_activation="expp1",
|
| 210 |
+
features=head_params.feature_dim,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def map_pdf_to_opacity(
|
| 214 |
+
self,
|
| 215 |
+
pdf: Float[Tensor, " *batch"],
|
| 216 |
+
global_step: int,
|
| 217 |
+
) -> Float[Tensor, " *batch"]:
|
| 218 |
+
# https://www.desmos.com/calculator/opvwti3ba9
|
| 219 |
+
|
| 220 |
+
# Figure out the exponent.
|
| 221 |
+
cfg = self.cfg.opacity_mapping
|
| 222 |
+
x = cfg.initial + min(global_step / cfg.warm_up, 1) * (cfg.final - cfg.initial)
|
| 223 |
+
exponent = 2**x
|
| 224 |
+
|
| 225 |
+
# Map the probability density to an opacity.
|
| 226 |
+
return 0.5 * (1 - (1 - pdf) ** exponent + pdf ** (1 / exponent))
|
| 227 |
+
|
| 228 |
+
def normalize_pts3d(self, pts3ds, valid_masks, original_extrinsics=None):
|
| 229 |
+
# normalize pts_all
|
| 230 |
+
B = pts3ds.shape[0]
|
| 231 |
+
pts3d_norms = []
|
| 232 |
+
scale_factors = []
|
| 233 |
+
for bs in range(B):
|
| 234 |
+
pts3d, valid_mask = pts3ds[bs], valid_masks[bs]
|
| 235 |
+
if original_extrinsics is not None:
|
| 236 |
+
camera_c2w = original_extrinsics[bs]
|
| 237 |
+
first_camera_w2c = (
|
| 238 |
+
camera_c2w[0].inverse().unsqueeze(0).repeat(pts3d.shape[0], 1, 1)
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
pts3d_homo = torch.cat(
|
| 242 |
+
[pts3d, torch.ones_like(pts3d[:, :, :, :1])], dim=-1
|
| 243 |
+
)
|
| 244 |
+
transformed_pts3d = torch.bmm(
|
| 245 |
+
first_camera_w2c, pts3d_homo.flatten(1, 2).transpose(1, 2)
|
| 246 |
+
).transpose(1, 2)[..., :3]
|
| 247 |
+
scene_scale = torch.norm(
|
| 248 |
+
transformed_pts3d.flatten(0, 1)[valid_mask.flatten(0, 2).bool()],
|
| 249 |
+
dim=-1,
|
| 250 |
+
).mean()
|
| 251 |
+
else:
|
| 252 |
+
transformed_pts3d = pts3d[valid_mask]
|
| 253 |
+
dis = transformed_pts3d.norm(dim=-1)
|
| 254 |
+
scene_scale = dis.mean().clip(min=1e-8)
|
| 255 |
+
# pts3d_norm[bs] = pts3d[bs] / scene_scale
|
| 256 |
+
pts3d_norms.append(pts3d / scene_scale)
|
| 257 |
+
scale_factors.append(scene_scale)
|
| 258 |
+
return torch.stack(pts3d_norms, dim=0), torch.stack(scale_factors, dim=0)
|
| 259 |
+
|
| 260 |
+
def align_pts_all_with_pts3d(
|
| 261 |
+
self, pts_all, pts3d, valid_mask, original_extrinsics=None
|
| 262 |
+
):
|
| 263 |
+
# align pts_all with pts3d
|
| 264 |
+
B = pts_all.shape[0]
|
| 265 |
+
|
| 266 |
+
# follow vggt's normalization implementation
|
| 267 |
+
pts3d_norm, scale_factor = self.normalize_pts3d(
|
| 268 |
+
pts3d, valid_mask, original_extrinsics
|
| 269 |
+
) # check if this is correct
|
| 270 |
+
pts_all = pts_all * scale_factor.view(B, 1, 1, 1, 1)
|
| 271 |
+
|
| 272 |
+
return pts_all
|
| 273 |
+
|
| 274 |
+
def pad_tensor_list(self, tensor_list, pad_shape, value=0.0):
|
| 275 |
+
padded = []
|
| 276 |
+
for t in tensor_list:
|
| 277 |
+
pad_len = pad_shape[0] - t.shape[0]
|
| 278 |
+
if pad_len > 0:
|
| 279 |
+
padding = torch.full(
|
| 280 |
+
(pad_len, *t.shape[1:]), value, device=t.device, dtype=t.dtype
|
| 281 |
+
)
|
| 282 |
+
t = torch.cat([t, padding], dim=0)
|
| 283 |
+
padded.append(t)
|
| 284 |
+
return torch.stack(padded)
|
| 285 |
+
|
| 286 |
+
def voxelizaton_with_fusion(self, img_feat, pts3d, voxel_size, conf=None):
|
| 287 |
+
# img_feat: B*V, C, H, W
|
| 288 |
+
# pts3d: B*V, 3, H, W
|
| 289 |
+
V, C, H, W = img_feat.shape
|
| 290 |
+
pts3d_flatten = pts3d.permute(0, 2, 3, 1).flatten(0, 2)
|
| 291 |
+
|
| 292 |
+
voxel_indices = (pts3d_flatten / voxel_size).round().int() # [B*V*N, 3]
|
| 293 |
+
unique_voxels, inverse_indices, counts = torch.unique(
|
| 294 |
+
voxel_indices, dim=0, return_inverse=True, return_counts=True
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
# Flatten confidence scores and features
|
| 298 |
+
conf_flat = conf.flatten() # [B*V*N]
|
| 299 |
+
anchor_feats_flat = img_feat.permute(0, 2, 3, 1).flatten(0, 2) # [B*V*N, ...]
|
| 300 |
+
|
| 301 |
+
# Compute softmax weights per voxel
|
| 302 |
+
conf_voxel_max, _ = scatter_max(conf_flat, inverse_indices, dim=0)
|
| 303 |
+
conf_exp = torch.exp(conf_flat - conf_voxel_max[inverse_indices])
|
| 304 |
+
voxel_weights = scatter_add(
|
| 305 |
+
conf_exp, inverse_indices, dim=0
|
| 306 |
+
) # [num_unique_voxels]
|
| 307 |
+
weights = (conf_exp / (voxel_weights[inverse_indices] + 1e-6)).unsqueeze(
|
| 308 |
+
-1
|
| 309 |
+
) # [B*V*N, 1]
|
| 310 |
+
|
| 311 |
+
# Compute weighted average of positions and features
|
| 312 |
+
weighted_pts = pts3d_flatten * weights
|
| 313 |
+
weighted_feats = anchor_feats_flat.squeeze(1) * weights
|
| 314 |
+
|
| 315 |
+
# Aggregate per voxel
|
| 316 |
+
voxel_pts = scatter_add(
|
| 317 |
+
weighted_pts, inverse_indices, dim=0
|
| 318 |
+
) # [num_unique_voxels, 3]
|
| 319 |
+
voxel_feats = scatter_add(
|
| 320 |
+
weighted_feats, inverse_indices, dim=0
|
| 321 |
+
) # [num_unique_voxels, feat_dim]
|
| 322 |
+
|
| 323 |
+
return voxel_pts, voxel_feats
|
| 324 |
+
|
| 325 |
+
def forward(
|
| 326 |
+
self,
|
| 327 |
+
image: torch.Tensor,
|
| 328 |
+
global_step: int = 0,
|
| 329 |
+
visualization_dump: Optional[dict] = None,
|
| 330 |
+
) -> Gaussians:
|
| 331 |
+
device = image.device
|
| 332 |
+
b, v, _, h, w = image.shape
|
| 333 |
+
distill_infos = {}
|
| 334 |
+
if self.distill:
|
| 335 |
+
distill_image = image.clone().detach()
|
| 336 |
+
for module in [
|
| 337 |
+
self.distill_aggregator,
|
| 338 |
+
self.distill_camera_head,
|
| 339 |
+
self.distill_depth_head,
|
| 340 |
+
]:
|
| 341 |
+
for param in module.parameters():
|
| 342 |
+
param.data = param.data.to(device, non_blocking=True)
|
| 343 |
+
|
| 344 |
+
with torch.no_grad():
|
| 345 |
+
# Process with bfloat16 precision
|
| 346 |
+
with torch.amp.autocast("cuda", enabled=True, dtype=torch.bfloat16):
|
| 347 |
+
distill_aggregated_tokens_list, distill_patch_start_idx = (
|
| 348 |
+
self.distill_aggregator(
|
| 349 |
+
distill_image.to(torch.bfloat16),
|
| 350 |
+
intermediate_layer_idx=self.cfg.intermediate_layer_idx,
|
| 351 |
+
)
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# Process with default precision
|
| 355 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 356 |
+
# Get camera pose information
|
| 357 |
+
distill_pred_pose_enc_list = self.distill_camera_head(
|
| 358 |
+
distill_aggregated_tokens_list
|
| 359 |
+
)
|
| 360 |
+
last_distill_pred_pose_enc = distill_pred_pose_enc_list[-1]
|
| 361 |
+
distill_extrinsic, distill_intrinsic = pose_encoding_to_extri_intri(
|
| 362 |
+
last_distill_pred_pose_enc, image.shape[-2:]
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Get depth information
|
| 366 |
+
distill_depth_map, distill_depth_conf = self.distill_depth_head(
|
| 367 |
+
distill_aggregated_tokens_list,
|
| 368 |
+
images=distill_image,
|
| 369 |
+
patch_start_idx=distill_patch_start_idx,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
# Convert depth to 3D points
|
| 373 |
+
distill_pts_all = batchify_unproject_depth_map_to_point_map(
|
| 374 |
+
distill_depth_map, distill_extrinsic, distill_intrinsic
|
| 375 |
+
)
|
| 376 |
+
# Store results
|
| 377 |
+
distill_infos["pred_pose_enc_list"] = distill_pred_pose_enc_list
|
| 378 |
+
distill_infos["pts_all"] = distill_pts_all
|
| 379 |
+
distill_infos["depth_map"] = distill_depth_map
|
| 380 |
+
|
| 381 |
+
conf_threshold = torch.quantile(
|
| 382 |
+
distill_depth_conf.flatten(2, 3), 0.3, dim=-1, keepdim=True
|
| 383 |
+
) # Get threshold for each view
|
| 384 |
+
conf_mask = distill_depth_conf > conf_threshold.unsqueeze(-1)
|
| 385 |
+
distill_infos["conf_mask"] = conf_mask
|
| 386 |
+
|
| 387 |
+
for module in [
|
| 388 |
+
self.distill_aggregator,
|
| 389 |
+
self.distill_camera_head,
|
| 390 |
+
self.distill_depth_head,
|
| 391 |
+
]:
|
| 392 |
+
for param in module.parameters():
|
| 393 |
+
param.data = param.data.cpu()
|
| 394 |
+
# Clean up to save memory
|
| 395 |
+
del distill_aggregated_tokens_list, distill_patch_start_idx
|
| 396 |
+
del distill_pred_pose_enc_list, last_distill_pred_pose_enc
|
| 397 |
+
del distill_extrinsic, distill_intrinsic
|
| 398 |
+
del distill_depth_map, distill_depth_conf
|
| 399 |
+
torch.cuda.empty_cache()
|
| 400 |
+
|
| 401 |
+
with torch.amp.autocast("cuda", enabled=True, dtype=torch.bfloat16):
|
| 402 |
+
aggregated_tokens_list, patch_start_idx = self.aggregator(
|
| 403 |
+
image.to(torch.bfloat16),
|
| 404 |
+
intermediate_layer_idx=self.cfg.intermediate_layer_idx,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
with torch.amp.autocast("cuda", enabled=False):
|
| 408 |
+
pred_pose_enc_list = self.camera_head(aggregated_tokens_list)
|
| 409 |
+
last_pred_pose_enc = pred_pose_enc_list[-1]
|
| 410 |
+
extrinsic, intrinsic = pose_encoding_to_extri_intri(
|
| 411 |
+
last_pred_pose_enc, image.shape[-2:]
|
| 412 |
+
) # only for debug
|
| 413 |
+
|
| 414 |
+
if self.cfg.pred_head_type == "point":
|
| 415 |
+
pts_all, pts_conf = self.point_head(
|
| 416 |
+
aggregated_tokens_list,
|
| 417 |
+
images=image,
|
| 418 |
+
patch_start_idx=patch_start_idx,
|
| 419 |
+
)
|
| 420 |
+
elif self.cfg.pred_head_type == "depth":
|
| 421 |
+
depth_map, depth_conf = self.depth_head(
|
| 422 |
+
aggregated_tokens_list,
|
| 423 |
+
images=image,
|
| 424 |
+
patch_start_idx=patch_start_idx,
|
| 425 |
+
)
|
| 426 |
+
pts_all = batchify_unproject_depth_map_to_point_map(
|
| 427 |
+
depth_map, extrinsic, intrinsic
|
| 428 |
+
)
|
| 429 |
+
else:
|
| 430 |
+
raise ValueError(f"Invalid pred_head_type: {self.cfg.pred_head_type}")
|
| 431 |
+
|
| 432 |
+
if self.cfg.render_conf:
|
| 433 |
+
conf_valid = torch.quantile(
|
| 434 |
+
depth_conf.flatten(0, 1), self.cfg.conf_threshold
|
| 435 |
+
)
|
| 436 |
+
conf_valid_mask = depth_conf > conf_valid
|
| 437 |
+
else:
|
| 438 |
+
conf_valid_mask = torch.ones_like(depth_conf, dtype=torch.bool)
|
| 439 |
+
|
| 440 |
+
# dpt style gs_head input format
|
| 441 |
+
out = self.gaussian_param_head(
|
| 442 |
+
aggregated_tokens_list,
|
| 443 |
+
pts_all.flatten(0, 1).permute(0, 3, 1, 2),
|
| 444 |
+
image,
|
| 445 |
+
patch_start_idx=patch_start_idx,
|
| 446 |
+
image_size=(h, w),
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
del aggregated_tokens_list, patch_start_idx
|
| 450 |
+
torch.cuda.empty_cache()
|
| 451 |
+
|
| 452 |
+
pts_flat = pts_all.flatten(2, 3)
|
| 453 |
+
scene_scale = pts_flat.norm(dim=-1).mean().clip(min=1e-8)
|
| 454 |
+
|
| 455 |
+
anchor_feats, conf = out[:, :, : self.raw_gs_dim], out[:, :, self.raw_gs_dim]
|
| 456 |
+
|
| 457 |
+
neural_feats_list, neural_pts_list = [], []
|
| 458 |
+
if self.cfg.voxelize:
|
| 459 |
+
for b_i in range(b):
|
| 460 |
+
neural_pts, neural_feats = self.voxelizaton_with_fusion(
|
| 461 |
+
anchor_feats[b_i],
|
| 462 |
+
pts_all[b_i].permute(0, 3, 1, 2).contiguous(),
|
| 463 |
+
self.voxel_size,
|
| 464 |
+
conf=conf[b_i],
|
| 465 |
+
)
|
| 466 |
+
neural_feats_list.append(neural_feats)
|
| 467 |
+
neural_pts_list.append(neural_pts)
|
| 468 |
+
else:
|
| 469 |
+
for b_i in range(b):
|
| 470 |
+
neural_feats_list.append(
|
| 471 |
+
anchor_feats[b_i].permute(0, 2, 3, 1)[conf_valid_mask[b_i]]
|
| 472 |
+
)
|
| 473 |
+
neural_pts_list.append(pts_all[b_i][conf_valid_mask[b_i]])
|
| 474 |
+
|
| 475 |
+
max_voxels = max(f.shape[0] for f in neural_feats_list)
|
| 476 |
+
neural_feats = self.pad_tensor_list(
|
| 477 |
+
neural_feats_list, (max_voxels,), value=-1e10
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
neural_pts = self.pad_tensor_list(
|
| 481 |
+
neural_pts_list, (max_voxels,), -1e4
|
| 482 |
+
) # -1 == invalid voxel
|
| 483 |
+
|
| 484 |
+
depths = neural_pts[..., -1].unsqueeze(-1)
|
| 485 |
+
densities = neural_feats[..., 0].sigmoid()
|
| 486 |
+
|
| 487 |
+
assert len(densities.shape) == 2, "the shape of densities should be (B, N)"
|
| 488 |
+
assert neural_pts.shape[1] > 1, "the number of voxels should be greater than 1"
|
| 489 |
+
|
| 490 |
+
opacity = self.map_pdf_to_opacity(densities, global_step).squeeze(-1)
|
| 491 |
+
if self.cfg.opacity_conf:
|
| 492 |
+
shift = torch.quantile(depth_conf, self.cfg.conf_threshold)
|
| 493 |
+
opacity = opacity * torch.sigmoid(depth_conf - shift)[
|
| 494 |
+
conf_valid_mask
|
| 495 |
+
].unsqueeze(
|
| 496 |
+
0
|
| 497 |
+
) # little bit hacky
|
| 498 |
+
|
| 499 |
+
# GS Prune, but only works when bs = 1
|
| 500 |
+
# if want to support bs > 1, need to random prune gaussians based on the rank of opacity like LongLRM
|
| 501 |
+
# Note: we not prune gaussians here, but we will try it in the future
|
| 502 |
+
if self.cfg.gs_prune and b == 1:
|
| 503 |
+
opacity_threshold = self.cfg.opacity_threshold
|
| 504 |
+
gaussian_usage = opacity > opacity_threshold # (B, N)
|
| 505 |
+
|
| 506 |
+
print(
|
| 507 |
+
f"based on opacity threshold {opacity_threshold}, pruned {gaussian_usage.shape[1] - neural_pts.shape[1]} gaussians out of {gaussian_usage.shape[1]}"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
if (gaussian_usage.sum() / gaussian_usage.numel()) > self.cfg.gs_keep_ratio:
|
| 511 |
+
# rank by opacity
|
| 512 |
+
num_keep = int(gaussian_usage.shape[1] * self.cfg.gs_keep_ratio)
|
| 513 |
+
idx_sort = opacity.argsort(dim=1, descending=True)
|
| 514 |
+
keep_idx = idx_sort[:, :num_keep]
|
| 515 |
+
gaussian_usage = torch.zeros_like(gaussian_usage, dtype=torch.bool)
|
| 516 |
+
gaussian_usage.scatter_(1, keep_idx, True)
|
| 517 |
+
|
| 518 |
+
neural_pts = neural_pts[gaussian_usage].view(b, -1, 3).contiguous()
|
| 519 |
+
depths = depths[gaussian_usage].view(b, -1, 1).contiguous()
|
| 520 |
+
neural_feats = (
|
| 521 |
+
neural_feats[gaussian_usage].view(b, -1, self.raw_gs_dim).contiguous()
|
| 522 |
+
)
|
| 523 |
+
opacity = opacity[gaussian_usage].view(b, -1).contiguous()
|
| 524 |
+
|
| 525 |
+
print(
|
| 526 |
+
f"finally pruned {gaussian_usage.shape[1] - neural_pts.shape[1]} gaussians out of {gaussian_usage.shape[1]}"
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
gaussians = self.gaussian_adapter.forward(
|
| 530 |
+
neural_pts,
|
| 531 |
+
depths,
|
| 532 |
+
opacity,
|
| 533 |
+
neural_feats[..., 1:].squeeze(2),
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
if visualization_dump is not None:
|
| 537 |
+
visualization_dump["depth"] = rearrange(
|
| 538 |
+
pts_all[..., -1].flatten(2, 3).unsqueeze(-1).unsqueeze(-1),
|
| 539 |
+
"b v (h w) srf s -> b v h w srf s",
|
| 540 |
+
h=h,
|
| 541 |
+
w=w,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
infos = {}
|
| 545 |
+
infos["scene_scale"] = scene_scale
|
| 546 |
+
infos["voxelize_ratio"] = densities.shape[1] / (h * w * v)
|
| 547 |
+
|
| 548 |
+
print(
|
| 549 |
+
f"scene scale: {scene_scale:.3f}, pixel-wise num: {h*w*v}, after voxelize: {neural_pts.shape[1]}, voxelize ratio: {infos['voxelize_ratio']:.3f}"
|
| 550 |
+
)
|
| 551 |
+
print(
|
| 552 |
+
f"Gaussians attributes: \n"
|
| 553 |
+
f"opacities: mean: {gaussians.opacities.mean()}, min: {gaussians.opacities.min()}, max: {gaussians.opacities.max()} \n"
|
| 554 |
+
f"scales: mean: {gaussians.scales.mean()}, min: {gaussians.scales.min()}, max: {gaussians.scales.max()}"
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
print("B:", b, "V:", v, "H:", h, "W:", w)
|
| 558 |
+
extrinsic_padding = (
|
| 559 |
+
torch.tensor([0, 0, 0, 1], device=device, dtype=extrinsic.dtype)
|
| 560 |
+
.view(1, 1, 1, 4)
|
| 561 |
+
.repeat(b, v, 1, 1)
|
| 562 |
+
)
|
| 563 |
+
intrinsic = intrinsic.clone() # Create a new tensor
|
| 564 |
+
intrinsic = torch.stack(
|
| 565 |
+
[intrinsic[:, :, 0] / w, intrinsic[:, :, 1] / h, intrinsic[:, :, 2]], dim=2
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
return EncoderOutput(
|
| 569 |
+
gaussians=gaussians,
|
| 570 |
+
pred_pose_enc_list=pred_pose_enc_list,
|
| 571 |
+
pred_context_pose=dict(
|
| 572 |
+
extrinsic=torch.cat([extrinsic, extrinsic_padding], dim=2).inverse(),
|
| 573 |
+
intrinsic=intrinsic,
|
| 574 |
+
),
|
| 575 |
+
depth_dict=dict(depth=depth_map, conf_valid_mask=conf_valid_mask),
|
| 576 |
+
infos=infos,
|
| 577 |
+
distill_infos=distill_infos,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
def get_data_shim(self) -> DataShim:
|
| 581 |
+
def data_shim(batch: BatchedExample) -> BatchedExample:
|
| 582 |
+
batch = apply_normalize_shim(
|
| 583 |
+
batch,
|
| 584 |
+
self.cfg.input_mean,
|
| 585 |
+
self.cfg.input_std,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
return batch
|
| 589 |
+
|
| 590 |
+
return data_shim
|
src/model/encoder/backbone/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .backbone import Backbone
|
| 5 |
+
from .backbone_croco_multiview import AsymmetricCroCoMulti
|
| 6 |
+
from .backbone_dino import BackboneDino, BackboneDinoCfg
|
| 7 |
+
from .backbone_resnet import BackboneResnet, BackboneResnetCfg
|
| 8 |
+
from .backbone_croco import AsymmetricCroCo, BackboneCrocoCfg
|
| 9 |
+
|
| 10 |
+
BACKBONES: dict[str, Backbone[Any]] = {
|
| 11 |
+
"resnet": BackboneResnet,
|
| 12 |
+
"dino": BackboneDino,
|
| 13 |
+
"croco": AsymmetricCroCo,
|
| 14 |
+
"croco_multi": AsymmetricCroCoMulti,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
BackboneCfg = BackboneResnetCfg | BackboneDinoCfg | BackboneCrocoCfg
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_backbone(cfg: BackboneCfg, d_in: int = 3) -> nn.Module:
|
| 21 |
+
return BACKBONES[cfg.name](cfg, d_in)
|
src/model/encoder/backbone/backbone.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Generic, TypeVar
|
| 3 |
+
|
| 4 |
+
from jaxtyping import Float
|
| 5 |
+
from torch import Tensor, nn
|
| 6 |
+
|
| 7 |
+
from src.dataset.types import BatchedViews
|
| 8 |
+
|
| 9 |
+
T = TypeVar("T")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Backbone(nn.Module, ABC, Generic[T]):
|
| 13 |
+
cfg: T
|
| 14 |
+
|
| 15 |
+
def __init__(self, cfg: T) -> None:
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.cfg = cfg
|
| 18 |
+
|
| 19 |
+
@abstractmethod
|
| 20 |
+
def forward(
|
| 21 |
+
self,
|
| 22 |
+
context: BatchedViews,
|
| 23 |
+
) -> Float[Tensor, "batch view d_out height width"]:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
@abstractmethod
|
| 28 |
+
def d_out(self) -> int:
|
| 29 |
+
pass
|
src/model/encoder/backbone/backbone_croco.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
from .croco.blocks import DecoderBlock
|
| 9 |
+
from .croco.croco import CroCoNet
|
| 10 |
+
from .croco.misc import fill_default_args, freeze_all_params, transpose_to_landscape, is_symmetrized, interleave, \
|
| 11 |
+
make_batch_symmetric
|
| 12 |
+
from .croco.patch_embed import get_patch_embed
|
| 13 |
+
from .backbone import Backbone
|
| 14 |
+
from src.geometry.camera_emb import get_intrinsic_embedding
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
inf = float('inf')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
croco_params = {
|
| 21 |
+
'ViTLarge_BaseDecoder': {
|
| 22 |
+
'enc_depth': 24,
|
| 23 |
+
'dec_depth': 12,
|
| 24 |
+
'enc_embed_dim': 1024,
|
| 25 |
+
'dec_embed_dim': 768,
|
| 26 |
+
'enc_num_heads': 16,
|
| 27 |
+
'dec_num_heads': 12,
|
| 28 |
+
'pos_embed': 'RoPE100',
|
| 29 |
+
'img_size': (512, 512),
|
| 30 |
+
},
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
default_dust3r_params = {
|
| 34 |
+
'enc_depth': 24,
|
| 35 |
+
'dec_depth': 12,
|
| 36 |
+
'enc_embed_dim': 1024,
|
| 37 |
+
'dec_embed_dim': 768,
|
| 38 |
+
'enc_num_heads': 16,
|
| 39 |
+
'dec_num_heads': 12,
|
| 40 |
+
'pos_embed': 'RoPE100',
|
| 41 |
+
'patch_embed_cls': 'PatchEmbedDust3R',
|
| 42 |
+
'img_size': (512, 512),
|
| 43 |
+
'head_type': 'dpt',
|
| 44 |
+
'output_mode': 'pts3d',
|
| 45 |
+
'depth_mode': ('exp', -inf, inf),
|
| 46 |
+
'conf_mode': ('exp', 1, inf)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class BackboneCrocoCfg:
|
| 52 |
+
name: Literal["croco", "croco_multi"]
|
| 53 |
+
model: Literal["ViTLarge_BaseDecoder", "ViTBase_SmallDecoder", "ViTBase_BaseDecoder"] # keep interface for the last two models, but they are not supported
|
| 54 |
+
patch_embed_cls: str = 'PatchEmbedDust3R' # PatchEmbedDust3R or ManyAR_PatchEmbed
|
| 55 |
+
asymmetry_decoder: bool = True
|
| 56 |
+
intrinsics_embed_loc: Literal["encoder", "decoder", "none"] = 'none'
|
| 57 |
+
intrinsics_embed_degree: int = 0
|
| 58 |
+
intrinsics_embed_type: Literal["pixelwise", "linear", "token"] = 'token' # linear or dpt
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AsymmetricCroCo(CroCoNet):
|
| 62 |
+
""" Two siamese encoders, followed by two decoders.
|
| 63 |
+
The goal is to output 3d points directly, both images in view1's frame
|
| 64 |
+
(hence the asymmetry).
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, cfg: BackboneCrocoCfg, d_in: int) -> None:
|
| 68 |
+
|
| 69 |
+
self.intrinsics_embed_loc = cfg.intrinsics_embed_loc
|
| 70 |
+
self.intrinsics_embed_degree = cfg.intrinsics_embed_degree
|
| 71 |
+
self.intrinsics_embed_type = cfg.intrinsics_embed_type
|
| 72 |
+
self.intrinsics_embed_encoder_dim = 0
|
| 73 |
+
self.intrinsics_embed_decoder_dim = 0
|
| 74 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 75 |
+
self.intrinsics_embed_encoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3
|
| 76 |
+
elif self.intrinsics_embed_loc == 'decoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 77 |
+
self.intrinsics_embed_decoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3
|
| 78 |
+
|
| 79 |
+
self.patch_embed_cls = cfg.patch_embed_cls
|
| 80 |
+
self.croco_args = fill_default_args(croco_params[cfg.model], CroCoNet.__init__)
|
| 81 |
+
|
| 82 |
+
super().__init__(**croco_params[cfg.model])
|
| 83 |
+
|
| 84 |
+
if cfg.asymmetry_decoder:
|
| 85 |
+
self.dec_blocks2 = deepcopy(self.dec_blocks) # This is used in DUSt3R and MASt3R
|
| 86 |
+
|
| 87 |
+
if self.intrinsics_embed_type == 'linear' or self.intrinsics_embed_type == 'token':
|
| 88 |
+
self.intrinsic_encoder = nn.Linear(9, 1024)
|
| 89 |
+
|
| 90 |
+
# self.set_freeze(freeze)
|
| 91 |
+
|
| 92 |
+
def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768, in_chans=3):
|
| 93 |
+
in_chans = in_chans + self.intrinsics_embed_encoder_dim
|
| 94 |
+
self.patch_embed = get_patch_embed(self.patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans)
|
| 95 |
+
|
| 96 |
+
def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec):
|
| 97 |
+
self.dec_depth = dec_depth
|
| 98 |
+
self.dec_embed_dim = dec_embed_dim
|
| 99 |
+
# transfer from encoder to decoder
|
| 100 |
+
enc_embed_dim = enc_embed_dim + self.intrinsics_embed_decoder_dim
|
| 101 |
+
self.decoder_embed = nn.Linear(enc_embed_dim, dec_embed_dim, bias=True)
|
| 102 |
+
# transformer for the decoder
|
| 103 |
+
self.dec_blocks = nn.ModuleList([
|
| 104 |
+
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)
|
| 105 |
+
for i in range(dec_depth)])
|
| 106 |
+
# final norm layer
|
| 107 |
+
self.dec_norm = norm_layer(dec_embed_dim)
|
| 108 |
+
|
| 109 |
+
def load_state_dict(self, ckpt, **kw):
|
| 110 |
+
# duplicate all weights for the second decoder if not present
|
| 111 |
+
new_ckpt = dict(ckpt)
|
| 112 |
+
if not any(k.startswith('dec_blocks2') for k in ckpt):
|
| 113 |
+
for key, value in ckpt.items():
|
| 114 |
+
if key.startswith('dec_blocks'):
|
| 115 |
+
new_ckpt[key.replace('dec_blocks', 'dec_blocks2')] = value
|
| 116 |
+
return super().load_state_dict(new_ckpt, **kw)
|
| 117 |
+
|
| 118 |
+
def set_freeze(self, freeze): # this is for use by downstream models
|
| 119 |
+
assert freeze in ['none', 'mask', 'encoder'], f"unexpected freeze={freeze}"
|
| 120 |
+
to_be_frozen = {
|
| 121 |
+
'none': [],
|
| 122 |
+
'mask': [self.mask_token],
|
| 123 |
+
'encoder': [self.mask_token, self.patch_embed, self.enc_blocks],
|
| 124 |
+
'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],
|
| 125 |
+
}
|
| 126 |
+
freeze_all_params(to_be_frozen[freeze])
|
| 127 |
+
|
| 128 |
+
def _set_prediction_head(self, *args, **kwargs):
|
| 129 |
+
""" No prediction head """
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
def _encode_image(self, image, true_shape, intrinsics_embed=None):
|
| 133 |
+
# embed the image into patches (x has size B x Npatches x C)
|
| 134 |
+
x, pos = self.patch_embed(image, true_shape=true_shape)
|
| 135 |
+
|
| 136 |
+
if intrinsics_embed is not None:
|
| 137 |
+
|
| 138 |
+
if self.intrinsics_embed_type == 'linear':
|
| 139 |
+
x = x + intrinsics_embed
|
| 140 |
+
elif self.intrinsics_embed_type == 'token':
|
| 141 |
+
x = torch.cat((x, intrinsics_embed), dim=1)
|
| 142 |
+
add_pose = pos[:, 0:1, :].clone()
|
| 143 |
+
add_pose[:, :, 0] += (pos[:, -1, 0].unsqueeze(-1) + 1)
|
| 144 |
+
pos = torch.cat((pos, add_pose), dim=1)
|
| 145 |
+
|
| 146 |
+
# add positional embedding without cls token
|
| 147 |
+
assert self.enc_pos_embed is None
|
| 148 |
+
|
| 149 |
+
# now apply the transformer encoder and normalization
|
| 150 |
+
for blk in self.enc_blocks:
|
| 151 |
+
x = blk(x, pos)
|
| 152 |
+
|
| 153 |
+
x = self.enc_norm(x)
|
| 154 |
+
return x, pos, None
|
| 155 |
+
|
| 156 |
+
def _encode_image_pairs(self, img1, img2, true_shape1, true_shape2, intrinsics_embed1=None, intrinsics_embed2=None):
|
| 157 |
+
if img1.shape[-2:] == img2.shape[-2:]:
|
| 158 |
+
out, pos, _ = self._encode_image(torch.cat((img1, img2), dim=0),
|
| 159 |
+
torch.cat((true_shape1, true_shape2), dim=0),
|
| 160 |
+
torch.cat((intrinsics_embed1, intrinsics_embed2), dim=0) if intrinsics_embed1 is not None else None)
|
| 161 |
+
out, out2 = out.chunk(2, dim=0)
|
| 162 |
+
pos, pos2 = pos.chunk(2, dim=0)
|
| 163 |
+
else:
|
| 164 |
+
out, pos, _ = self._encode_image(img1, true_shape1, intrinsics_embed1)
|
| 165 |
+
out2, pos2, _ = self._encode_image(img2, true_shape2, intrinsics_embed2)
|
| 166 |
+
return out, out2, pos, pos2
|
| 167 |
+
|
| 168 |
+
def _encode_symmetrized(self, view1, view2, force_asym=False):
|
| 169 |
+
img1 = view1['img']
|
| 170 |
+
img2 = view2['img']
|
| 171 |
+
B = img1.shape[0]
|
| 172 |
+
# Recover true_shape when available, otherwise assume that the img shape is the true one
|
| 173 |
+
shape1 = view1.get('true_shape', torch.tensor(img1.shape[-2:])[None].repeat(B, 1))
|
| 174 |
+
shape2 = view2.get('true_shape', torch.tensor(img2.shape[-2:])[None].repeat(B, 1))
|
| 175 |
+
# warning! maybe the images have different portrait/landscape orientations
|
| 176 |
+
|
| 177 |
+
intrinsics_embed1 = view1.get('intrinsics_embed', None)
|
| 178 |
+
intrinsics_embed2 = view2.get('intrinsics_embed', None)
|
| 179 |
+
|
| 180 |
+
if force_asym or not is_symmetrized(view1, view2):
|
| 181 |
+
feat1, feat2, pos1, pos2 = self._encode_image_pairs(img1, img2, shape1, shape2, intrinsics_embed1, intrinsics_embed2)
|
| 182 |
+
else:
|
| 183 |
+
# computing half of forward pass!'
|
| 184 |
+
feat1, feat2, pos1, pos2 = self._encode_image_pairs(img1[::2], img2[::2], shape1[::2], shape2[::2])
|
| 185 |
+
feat1, feat2 = interleave(feat1, feat2)
|
| 186 |
+
pos1, pos2 = interleave(pos1, pos2)
|
| 187 |
+
|
| 188 |
+
return (shape1, shape2), (feat1, feat2), (pos1, pos2)
|
| 189 |
+
|
| 190 |
+
def _decoder(self, f1, pos1, f2, pos2, extra_embed1=None, extra_embed2=None):
|
| 191 |
+
final_output = [(f1, f2)] # before projection
|
| 192 |
+
|
| 193 |
+
if extra_embed1 is not None:
|
| 194 |
+
f1 = torch.cat((f1, extra_embed1), dim=-1)
|
| 195 |
+
if extra_embed2 is not None:
|
| 196 |
+
f2 = torch.cat((f2, extra_embed2), dim=-1)
|
| 197 |
+
|
| 198 |
+
# project to decoder dim
|
| 199 |
+
f1 = self.decoder_embed(f1)
|
| 200 |
+
f2 = self.decoder_embed(f2)
|
| 201 |
+
|
| 202 |
+
final_output.append((f1, f2))
|
| 203 |
+
for blk1, blk2 in zip(self.dec_blocks, self.dec_blocks2):
|
| 204 |
+
# img1 side
|
| 205 |
+
f1, _ = blk1(*final_output[-1][::+1], pos1, pos2)
|
| 206 |
+
# img2 side
|
| 207 |
+
f2, _ = blk2(*final_output[-1][::-1], pos2, pos1)
|
| 208 |
+
# store the result
|
| 209 |
+
final_output.append((f1, f2))
|
| 210 |
+
|
| 211 |
+
# normalize last output
|
| 212 |
+
del final_output[1] # duplicate with final_output[0]
|
| 213 |
+
final_output[-1] = tuple(map(self.dec_norm, final_output[-1]))
|
| 214 |
+
return zip(*final_output)
|
| 215 |
+
|
| 216 |
+
def _downstream_head(self, head_num, decout, img_shape):
|
| 217 |
+
B, S, D = decout[-1].shape
|
| 218 |
+
# img_shape = tuple(map(int, img_shape))
|
| 219 |
+
head = getattr(self, f'head{head_num}')
|
| 220 |
+
return head(decout, img_shape)
|
| 221 |
+
|
| 222 |
+
def forward(self,
|
| 223 |
+
context: dict,
|
| 224 |
+
symmetrize_batch=False,
|
| 225 |
+
return_views=False,
|
| 226 |
+
):
|
| 227 |
+
b, v, _, h, w = context["image"].shape
|
| 228 |
+
device = context["image"].device
|
| 229 |
+
|
| 230 |
+
view1, view2 = ({'img': context["image"][:, 0]},
|
| 231 |
+
{'img': context["image"][:, 1]})
|
| 232 |
+
|
| 233 |
+
# camera embedding in the encoder
|
| 234 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 235 |
+
intrinsic_emb = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree)
|
| 236 |
+
view1['img'] = torch.cat((view1['img'], intrinsic_emb[:, 0]), dim=1)
|
| 237 |
+
view2['img'] = torch.cat((view2['img'], intrinsic_emb[:, 1]), dim=1)
|
| 238 |
+
|
| 239 |
+
if self.intrinsics_embed_loc == 'encoder' and (self.intrinsics_embed_type == 'token' or self.intrinsics_embed_type == 'linear'):
|
| 240 |
+
intrinsic_embedding = self.intrinsic_encoder(context["intrinsics"].flatten(2))
|
| 241 |
+
view1['intrinsics_embed'] = intrinsic_embedding[:, 0].unsqueeze(1)
|
| 242 |
+
view2['intrinsics_embed'] = intrinsic_embedding[:, 1].unsqueeze(1)
|
| 243 |
+
|
| 244 |
+
if symmetrize_batch:
|
| 245 |
+
instance_list_view1, instance_list_view2 = [0 for _ in range(b)], [1 for _ in range(b)]
|
| 246 |
+
view1['instance'] = instance_list_view1
|
| 247 |
+
view2['instance'] = instance_list_view2
|
| 248 |
+
view1['idx'] = instance_list_view1
|
| 249 |
+
view2['idx'] = instance_list_view2
|
| 250 |
+
view1, view2 = make_batch_symmetric(view1, view2)
|
| 251 |
+
|
| 252 |
+
# encode the two images --> B,S,D
|
| 253 |
+
(shape1, shape2), (feat1, feat2), (pos1, pos2) = self._encode_symmetrized(view1, view2, force_asym=False)
|
| 254 |
+
else:
|
| 255 |
+
# encode the two images --> B,S,D
|
| 256 |
+
(shape1, shape2), (feat1, feat2), (pos1, pos2) = self._encode_symmetrized(view1, view2, force_asym=True)
|
| 257 |
+
|
| 258 |
+
if self.intrinsics_embed_loc == 'decoder':
|
| 259 |
+
# FIXME: downsample is hardcoded to 16
|
| 260 |
+
intrinsic_emb = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree, downsample=16, merge_hw=True)
|
| 261 |
+
dec1, dec2 = self._decoder(feat1, pos1, feat2, pos2, intrinsic_emb[:, 0], intrinsic_emb[:, 1])
|
| 262 |
+
else:
|
| 263 |
+
dec1, dec2 = self._decoder(feat1, pos1, feat2, pos2)
|
| 264 |
+
|
| 265 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'token':
|
| 266 |
+
dec1, dec2 = list(dec1), list(dec2)
|
| 267 |
+
for i in range(len(dec1)):
|
| 268 |
+
dec1[i] = dec1[i][:, :-1]
|
| 269 |
+
dec2[i] = dec2[i][:, :-1]
|
| 270 |
+
|
| 271 |
+
if return_views:
|
| 272 |
+
return dec1, dec2, shape1, shape2, view1, view2
|
| 273 |
+
return dec1, dec2, shape1, shape2
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def patch_size(self) -> int:
|
| 277 |
+
return 16
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def d_out(self) -> int:
|
| 281 |
+
return 1024
|
src/model/encoder/backbone/backbone_croco_multiview.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from .croco.blocks import DecoderBlock
|
| 10 |
+
from .croco.croco import CroCoNet
|
| 11 |
+
from .croco.misc import fill_default_args, freeze_all_params, transpose_to_landscape, is_symmetrized, interleave, \
|
| 12 |
+
make_batch_symmetric
|
| 13 |
+
from .croco.patch_embed import get_patch_embed
|
| 14 |
+
from .backbone import Backbone
|
| 15 |
+
from src.geometry.camera_emb import get_intrinsic_embedding
|
| 16 |
+
|
| 17 |
+
inf = float('inf')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
croco_params = {
|
| 21 |
+
'ViTLarge_BaseDecoder': {
|
| 22 |
+
'enc_depth': 24,
|
| 23 |
+
'dec_depth': 12,
|
| 24 |
+
'enc_embed_dim': 1024,
|
| 25 |
+
'dec_embed_dim': 768,
|
| 26 |
+
'enc_num_heads': 16,
|
| 27 |
+
'dec_num_heads': 12,
|
| 28 |
+
'pos_embed': 'RoPE100',
|
| 29 |
+
'img_size': (512, 512),
|
| 30 |
+
},
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
default_dust3r_params = {
|
| 34 |
+
'enc_depth': 24,
|
| 35 |
+
'dec_depth': 12,
|
| 36 |
+
'enc_embed_dim': 1024,
|
| 37 |
+
'dec_embed_dim': 768,
|
| 38 |
+
'enc_num_heads': 16,
|
| 39 |
+
'dec_num_heads': 12,
|
| 40 |
+
'pos_embed': 'RoPE100',
|
| 41 |
+
'patch_embed_cls': 'PatchEmbedDust3R',
|
| 42 |
+
'img_size': (512, 512),
|
| 43 |
+
'head_type': 'dpt',
|
| 44 |
+
'output_mode': 'pts3d',
|
| 45 |
+
'depth_mode': ('exp', -inf, inf),
|
| 46 |
+
'conf_mode': ('exp', 1, inf)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class BackboneCrocoCfg:
|
| 52 |
+
name: Literal["croco"]
|
| 53 |
+
model: Literal["ViTLarge_BaseDecoder", "ViTBase_SmallDecoder", "ViTBase_BaseDecoder"] # keep interface for the last two models, but they are not supported
|
| 54 |
+
patch_embed_cls: str = 'PatchEmbedDust3R' # PatchEmbedDust3R or ManyAR_PatchEmbed
|
| 55 |
+
asymmetry_decoder: bool = True
|
| 56 |
+
intrinsics_embed_loc: Literal["encoder", "decoder", "none"] = 'none'
|
| 57 |
+
intrinsics_embed_degree: int = 0
|
| 58 |
+
intrinsics_embed_type: Literal["pixelwise", "linear", "token"] = 'token' # linear or dpt
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AsymmetricCroCoMulti(CroCoNet):
|
| 62 |
+
""" Two siamese encoders, followed by two decoders.
|
| 63 |
+
The goal is to output 3d points directly, both images in view1's frame
|
| 64 |
+
(hence the asymmetry).
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, cfg: BackboneCrocoCfg, d_in: int) -> None:
|
| 68 |
+
|
| 69 |
+
self.intrinsics_embed_loc = cfg.intrinsics_embed_loc
|
| 70 |
+
self.intrinsics_embed_degree = cfg.intrinsics_embed_degree
|
| 71 |
+
self.intrinsics_embed_type = cfg.intrinsics_embed_type
|
| 72 |
+
self.intrinsics_embed_encoder_dim = 0
|
| 73 |
+
self.intrinsics_embed_decoder_dim = 0
|
| 74 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 75 |
+
self.intrinsics_embed_encoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3
|
| 76 |
+
elif self.intrinsics_embed_loc == 'decoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 77 |
+
self.intrinsics_embed_decoder_dim = (self.intrinsics_embed_degree + 1) ** 2 if self.intrinsics_embed_degree > 0 else 3
|
| 78 |
+
|
| 79 |
+
self.patch_embed_cls = cfg.patch_embed_cls
|
| 80 |
+
self.croco_args = fill_default_args(croco_params[cfg.model], CroCoNet.__init__)
|
| 81 |
+
|
| 82 |
+
super().__init__(**croco_params[cfg.model])
|
| 83 |
+
|
| 84 |
+
if cfg.asymmetry_decoder:
|
| 85 |
+
self.dec_blocks2 = deepcopy(self.dec_blocks) # This is used in DUSt3R and MASt3R
|
| 86 |
+
|
| 87 |
+
if self.intrinsics_embed_type == 'linear' or self.intrinsics_embed_type == 'token':
|
| 88 |
+
self.intrinsic_encoder = nn.Linear(9, 1024)
|
| 89 |
+
|
| 90 |
+
# self.set_downstream_head(output_mode, head_type, landscape_only, depth_mode, conf_mode, **croco_kwargs)
|
| 91 |
+
# self.set_freeze(freeze)
|
| 92 |
+
|
| 93 |
+
def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768, in_chans=3):
|
| 94 |
+
in_chans = in_chans + self.intrinsics_embed_encoder_dim
|
| 95 |
+
self.patch_embed = get_patch_embed(self.patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans)
|
| 96 |
+
|
| 97 |
+
def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec):
|
| 98 |
+
self.dec_depth = dec_depth
|
| 99 |
+
self.dec_embed_dim = dec_embed_dim
|
| 100 |
+
# transfer from encoder to decoder
|
| 101 |
+
enc_embed_dim = enc_embed_dim + self.intrinsics_embed_decoder_dim
|
| 102 |
+
self.decoder_embed = nn.Linear(enc_embed_dim, dec_embed_dim, bias=True)
|
| 103 |
+
# transformer for the decoder
|
| 104 |
+
self.dec_blocks = nn.ModuleList([
|
| 105 |
+
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)
|
| 106 |
+
for i in range(dec_depth)])
|
| 107 |
+
# final norm layer
|
| 108 |
+
self.dec_norm = norm_layer(dec_embed_dim)
|
| 109 |
+
|
| 110 |
+
def load_state_dict(self, ckpt, **kw):
|
| 111 |
+
# duplicate all weights for the second decoder if not present
|
| 112 |
+
new_ckpt = dict(ckpt)
|
| 113 |
+
if not any(k.startswith('dec_blocks2') for k in ckpt):
|
| 114 |
+
for key, value in ckpt.items():
|
| 115 |
+
if key.startswith('dec_blocks'):
|
| 116 |
+
new_ckpt[key.replace('dec_blocks', 'dec_blocks2')] = value
|
| 117 |
+
return super().load_state_dict(new_ckpt, **kw)
|
| 118 |
+
|
| 119 |
+
def set_freeze(self, freeze): # this is for use by downstream models
|
| 120 |
+
assert freeze in ['none', 'mask', 'encoder'], f"unexpected freeze={freeze}"
|
| 121 |
+
to_be_frozen = {
|
| 122 |
+
'none': [],
|
| 123 |
+
'mask': [self.mask_token],
|
| 124 |
+
'encoder': [self.mask_token, self.patch_embed, self.enc_blocks],
|
| 125 |
+
'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],
|
| 126 |
+
}
|
| 127 |
+
freeze_all_params(to_be_frozen[freeze])
|
| 128 |
+
|
| 129 |
+
def _set_prediction_head(self, *args, **kwargs):
|
| 130 |
+
""" No prediction head """
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
def _encode_image(self, image, true_shape, intrinsics_embed=None):
|
| 134 |
+
# embed the image into patches (x has size B x Npatches x C)
|
| 135 |
+
x, pos = self.patch_embed(image, true_shape=true_shape)
|
| 136 |
+
|
| 137 |
+
if intrinsics_embed is not None:
|
| 138 |
+
|
| 139 |
+
if self.intrinsics_embed_type == 'linear':
|
| 140 |
+
x = x + intrinsics_embed
|
| 141 |
+
elif self.intrinsics_embed_type == 'token':
|
| 142 |
+
x = torch.cat((x, intrinsics_embed), dim=1)
|
| 143 |
+
add_pose = pos[:, 0:1, :].clone()
|
| 144 |
+
add_pose[:, :, 0] += (pos[:, -1, 0].unsqueeze(-1) + 1)
|
| 145 |
+
pos = torch.cat((pos, add_pose), dim=1)
|
| 146 |
+
|
| 147 |
+
# add positional embedding without cls token
|
| 148 |
+
assert self.enc_pos_embed is None
|
| 149 |
+
|
| 150 |
+
# now apply the transformer encoder and normalization
|
| 151 |
+
for blk in self.enc_blocks:
|
| 152 |
+
x = blk(x, pos)
|
| 153 |
+
|
| 154 |
+
x = self.enc_norm(x)
|
| 155 |
+
return x, pos, None
|
| 156 |
+
|
| 157 |
+
def _decoder(self, feat, pose, extra_embed=None):
|
| 158 |
+
b, v, l, c = feat.shape
|
| 159 |
+
final_output = [feat] # before projection
|
| 160 |
+
if extra_embed is not None:
|
| 161 |
+
feat = torch.cat((feat, extra_embed), dim=-1)
|
| 162 |
+
|
| 163 |
+
# project to decoder dim
|
| 164 |
+
f = rearrange(feat, "b v l c -> (b v) l c")
|
| 165 |
+
f = self.decoder_embed(f)
|
| 166 |
+
f = rearrange(f, "(b v) l c -> b v l c", b=b, v=v)
|
| 167 |
+
final_output.append(f)
|
| 168 |
+
|
| 169 |
+
def generate_ctx_views(x):
|
| 170 |
+
b, v, l, c = x.shape
|
| 171 |
+
ctx_views = x.unsqueeze(1).expand(b, v, v, l, c)
|
| 172 |
+
mask = torch.arange(v).unsqueeze(0) != torch.arange(v).unsqueeze(1)
|
| 173 |
+
ctx_views = ctx_views[:, mask].reshape(b, v, v - 1, l, c) # B, V, V-1, L, C
|
| 174 |
+
ctx_views = ctx_views.flatten(2, 3) # B, V, (V-1)*L, C
|
| 175 |
+
return ctx_views.contiguous()
|
| 176 |
+
|
| 177 |
+
pos_ctx = generate_ctx_views(pose)
|
| 178 |
+
for blk1, blk2 in zip(self.dec_blocks, self.dec_blocks2):
|
| 179 |
+
feat_current = final_output[-1]
|
| 180 |
+
feat_current_ctx = generate_ctx_views(feat_current)
|
| 181 |
+
# img1 side
|
| 182 |
+
f1, _ = blk1(feat_current[:, 0].contiguous(), feat_current_ctx[:, 0].contiguous(), pose[:, 0].contiguous(), pos_ctx[:, 0].contiguous())
|
| 183 |
+
f1 = f1.unsqueeze(1)
|
| 184 |
+
# img2 side
|
| 185 |
+
f2, _ = blk2(rearrange(feat_current[:, 1:], "b v l c -> (b v) l c"),
|
| 186 |
+
rearrange(feat_current_ctx[:, 1:], "b v l c -> (b v) l c"),
|
| 187 |
+
rearrange(pose[:, 1:], "b v l c -> (b v) l c"),
|
| 188 |
+
rearrange(pos_ctx[:, 1:], "b v l c -> (b v) l c"))
|
| 189 |
+
f2 = rearrange(f2, "(b v) l c -> b v l c", b=b, v=v-1)
|
| 190 |
+
# store the result
|
| 191 |
+
final_output.append(torch.cat((f1, f2), dim=1))
|
| 192 |
+
|
| 193 |
+
# normalize last output
|
| 194 |
+
del final_output[1] # duplicate with final_output[0]
|
| 195 |
+
last_feat = rearrange(final_output[-1], "b v l c -> (b v) l c")
|
| 196 |
+
last_feat = self.dec_norm(last_feat)
|
| 197 |
+
final_output[-1] = rearrange(last_feat, "(b v) l c -> b v l c", b=b, v=v)
|
| 198 |
+
return final_output
|
| 199 |
+
|
| 200 |
+
def forward(self,
|
| 201 |
+
context: dict,
|
| 202 |
+
symmetrize_batch=False,
|
| 203 |
+
return_views=False,
|
| 204 |
+
):
|
| 205 |
+
b, v, _, h, w = context["image"].shape
|
| 206 |
+
images_all = context["image"]
|
| 207 |
+
|
| 208 |
+
# camera embedding in the encoder
|
| 209 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'pixelwise':
|
| 210 |
+
intrinsic_embedding = get_intrinsic_embedding(context, degree=self.intrinsics_embed_degree)
|
| 211 |
+
images_all = torch.cat((images_all, intrinsic_embedding), dim=2)
|
| 212 |
+
|
| 213 |
+
intrinsic_embedding_all = None
|
| 214 |
+
if self.intrinsics_embed_loc == 'encoder' and (self.intrinsics_embed_type == 'token' or self.intrinsics_embed_type == 'linear'):
|
| 215 |
+
intrinsic_embedding = self.intrinsic_encoder(context["intrinsics"].flatten(2))
|
| 216 |
+
intrinsic_embedding_all = rearrange(intrinsic_embedding, "b v c -> (b v) c").unsqueeze(1)
|
| 217 |
+
|
| 218 |
+
# step 1: encoder input images
|
| 219 |
+
images_all = rearrange(images_all, "b v c h w -> (b v) c h w")
|
| 220 |
+
shape_all = torch.tensor(images_all.shape[-2:])[None].repeat(b*v, 1)
|
| 221 |
+
|
| 222 |
+
feat, pose, _ = self._encode_image(images_all, shape_all, intrinsic_embedding_all)
|
| 223 |
+
|
| 224 |
+
feat = rearrange(feat, "(b v) l c -> b v l c", b=b, v=v)
|
| 225 |
+
pose = rearrange(pose, "(b v) l c -> b v l c", b=b, v=v)
|
| 226 |
+
|
| 227 |
+
# step 2: decoder
|
| 228 |
+
dec_feat = self._decoder(feat, pose)
|
| 229 |
+
shape = rearrange(shape_all, "(b v) c -> b v c", b=b, v=v)
|
| 230 |
+
images = rearrange(images_all, "(b v) c h w -> b v c h w", b=b, v=v)
|
| 231 |
+
|
| 232 |
+
if self.intrinsics_embed_loc == 'encoder' and self.intrinsics_embed_type == 'token':
|
| 233 |
+
dec_feat = list(dec_feat)
|
| 234 |
+
for i in range(len(dec_feat)):
|
| 235 |
+
dec_feat[i] = dec_feat[i][:, :, :-1]
|
| 236 |
+
|
| 237 |
+
return dec_feat, shape, images
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
def patch_size(self) -> int:
|
| 241 |
+
return 16
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
def d_out(self) -> int:
|
| 245 |
+
return 1024
|
src/model/encoder/backbone/backbone_dino.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from einops import rearrange, repeat
|
| 6 |
+
from jaxtyping import Float
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
from src.dataset.types import BatchedViews
|
| 10 |
+
from .backbone import Backbone
|
| 11 |
+
from .backbone_resnet import BackboneResnet, BackboneResnetCfg
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class BackboneDinoCfg:
|
| 16 |
+
name: Literal["dino"]
|
| 17 |
+
model: Literal["dino_vits16", "dino_vits8", "dino_vitb16", "dino_vitb8"]
|
| 18 |
+
d_out: int
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class BackboneDino(Backbone[BackboneDinoCfg]):
|
| 22 |
+
def __init__(self, cfg: BackboneDinoCfg, d_in: int) -> None:
|
| 23 |
+
super().__init__(cfg)
|
| 24 |
+
assert d_in == 3
|
| 25 |
+
self.dino = torch.hub.load("facebookresearch/dino:main", cfg.model)
|
| 26 |
+
self.resnet_backbone = BackboneResnet(
|
| 27 |
+
BackboneResnetCfg("resnet", "dino_resnet50", 4, False, cfg.d_out),
|
| 28 |
+
d_in,
|
| 29 |
+
)
|
| 30 |
+
self.global_token_mlp = nn.Sequential(
|
| 31 |
+
nn.Linear(768, 768),
|
| 32 |
+
nn.ReLU(),
|
| 33 |
+
nn.Linear(768, cfg.d_out),
|
| 34 |
+
)
|
| 35 |
+
self.local_token_mlp = nn.Sequential(
|
| 36 |
+
nn.Linear(768, 768),
|
| 37 |
+
nn.ReLU(),
|
| 38 |
+
nn.Linear(768, cfg.d_out),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def forward(
|
| 42 |
+
self,
|
| 43 |
+
context: BatchedViews,
|
| 44 |
+
) -> Float[Tensor, "batch view d_out height width"]:
|
| 45 |
+
# Compute features from the DINO-pretrained resnet50.
|
| 46 |
+
resnet_features = self.resnet_backbone(context)
|
| 47 |
+
|
| 48 |
+
# Compute features from the DINO-pretrained ViT.
|
| 49 |
+
b, v, _, h, w = context["image"].shape
|
| 50 |
+
assert h % self.patch_size == 0 and w % self.patch_size == 0
|
| 51 |
+
tokens = rearrange(context["image"], "b v c h w -> (b v) c h w")
|
| 52 |
+
tokens = self.dino.get_intermediate_layers(tokens)[0]
|
| 53 |
+
global_token = self.global_token_mlp(tokens[:, 0])
|
| 54 |
+
local_tokens = self.local_token_mlp(tokens[:, 1:])
|
| 55 |
+
|
| 56 |
+
# Repeat the global token to match the image shape.
|
| 57 |
+
global_token = repeat(global_token, "(b v) c -> b v c h w", b=b, v=v, h=h, w=w)
|
| 58 |
+
|
| 59 |
+
# Repeat the local tokens to match the image shape.
|
| 60 |
+
local_tokens = repeat(
|
| 61 |
+
local_tokens,
|
| 62 |
+
"(b v) (h w) c -> b v c (h hps) (w wps)",
|
| 63 |
+
b=b,
|
| 64 |
+
v=v,
|
| 65 |
+
h=h // self.patch_size,
|
| 66 |
+
hps=self.patch_size,
|
| 67 |
+
w=w // self.patch_size,
|
| 68 |
+
wps=self.patch_size,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
return resnet_features + local_tokens + global_token
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def patch_size(self) -> int:
|
| 75 |
+
return int("".join(filter(str.isdigit, self.cfg.model)))
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def d_out(self) -> int:
|
| 79 |
+
return self.cfg.d_out
|
src/model/encoder/backbone/backbone_resnet.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import torchvision
|
| 8 |
+
from einops import rearrange
|
| 9 |
+
from jaxtyping import Float
|
| 10 |
+
from torch import Tensor, nn
|
| 11 |
+
from torchvision.models import ResNet
|
| 12 |
+
|
| 13 |
+
from src.dataset.types import BatchedViews
|
| 14 |
+
from .backbone import Backbone
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class BackboneResnetCfg:
|
| 19 |
+
name: Literal["resnet"]
|
| 20 |
+
model: Literal[
|
| 21 |
+
"resnet18", "resnet34", "resnet50", "resnet101", "resnet152", "dino_resnet50"
|
| 22 |
+
]
|
| 23 |
+
num_layers: int
|
| 24 |
+
use_first_pool: bool
|
| 25 |
+
d_out: int
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class BackboneResnet(Backbone[BackboneResnetCfg]):
|
| 29 |
+
model: ResNet
|
| 30 |
+
|
| 31 |
+
def __init__(self, cfg: BackboneResnetCfg, d_in: int) -> None:
|
| 32 |
+
super().__init__(cfg)
|
| 33 |
+
|
| 34 |
+
assert d_in == 3
|
| 35 |
+
|
| 36 |
+
norm_layer = functools.partial(
|
| 37 |
+
nn.InstanceNorm2d,
|
| 38 |
+
affine=False,
|
| 39 |
+
track_running_stats=False,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if cfg.model == "dino_resnet50":
|
| 43 |
+
self.model = torch.hub.load("facebookresearch/dino:main", "dino_resnet50")
|
| 44 |
+
else:
|
| 45 |
+
self.model = getattr(torchvision.models, cfg.model)(norm_layer=norm_layer)
|
| 46 |
+
|
| 47 |
+
# Set up projections
|
| 48 |
+
self.projections = nn.ModuleDict({})
|
| 49 |
+
for index in range(1, cfg.num_layers):
|
| 50 |
+
key = f"layer{index}"
|
| 51 |
+
block = getattr(self.model, key)
|
| 52 |
+
conv_index = 1
|
| 53 |
+
try:
|
| 54 |
+
while True:
|
| 55 |
+
d_layer_out = getattr(block[-1], f"conv{conv_index}").out_channels
|
| 56 |
+
conv_index += 1
|
| 57 |
+
except AttributeError:
|
| 58 |
+
pass
|
| 59 |
+
self.projections[key] = nn.Conv2d(d_layer_out, cfg.d_out, 1)
|
| 60 |
+
|
| 61 |
+
# Add a projection for the first layer.
|
| 62 |
+
self.projections["layer0"] = nn.Conv2d(
|
| 63 |
+
self.model.conv1.out_channels, cfg.d_out, 1
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def forward(
|
| 67 |
+
self,
|
| 68 |
+
context: BatchedViews,
|
| 69 |
+
) -> Float[Tensor, "batch view d_out height width"]:
|
| 70 |
+
# Merge the batch dimensions.
|
| 71 |
+
b, v, _, h, w = context["image"].shape
|
| 72 |
+
x = rearrange(context["image"], "b v c h w -> (b v) c h w")
|
| 73 |
+
|
| 74 |
+
# Run the images through the resnet.
|
| 75 |
+
x = self.model.conv1(x)
|
| 76 |
+
x = self.model.bn1(x)
|
| 77 |
+
x = self.model.relu(x)
|
| 78 |
+
features = [self.projections["layer0"](x)]
|
| 79 |
+
|
| 80 |
+
# Propagate the input through the resnet's layers.
|
| 81 |
+
for index in range(1, self.cfg.num_layers):
|
| 82 |
+
key = f"layer{index}"
|
| 83 |
+
if index == 0 and self.cfg.use_first_pool:
|
| 84 |
+
x = self.model.maxpool(x)
|
| 85 |
+
x = getattr(self.model, key)(x)
|
| 86 |
+
features.append(self.projections[key](x))
|
| 87 |
+
|
| 88 |
+
# Upscale the features.
|
| 89 |
+
features = [
|
| 90 |
+
F.interpolate(f, (h, w), mode="bilinear", align_corners=True)
|
| 91 |
+
for f in features
|
| 92 |
+
]
|
| 93 |
+
features = torch.stack(features).sum(dim=0)
|
| 94 |
+
|
| 95 |
+
# Separate batch dimensions.
|
| 96 |
+
return rearrange(features, "(b v) c h w -> b v c h w", b=b, v=v)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def d_out(self) -> int:
|
| 100 |
+
return self.cfg.d_out
|
src/model/encoder/backbone/croco/README.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Most of the code under src/model/encoder/backbone/croco/ is from the original CROCO implementation.
|
| 2 |
+
The code is not modified in any way except the relative module path.
|
| 3 |
+
The original code can be found at [croco Github Repo](https://github.com/naver/croco/tree/743ee71a2a9bf57cea6832a9064a70a0597fcfcb/models).
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
Except:
|
| 7 |
+
- 'misc.py', 'patch_embed.py' is from DUSt3R.
|
src/model/encoder/backbone/croco/__init__.py
ADDED
|
File without changes
|
src/model/encoder/backbone/croco/blocks.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
# Main encoder/decoder blocks
|
| 7 |
+
# --------------------------------------------------------
|
| 8 |
+
# References:
|
| 9 |
+
# timm
|
| 10 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
|
| 11 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/helpers.py
|
| 12 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
|
| 13 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/mlp.py
|
| 14 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/patch_embed.py
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
|
| 20 |
+
from itertools import repeat
|
| 21 |
+
import collections.abc
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _ntuple(n):
|
| 25 |
+
def parse(x):
|
| 26 |
+
if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
|
| 27 |
+
return x
|
| 28 |
+
return tuple(repeat(x, n))
|
| 29 |
+
return parse
|
| 30 |
+
to_2tuple = _ntuple(2)
|
| 31 |
+
|
| 32 |
+
def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
|
| 33 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 34 |
+
"""
|
| 35 |
+
if drop_prob == 0. or not training:
|
| 36 |
+
return x
|
| 37 |
+
keep_prob = 1 - drop_prob
|
| 38 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 39 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 40 |
+
if keep_prob > 0.0 and scale_by_keep:
|
| 41 |
+
random_tensor.div_(keep_prob)
|
| 42 |
+
return x * random_tensor
|
| 43 |
+
|
| 44 |
+
class DropPath(nn.Module):
|
| 45 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 46 |
+
"""
|
| 47 |
+
def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
|
| 48 |
+
super(DropPath, self).__init__()
|
| 49 |
+
self.drop_prob = drop_prob
|
| 50 |
+
self.scale_by_keep = scale_by_keep
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
|
| 54 |
+
|
| 55 |
+
def extra_repr(self):
|
| 56 |
+
return f'drop_prob={round(self.drop_prob,3):0.3f}'
|
| 57 |
+
|
| 58 |
+
class Mlp(nn.Module):
|
| 59 |
+
""" MLP as used in Vision Transformer, MLP-Mixer and related networks"""
|
| 60 |
+
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, drop=0.):
|
| 61 |
+
super().__init__()
|
| 62 |
+
out_features = out_features or in_features
|
| 63 |
+
hidden_features = hidden_features or in_features
|
| 64 |
+
bias = to_2tuple(bias)
|
| 65 |
+
drop_probs = to_2tuple(drop)
|
| 66 |
+
|
| 67 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0])
|
| 68 |
+
self.act = act_layer()
|
| 69 |
+
self.drop1 = nn.Dropout(drop_probs[0])
|
| 70 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1])
|
| 71 |
+
self.drop2 = nn.Dropout(drop_probs[1])
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
x = self.fc1(x)
|
| 75 |
+
x = self.act(x)
|
| 76 |
+
x = self.drop1(x)
|
| 77 |
+
x = self.fc2(x)
|
| 78 |
+
x = self.drop2(x)
|
| 79 |
+
return x
|
| 80 |
+
|
| 81 |
+
class Attention(nn.Module):
|
| 82 |
+
|
| 83 |
+
def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.num_heads = num_heads
|
| 86 |
+
head_dim = dim // num_heads
|
| 87 |
+
self.scale = head_dim ** -0.5
|
| 88 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 89 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 90 |
+
self.proj = nn.Linear(dim, dim)
|
| 91 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 92 |
+
self.rope = rope
|
| 93 |
+
|
| 94 |
+
def forward(self, x, xpos):
|
| 95 |
+
B, N, C = x.shape
|
| 96 |
+
|
| 97 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).transpose(1,3)
|
| 98 |
+
q, k, v = [qkv[:,:,i] for i in range(3)]
|
| 99 |
+
# q,k,v = qkv.unbind(2) # make torchscript happy (cannot use tensor as tuple)
|
| 100 |
+
|
| 101 |
+
if self.rope is not None:
|
| 102 |
+
q = self.rope(q, xpos)
|
| 103 |
+
k = self.rope(k, xpos)
|
| 104 |
+
|
| 105 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 106 |
+
attn = attn.softmax(dim=-1)
|
| 107 |
+
attn = self.attn_drop(attn)
|
| 108 |
+
|
| 109 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 110 |
+
x = self.proj(x)
|
| 111 |
+
x = self.proj_drop(x)
|
| 112 |
+
return x
|
| 113 |
+
|
| 114 |
+
class Block(nn.Module):
|
| 115 |
+
|
| 116 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
|
| 117 |
+
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, rope=None):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.norm1 = norm_layer(dim)
|
| 120 |
+
self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
|
| 121 |
+
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
|
| 122 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 123 |
+
self.norm2 = norm_layer(dim)
|
| 124 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 125 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 126 |
+
|
| 127 |
+
def forward(self, x, xpos):
|
| 128 |
+
x = x + self.drop_path(self.attn(self.norm1(x), xpos))
|
| 129 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 130 |
+
return x
|
| 131 |
+
|
| 132 |
+
class CrossAttention(nn.Module):
|
| 133 |
+
|
| 134 |
+
def __init__(self, dim, rope=None, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.num_heads = num_heads
|
| 137 |
+
head_dim = dim // num_heads
|
| 138 |
+
self.scale = head_dim ** -0.5
|
| 139 |
+
|
| 140 |
+
self.projq = nn.Linear(dim, dim, bias=qkv_bias)
|
| 141 |
+
self.projk = nn.Linear(dim, dim, bias=qkv_bias)
|
| 142 |
+
self.projv = nn.Linear(dim, dim, bias=qkv_bias)
|
| 143 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 144 |
+
self.proj = nn.Linear(dim, dim)
|
| 145 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 146 |
+
|
| 147 |
+
self.rope = rope
|
| 148 |
+
|
| 149 |
+
def forward(self, query, key, value, qpos, kpos):
|
| 150 |
+
B, Nq, C = query.shape
|
| 151 |
+
Nk = key.shape[1]
|
| 152 |
+
Nv = value.shape[1]
|
| 153 |
+
|
| 154 |
+
q = self.projq(query).reshape(B,Nq,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3)
|
| 155 |
+
k = self.projk(key).reshape(B,Nk,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3)
|
| 156 |
+
v = self.projv(value).reshape(B,Nv,self.num_heads, C// self.num_heads).permute(0, 2, 1, 3)
|
| 157 |
+
|
| 158 |
+
if self.rope is not None:
|
| 159 |
+
q = self.rope(q, qpos)
|
| 160 |
+
k = self.rope(k, kpos)
|
| 161 |
+
|
| 162 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 163 |
+
attn = attn.softmax(dim=-1)
|
| 164 |
+
attn = self.attn_drop(attn)
|
| 165 |
+
|
| 166 |
+
x = (attn @ v).transpose(1, 2).reshape(B, Nq, C)
|
| 167 |
+
x = self.proj(x)
|
| 168 |
+
x = self.proj_drop(x)
|
| 169 |
+
return x
|
| 170 |
+
|
| 171 |
+
class DecoderBlock(nn.Module):
|
| 172 |
+
|
| 173 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
|
| 174 |
+
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, norm_mem=True, rope=None):
|
| 175 |
+
super().__init__()
|
| 176 |
+
self.norm1 = norm_layer(dim)
|
| 177 |
+
self.attn = Attention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
|
| 178 |
+
self.cross_attn = CrossAttention(dim, rope=rope, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
|
| 179 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 180 |
+
self.norm2 = norm_layer(dim)
|
| 181 |
+
self.norm3 = norm_layer(dim)
|
| 182 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 183 |
+
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
| 184 |
+
self.norm_y = norm_layer(dim) if norm_mem else nn.Identity()
|
| 185 |
+
|
| 186 |
+
def forward(self, x, y, xpos, ypos):
|
| 187 |
+
x = x + self.drop_path(self.attn(self.norm1(x), xpos))
|
| 188 |
+
y_ = self.norm_y(y)
|
| 189 |
+
x = x + self.drop_path(self.cross_attn(self.norm2(x), y_, y_, xpos, ypos))
|
| 190 |
+
x = x + self.drop_path(self.mlp(self.norm3(x)))
|
| 191 |
+
return x, y
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# patch embedding
|
| 195 |
+
class PositionGetter(object):
|
| 196 |
+
""" return positions of patches """
|
| 197 |
+
|
| 198 |
+
def __init__(self):
|
| 199 |
+
self.cache_positions = {}
|
| 200 |
+
|
| 201 |
+
def __call__(self, b, h, w, device):
|
| 202 |
+
if not (h,w) in self.cache_positions:
|
| 203 |
+
x = torch.arange(w, device=device)
|
| 204 |
+
y = torch.arange(h, device=device)
|
| 205 |
+
self.cache_positions[h,w] = torch.cartesian_prod(y, x) # (h, w, 2)
|
| 206 |
+
pos = self.cache_positions[h,w].view(1, h*w, 2).expand(b, -1, 2).clone()
|
| 207 |
+
return pos
|
| 208 |
+
|
| 209 |
+
class PatchEmbed(nn.Module):
|
| 210 |
+
""" just adding _init_weights + position getter compared to timm.models.layers.patch_embed.PatchEmbed"""
|
| 211 |
+
|
| 212 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
|
| 213 |
+
super().__init__()
|
| 214 |
+
img_size = to_2tuple(img_size)
|
| 215 |
+
patch_size = to_2tuple(patch_size)
|
| 216 |
+
self.img_size = img_size
|
| 217 |
+
self.patch_size = patch_size
|
| 218 |
+
self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
|
| 219 |
+
self.num_patches = self.grid_size[0] * self.grid_size[1]
|
| 220 |
+
self.flatten = flatten
|
| 221 |
+
|
| 222 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
| 223 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
| 224 |
+
|
| 225 |
+
self.position_getter = PositionGetter()
|
| 226 |
+
|
| 227 |
+
def forward(self, x):
|
| 228 |
+
B, C, H, W = x.shape
|
| 229 |
+
torch._assert(H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]}).")
|
| 230 |
+
torch._assert(W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]}).")
|
| 231 |
+
x = self.proj(x)
|
| 232 |
+
pos = self.position_getter(B, x.size(2), x.size(3), x.device)
|
| 233 |
+
if self.flatten:
|
| 234 |
+
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
|
| 235 |
+
x = self.norm(x)
|
| 236 |
+
return x, pos
|
| 237 |
+
|
| 238 |
+
def _init_weights(self):
|
| 239 |
+
w = self.proj.weight.data
|
| 240 |
+
torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
|
| 241 |
+
|
src/model/encoder/backbone/croco/croco.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
# CroCo model during pretraining
|
| 7 |
+
# --------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
torch.backends.cuda.matmul.allow_tf32 = True # for gpu >= Ampere and pytorch >= 1.12
|
| 14 |
+
from functools import partial
|
| 15 |
+
|
| 16 |
+
from .blocks import Block, DecoderBlock, PatchEmbed
|
| 17 |
+
from .pos_embed import get_2d_sincos_pos_embed, RoPE2D
|
| 18 |
+
from .masking import RandomMask
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CroCoNet(nn.Module):
|
| 22 |
+
|
| 23 |
+
def __init__(self,
|
| 24 |
+
img_size=224, # input image size
|
| 25 |
+
patch_size=16, # patch_size
|
| 26 |
+
mask_ratio=0.9, # ratios of masked tokens
|
| 27 |
+
enc_embed_dim=768, # encoder feature dimension
|
| 28 |
+
enc_depth=12, # encoder depth
|
| 29 |
+
enc_num_heads=12, # encoder number of heads in the transformer block
|
| 30 |
+
dec_embed_dim=512, # decoder feature dimension
|
| 31 |
+
dec_depth=8, # decoder depth
|
| 32 |
+
dec_num_heads=16, # decoder number of heads in the transformer block
|
| 33 |
+
mlp_ratio=4,
|
| 34 |
+
norm_layer=partial(nn.LayerNorm, eps=1e-6),
|
| 35 |
+
norm_im2_in_dec=True, # whether to apply normalization of the 'memory' = (second image) in the decoder
|
| 36 |
+
pos_embed='cosine', # positional embedding (either cosine or RoPE100)
|
| 37 |
+
):
|
| 38 |
+
|
| 39 |
+
super(CroCoNet, self).__init__()
|
| 40 |
+
|
| 41 |
+
# patch embeddings (with initialization done as in MAE)
|
| 42 |
+
self._set_patch_embed(img_size, patch_size, enc_embed_dim)
|
| 43 |
+
|
| 44 |
+
# mask generations
|
| 45 |
+
self._set_mask_generator(self.patch_embed.num_patches, mask_ratio)
|
| 46 |
+
|
| 47 |
+
self.pos_embed = pos_embed
|
| 48 |
+
if pos_embed=='cosine':
|
| 49 |
+
# positional embedding of the encoder
|
| 50 |
+
enc_pos_embed = get_2d_sincos_pos_embed(enc_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0)
|
| 51 |
+
self.register_buffer('enc_pos_embed', torch.from_numpy(enc_pos_embed).float())
|
| 52 |
+
# positional embedding of the decoder
|
| 53 |
+
dec_pos_embed = get_2d_sincos_pos_embed(dec_embed_dim, int(self.patch_embed.num_patches**.5), n_cls_token=0)
|
| 54 |
+
self.register_buffer('dec_pos_embed', torch.from_numpy(dec_pos_embed).float())
|
| 55 |
+
# pos embedding in each block
|
| 56 |
+
self.rope = None # nothing for cosine
|
| 57 |
+
elif pos_embed.startswith('RoPE'): # eg RoPE100
|
| 58 |
+
self.enc_pos_embed = None # nothing to add in the encoder with RoPE
|
| 59 |
+
self.dec_pos_embed = None # nothing to add in the decoder with RoPE
|
| 60 |
+
if RoPE2D is None: raise ImportError("Cannot find cuRoPE2D, please install it following the README instructions")
|
| 61 |
+
freq = float(pos_embed[len('RoPE'):])
|
| 62 |
+
self.rope = RoPE2D(freq=freq)
|
| 63 |
+
else:
|
| 64 |
+
raise NotImplementedError('Unknown pos_embed '+pos_embed)
|
| 65 |
+
|
| 66 |
+
# transformer for the encoder
|
| 67 |
+
self.enc_depth = enc_depth
|
| 68 |
+
self.enc_embed_dim = enc_embed_dim
|
| 69 |
+
self.enc_blocks = nn.ModuleList([
|
| 70 |
+
Block(enc_embed_dim, enc_num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer, rope=self.rope)
|
| 71 |
+
for i in range(enc_depth)])
|
| 72 |
+
self.enc_norm = norm_layer(enc_embed_dim)
|
| 73 |
+
|
| 74 |
+
# masked tokens
|
| 75 |
+
self._set_mask_token(dec_embed_dim)
|
| 76 |
+
|
| 77 |
+
# decoder
|
| 78 |
+
self._set_decoder(enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec)
|
| 79 |
+
|
| 80 |
+
# prediction head
|
| 81 |
+
self._set_prediction_head(dec_embed_dim, patch_size)
|
| 82 |
+
|
| 83 |
+
# initializer weights
|
| 84 |
+
self.initialize_weights()
|
| 85 |
+
|
| 86 |
+
def _set_patch_embed(self, img_size=224, patch_size=16, enc_embed_dim=768):
|
| 87 |
+
self.patch_embed = PatchEmbed(img_size, patch_size, 3, enc_embed_dim)
|
| 88 |
+
|
| 89 |
+
def _set_mask_generator(self, num_patches, mask_ratio):
|
| 90 |
+
self.mask_generator = RandomMask(num_patches, mask_ratio)
|
| 91 |
+
|
| 92 |
+
def _set_mask_token(self, dec_embed_dim):
|
| 93 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, dec_embed_dim))
|
| 94 |
+
|
| 95 |
+
def _set_decoder(self, enc_embed_dim, dec_embed_dim, dec_num_heads, dec_depth, mlp_ratio, norm_layer, norm_im2_in_dec):
|
| 96 |
+
self.dec_depth = dec_depth
|
| 97 |
+
self.dec_embed_dim = dec_embed_dim
|
| 98 |
+
# transfer from encoder to decoder
|
| 99 |
+
self.decoder_embed = nn.Linear(enc_embed_dim+0, dec_embed_dim, bias=True)
|
| 100 |
+
# transformer for the decoder
|
| 101 |
+
self.dec_blocks = nn.ModuleList([
|
| 102 |
+
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)
|
| 103 |
+
for i in range(dec_depth)])
|
| 104 |
+
# final norm layer
|
| 105 |
+
self.dec_norm = norm_layer(dec_embed_dim)
|
| 106 |
+
|
| 107 |
+
def _set_prediction_head(self, dec_embed_dim, patch_size):
|
| 108 |
+
self.prediction_head = nn.Linear(dec_embed_dim, patch_size**2 * 3, bias=True)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def initialize_weights(self):
|
| 112 |
+
# patch embed
|
| 113 |
+
self.patch_embed._init_weights()
|
| 114 |
+
# mask tokens
|
| 115 |
+
if self.mask_token is not None: torch.nn.init.normal_(self.mask_token, std=.02)
|
| 116 |
+
# linears and layer norms
|
| 117 |
+
self.apply(self._init_weights)
|
| 118 |
+
|
| 119 |
+
def _init_weights(self, m):
|
| 120 |
+
if isinstance(m, nn.Linear):
|
| 121 |
+
# we use xavier_uniform following official JAX ViT:
|
| 122 |
+
torch.nn.init.xavier_uniform_(m.weight)
|
| 123 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 124 |
+
nn.init.constant_(m.bias, 0)
|
| 125 |
+
elif isinstance(m, nn.LayerNorm):
|
| 126 |
+
nn.init.constant_(m.bias, 0)
|
| 127 |
+
nn.init.constant_(m.weight, 1.0)
|
| 128 |
+
|
| 129 |
+
def _encode_image(self, image, do_mask=False, return_all_blocks=False):
|
| 130 |
+
"""
|
| 131 |
+
image has B x 3 x img_size x img_size
|
| 132 |
+
do_mask: whether to perform masking or not
|
| 133 |
+
return_all_blocks: if True, return the features at the end of every block
|
| 134 |
+
instead of just the features from the last block (eg for some prediction heads)
|
| 135 |
+
"""
|
| 136 |
+
# embed the image into patches (x has size B x Npatches x C)
|
| 137 |
+
# and get position if each return patch (pos has size B x Npatches x 2)
|
| 138 |
+
x, pos = self.patch_embed(image)
|
| 139 |
+
# add positional embedding without cls token
|
| 140 |
+
if self.enc_pos_embed is not None:
|
| 141 |
+
x = x + self.enc_pos_embed[None,...]
|
| 142 |
+
# apply masking
|
| 143 |
+
B,N,C = x.size()
|
| 144 |
+
if do_mask:
|
| 145 |
+
masks = self.mask_generator(x)
|
| 146 |
+
x = x[~masks].view(B, -1, C)
|
| 147 |
+
posvis = pos[~masks].view(B, -1, 2)
|
| 148 |
+
else:
|
| 149 |
+
B,N,C = x.size()
|
| 150 |
+
masks = torch.zeros((B,N), dtype=bool)
|
| 151 |
+
posvis = pos
|
| 152 |
+
# now apply the transformer encoder and normalization
|
| 153 |
+
if return_all_blocks:
|
| 154 |
+
out = []
|
| 155 |
+
for blk in self.enc_blocks:
|
| 156 |
+
x = blk(x, posvis)
|
| 157 |
+
out.append(x)
|
| 158 |
+
out[-1] = self.enc_norm(out[-1])
|
| 159 |
+
return out, pos, masks
|
| 160 |
+
else:
|
| 161 |
+
for blk in self.enc_blocks:
|
| 162 |
+
x = blk(x, posvis)
|
| 163 |
+
x = self.enc_norm(x)
|
| 164 |
+
return x, pos, masks
|
| 165 |
+
|
| 166 |
+
def _decoder(self, feat1, pos1, masks1, feat2, pos2, return_all_blocks=False):
|
| 167 |
+
"""
|
| 168 |
+
return_all_blocks: if True, return the features at the end of every block
|
| 169 |
+
instead of just the features from the last block (eg for some prediction heads)
|
| 170 |
+
|
| 171 |
+
masks1 can be None => assume image1 fully visible
|
| 172 |
+
"""
|
| 173 |
+
# encoder to decoder layer
|
| 174 |
+
visf1 = self.decoder_embed(feat1)
|
| 175 |
+
f2 = self.decoder_embed(feat2)
|
| 176 |
+
# append masked tokens to the sequence
|
| 177 |
+
B,Nenc,C = visf1.size()
|
| 178 |
+
if masks1 is None: # downstreams
|
| 179 |
+
f1_ = visf1
|
| 180 |
+
else: # pretraining
|
| 181 |
+
Ntotal = masks1.size(1)
|
| 182 |
+
f1_ = self.mask_token.repeat(B, Ntotal, 1).to(dtype=visf1.dtype)
|
| 183 |
+
f1_[~masks1] = visf1.view(B * Nenc, C)
|
| 184 |
+
# add positional embedding
|
| 185 |
+
if self.dec_pos_embed is not None:
|
| 186 |
+
f1_ = f1_ + self.dec_pos_embed
|
| 187 |
+
f2 = f2 + self.dec_pos_embed
|
| 188 |
+
# apply Transformer blocks
|
| 189 |
+
out = f1_
|
| 190 |
+
out2 = f2
|
| 191 |
+
if return_all_blocks:
|
| 192 |
+
_out, out = out, []
|
| 193 |
+
for blk in self.dec_blocks:
|
| 194 |
+
_out, out2 = blk(_out, out2, pos1, pos2)
|
| 195 |
+
out.append(_out)
|
| 196 |
+
out[-1] = self.dec_norm(out[-1])
|
| 197 |
+
else:
|
| 198 |
+
for blk in self.dec_blocks:
|
| 199 |
+
out, out2 = blk(out, out2, pos1, pos2)
|
| 200 |
+
out = self.dec_norm(out)
|
| 201 |
+
return out
|
| 202 |
+
|
| 203 |
+
def patchify(self, imgs):
|
| 204 |
+
"""
|
| 205 |
+
imgs: (B, 3, H, W)
|
| 206 |
+
x: (B, L, patch_size**2 *3)
|
| 207 |
+
"""
|
| 208 |
+
p = self.patch_embed.patch_size[0]
|
| 209 |
+
assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0
|
| 210 |
+
|
| 211 |
+
h = w = imgs.shape[2] // p
|
| 212 |
+
x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p))
|
| 213 |
+
x = torch.einsum('nchpwq->nhwpqc', x)
|
| 214 |
+
x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3))
|
| 215 |
+
|
| 216 |
+
return x
|
| 217 |
+
|
| 218 |
+
def unpatchify(self, x, channels=3):
|
| 219 |
+
"""
|
| 220 |
+
x: (N, L, patch_size**2 *channels)
|
| 221 |
+
imgs: (N, 3, H, W)
|
| 222 |
+
"""
|
| 223 |
+
patch_size = self.patch_embed.patch_size[0]
|
| 224 |
+
h = w = int(x.shape[1]**.5)
|
| 225 |
+
assert h * w == x.shape[1]
|
| 226 |
+
x = x.reshape(shape=(x.shape[0], h, w, patch_size, patch_size, channels))
|
| 227 |
+
x = torch.einsum('nhwpqc->nchpwq', x)
|
| 228 |
+
imgs = x.reshape(shape=(x.shape[0], channels, h * patch_size, h * patch_size))
|
| 229 |
+
return imgs
|
| 230 |
+
|
| 231 |
+
def forward(self, img1, img2):
|
| 232 |
+
"""
|
| 233 |
+
img1: tensor of size B x 3 x img_size x img_size
|
| 234 |
+
img2: tensor of size B x 3 x img_size x img_size
|
| 235 |
+
|
| 236 |
+
out will be B x N x (3*patch_size*patch_size)
|
| 237 |
+
masks are also returned as B x N just in case
|
| 238 |
+
"""
|
| 239 |
+
# encoder of the masked first image
|
| 240 |
+
feat1, pos1, mask1 = self._encode_image(img1, do_mask=True)
|
| 241 |
+
# encoder of the second image
|
| 242 |
+
feat2, pos2, _ = self._encode_image(img2, do_mask=False)
|
| 243 |
+
# decoder
|
| 244 |
+
decfeat = self._decoder(feat1, pos1, mask1, feat2, pos2)
|
| 245 |
+
# prediction head
|
| 246 |
+
out = self.prediction_head(decfeat)
|
| 247 |
+
# get target
|
| 248 |
+
target = self.patchify(img1)
|
| 249 |
+
return out, mask1, target
|
src/model/encoder/backbone/croco/curope/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
from .curope2d import cuRoPE2D
|
src/model/encoder/backbone/croco/curope/curope.cpp
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 3 |
+
Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 4 |
+
*/
|
| 5 |
+
|
| 6 |
+
#include <torch/extension.h>
|
| 7 |
+
|
| 8 |
+
// forward declaration
|
| 9 |
+
void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd );
|
| 10 |
+
|
| 11 |
+
void rope_2d_cpu( torch::Tensor tokens, const torch::Tensor positions, const float base, const float fwd )
|
| 12 |
+
{
|
| 13 |
+
const int B = tokens.size(0);
|
| 14 |
+
const int N = tokens.size(1);
|
| 15 |
+
const int H = tokens.size(2);
|
| 16 |
+
const int D = tokens.size(3) / 4;
|
| 17 |
+
|
| 18 |
+
auto tok = tokens.accessor<float, 4>();
|
| 19 |
+
auto pos = positions.accessor<int64_t, 3>();
|
| 20 |
+
|
| 21 |
+
for (int b = 0; b < B; b++) {
|
| 22 |
+
for (int x = 0; x < 2; x++) { // y and then x (2d)
|
| 23 |
+
for (int n = 0; n < N; n++) {
|
| 24 |
+
|
| 25 |
+
// grab the token position
|
| 26 |
+
const int p = pos[b][n][x];
|
| 27 |
+
|
| 28 |
+
for (int h = 0; h < H; h++) {
|
| 29 |
+
for (int d = 0; d < D; d++) {
|
| 30 |
+
// grab the two values
|
| 31 |
+
float u = tok[b][n][h][d+0+x*2*D];
|
| 32 |
+
float v = tok[b][n][h][d+D+x*2*D];
|
| 33 |
+
|
| 34 |
+
// grab the cos,sin
|
| 35 |
+
const float inv_freq = fwd * p / powf(base, d/float(D));
|
| 36 |
+
float c = cosf(inv_freq);
|
| 37 |
+
float s = sinf(inv_freq);
|
| 38 |
+
|
| 39 |
+
// write the result
|
| 40 |
+
tok[b][n][h][d+0+x*2*D] = u*c - v*s;
|
| 41 |
+
tok[b][n][h][d+D+x*2*D] = v*c + u*s;
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
void rope_2d( torch::Tensor tokens, // B,N,H,D
|
| 50 |
+
const torch::Tensor positions, // B,N,2
|
| 51 |
+
const float base,
|
| 52 |
+
const float fwd )
|
| 53 |
+
{
|
| 54 |
+
TORCH_CHECK(tokens.dim() == 4, "tokens must have 4 dimensions");
|
| 55 |
+
TORCH_CHECK(positions.dim() == 3, "positions must have 3 dimensions");
|
| 56 |
+
TORCH_CHECK(tokens.size(0) == positions.size(0), "batch size differs between tokens & positions");
|
| 57 |
+
TORCH_CHECK(tokens.size(1) == positions.size(1), "seq_length differs between tokens & positions");
|
| 58 |
+
TORCH_CHECK(positions.size(2) == 2, "positions.shape[2] must be equal to 2");
|
| 59 |
+
TORCH_CHECK(tokens.is_cuda() == positions.is_cuda(), "tokens and positions are not on the same device" );
|
| 60 |
+
|
| 61 |
+
if (tokens.is_cuda())
|
| 62 |
+
rope_2d_cuda( tokens, positions, base, fwd );
|
| 63 |
+
else
|
| 64 |
+
rope_2d_cpu( tokens, positions, base, fwd );
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 68 |
+
m.def("rope_2d", &rope_2d, "RoPE 2d forward/backward");
|
| 69 |
+
}
|
src/model/encoder/backbone/croco/curope/curope2d.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
import curope as _kernels # run `python setup.py install`
|
| 8 |
+
except ModuleNotFoundError:
|
| 9 |
+
from . import curope as _kernels # run `python setup.py build_ext --inplace`
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class cuRoPE2D_func (torch.autograd.Function):
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def forward(ctx, tokens, positions, base, F0=1):
|
| 16 |
+
ctx.save_for_backward(positions)
|
| 17 |
+
ctx.saved_base = base
|
| 18 |
+
ctx.saved_F0 = F0
|
| 19 |
+
# tokens = tokens.clone() # uncomment this if inplace doesn't work
|
| 20 |
+
_kernels.rope_2d( tokens, positions, base, F0 )
|
| 21 |
+
ctx.mark_dirty(tokens)
|
| 22 |
+
return tokens
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def backward(ctx, grad_res):
|
| 26 |
+
positions, base, F0 = ctx.saved_tensors[0], ctx.saved_base, ctx.saved_F0
|
| 27 |
+
_kernels.rope_2d( grad_res, positions, base, -F0 )
|
| 28 |
+
ctx.mark_dirty(grad_res)
|
| 29 |
+
return grad_res, None, None, None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class cuRoPE2D(torch.nn.Module):
|
| 33 |
+
def __init__(self, freq=100.0, F0=1.0):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.base = freq
|
| 36 |
+
self.F0 = F0
|
| 37 |
+
|
| 38 |
+
def forward(self, tokens, positions):
|
| 39 |
+
cuRoPE2D_func.apply( tokens.transpose(1,2), positions, self.base, self.F0 )
|
| 40 |
+
return tokens
|
src/model/encoder/backbone/croco/curope/kernels.cu
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 3 |
+
Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 4 |
+
*/
|
| 5 |
+
|
| 6 |
+
#include <torch/extension.h>
|
| 7 |
+
#include <cuda.h>
|
| 8 |
+
#include <cuda_runtime.h>
|
| 9 |
+
#include <vector>
|
| 10 |
+
|
| 11 |
+
#define CHECK_CUDA(tensor) {\
|
| 12 |
+
TORCH_CHECK((tensor).is_cuda(), #tensor " is not in cuda memory"); \
|
| 13 |
+
TORCH_CHECK((tensor).is_contiguous(), #tensor " is not contiguous"); }
|
| 14 |
+
void CHECK_KERNEL() {auto error = cudaGetLastError(); TORCH_CHECK( error == cudaSuccess, cudaGetErrorString(error));}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
template < typename scalar_t >
|
| 18 |
+
__global__ void rope_2d_cuda_kernel(
|
| 19 |
+
//scalar_t* __restrict__ tokens,
|
| 20 |
+
torch::PackedTensorAccessor32<scalar_t,4,torch::RestrictPtrTraits> tokens,
|
| 21 |
+
const int64_t* __restrict__ pos,
|
| 22 |
+
const float base,
|
| 23 |
+
const float fwd )
|
| 24 |
+
// const int N, const int H, const int D )
|
| 25 |
+
{
|
| 26 |
+
// tokens shape = (B, N, H, D)
|
| 27 |
+
const int N = tokens.size(1);
|
| 28 |
+
const int H = tokens.size(2);
|
| 29 |
+
const int D = tokens.size(3);
|
| 30 |
+
|
| 31 |
+
// each block update a single token, for all heads
|
| 32 |
+
// each thread takes care of a single output
|
| 33 |
+
extern __shared__ float shared[];
|
| 34 |
+
float* shared_inv_freq = shared + D;
|
| 35 |
+
|
| 36 |
+
const int b = blockIdx.x / N;
|
| 37 |
+
const int n = blockIdx.x % N;
|
| 38 |
+
|
| 39 |
+
const int Q = D / 4;
|
| 40 |
+
// one token = [0..Q : Q..2Q : 2Q..3Q : 3Q..D]
|
| 41 |
+
// u_Y v_Y u_X v_X
|
| 42 |
+
|
| 43 |
+
// shared memory: first, compute inv_freq
|
| 44 |
+
if (threadIdx.x < Q)
|
| 45 |
+
shared_inv_freq[threadIdx.x] = fwd / powf(base, threadIdx.x/float(Q));
|
| 46 |
+
__syncthreads();
|
| 47 |
+
|
| 48 |
+
// start of X or Y part
|
| 49 |
+
const int X = threadIdx.x < D/2 ? 0 : 1;
|
| 50 |
+
const int m = (X*D/2) + (threadIdx.x % Q); // index of u_Y or u_X
|
| 51 |
+
|
| 52 |
+
// grab the cos,sin appropriate for me
|
| 53 |
+
const float freq = pos[blockIdx.x*2+X] * shared_inv_freq[threadIdx.x % Q];
|
| 54 |
+
const float cos = cosf(freq);
|
| 55 |
+
const float sin = sinf(freq);
|
| 56 |
+
/*
|
| 57 |
+
float* shared_cos_sin = shared + D + D/4;
|
| 58 |
+
if ((threadIdx.x % (D/2)) < Q)
|
| 59 |
+
shared_cos_sin[m+0] = cosf(freq);
|
| 60 |
+
else
|
| 61 |
+
shared_cos_sin[m+Q] = sinf(freq);
|
| 62 |
+
__syncthreads();
|
| 63 |
+
const float cos = shared_cos_sin[m+0];
|
| 64 |
+
const float sin = shared_cos_sin[m+Q];
|
| 65 |
+
*/
|
| 66 |
+
|
| 67 |
+
for (int h = 0; h < H; h++)
|
| 68 |
+
{
|
| 69 |
+
// then, load all the token for this head in shared memory
|
| 70 |
+
shared[threadIdx.x] = tokens[b][n][h][threadIdx.x];
|
| 71 |
+
__syncthreads();
|
| 72 |
+
|
| 73 |
+
const float u = shared[m];
|
| 74 |
+
const float v = shared[m+Q];
|
| 75 |
+
|
| 76 |
+
// write output
|
| 77 |
+
if ((threadIdx.x % (D/2)) < Q)
|
| 78 |
+
tokens[b][n][h][threadIdx.x] = u*cos - v*sin;
|
| 79 |
+
else
|
| 80 |
+
tokens[b][n][h][threadIdx.x] = v*cos + u*sin;
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd )
|
| 85 |
+
{
|
| 86 |
+
const int B = tokens.size(0); // batch size
|
| 87 |
+
const int N = tokens.size(1); // sequence length
|
| 88 |
+
const int H = tokens.size(2); // number of heads
|
| 89 |
+
const int D = tokens.size(3); // dimension per head
|
| 90 |
+
|
| 91 |
+
TORCH_CHECK(tokens.stride(3) == 1 && tokens.stride(2) == D, "tokens are not contiguous");
|
| 92 |
+
TORCH_CHECK(pos.is_contiguous(), "positions are not contiguous");
|
| 93 |
+
TORCH_CHECK(pos.size(0) == B && pos.size(1) == N && pos.size(2) == 2, "bad pos.shape");
|
| 94 |
+
TORCH_CHECK(D % 4 == 0, "token dim must be multiple of 4");
|
| 95 |
+
|
| 96 |
+
// one block for each layer, one thread per local-max
|
| 97 |
+
const int THREADS_PER_BLOCK = D;
|
| 98 |
+
const int N_BLOCKS = B * N; // each block takes care of H*D values
|
| 99 |
+
const int SHARED_MEM = sizeof(float) * (D + D/4);
|
| 100 |
+
|
| 101 |
+
AT_DISPATCH_FLOATING_TYPES_AND_HALF(tokens.type(), "rope_2d_cuda", ([&] {
|
| 102 |
+
rope_2d_cuda_kernel<scalar_t> <<<N_BLOCKS, THREADS_PER_BLOCK, SHARED_MEM>>> (
|
| 103 |
+
//tokens.data_ptr<scalar_t>(),
|
| 104 |
+
tokens.packed_accessor32<scalar_t,4,torch::RestrictPtrTraits>(),
|
| 105 |
+
pos.data_ptr<int64_t>(),
|
| 106 |
+
base, fwd); //, N, H, D );
|
| 107 |
+
}));
|
| 108 |
+
}
|
src/model/encoder/backbone/croco/curope/setup.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
from setuptools import setup
|
| 5 |
+
from torch import cuda
|
| 6 |
+
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
|
| 7 |
+
|
| 8 |
+
# compile for all possible CUDA architectures
|
| 9 |
+
all_cuda_archs = cuda.get_gencode_flags().replace('compute=','arch=').split()
|
| 10 |
+
# alternatively, you can list cuda archs that you want, eg:
|
| 11 |
+
# all_cuda_archs = [
|
| 12 |
+
# '-gencode', 'arch=compute_70,code=sm_70',
|
| 13 |
+
# '-gencode', 'arch=compute_75,code=sm_75',
|
| 14 |
+
# '-gencode', 'arch=compute_80,code=sm_80',
|
| 15 |
+
# '-gencode', 'arch=compute_86,code=sm_86'
|
| 16 |
+
# ]
|
| 17 |
+
|
| 18 |
+
setup(
|
| 19 |
+
name = 'curope',
|
| 20 |
+
ext_modules = [
|
| 21 |
+
CUDAExtension(
|
| 22 |
+
name='curope',
|
| 23 |
+
sources=[
|
| 24 |
+
"curope.cpp",
|
| 25 |
+
"kernels.cu",
|
| 26 |
+
],
|
| 27 |
+
extra_compile_args = dict(
|
| 28 |
+
nvcc=['-O3','--ptxas-options=-v',"--use_fast_math"]+all_cuda_archs,
|
| 29 |
+
cxx=['-O3'])
|
| 30 |
+
)
|
| 31 |
+
],
|
| 32 |
+
cmdclass = {
|
| 33 |
+
'build_ext': BuildExtension
|
| 34 |
+
})
|
src/model/encoder/backbone/croco/masking.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
# Masking utils
|
| 7 |
+
# --------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
|
| 12 |
+
class RandomMask(nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
random masking
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, num_patches, mask_ratio):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.num_patches = num_patches
|
| 20 |
+
self.num_mask = int(mask_ratio * self.num_patches)
|
| 21 |
+
|
| 22 |
+
def __call__(self, x):
|
| 23 |
+
noise = torch.rand(x.size(0), self.num_patches, device=x.device)
|
| 24 |
+
argsort = torch.argsort(noise, dim=1)
|
| 25 |
+
return argsort < self.num_mask
|
src/model/encoder/backbone/croco/misc.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# utilitary functions for DUSt3R
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def fill_default_args(kwargs, func):
|
| 11 |
+
import inspect # a bit hacky but it works reliably
|
| 12 |
+
signature = inspect.signature(func)
|
| 13 |
+
|
| 14 |
+
for k, v in signature.parameters.items():
|
| 15 |
+
if v.default is inspect.Parameter.empty:
|
| 16 |
+
continue
|
| 17 |
+
kwargs.setdefault(k, v.default)
|
| 18 |
+
|
| 19 |
+
return kwargs
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def freeze_all_params(modules):
|
| 23 |
+
for module in modules:
|
| 24 |
+
try:
|
| 25 |
+
for n, param in module.named_parameters():
|
| 26 |
+
param.requires_grad = False
|
| 27 |
+
except AttributeError:
|
| 28 |
+
# module is directly a parameter
|
| 29 |
+
module.requires_grad = False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_symmetrized(gt1, gt2):
|
| 33 |
+
x = gt1['instance']
|
| 34 |
+
y = gt2['instance']
|
| 35 |
+
if len(x) == len(y) and len(x) == 1:
|
| 36 |
+
return False # special case of batchsize 1
|
| 37 |
+
ok = True
|
| 38 |
+
for i in range(0, len(x), 2):
|
| 39 |
+
ok = ok and (x[i] == y[i+1]) and (x[i+1] == y[i])
|
| 40 |
+
return ok
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def flip(tensor):
|
| 44 |
+
""" flip so that tensor[0::2] <=> tensor[1::2] """
|
| 45 |
+
return torch.stack((tensor[1::2], tensor[0::2]), dim=1).flatten(0, 1)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def interleave(tensor1, tensor2):
|
| 49 |
+
res1 = torch.stack((tensor1, tensor2), dim=1).flatten(0, 1)
|
| 50 |
+
res2 = torch.stack((tensor2, tensor1), dim=1).flatten(0, 1)
|
| 51 |
+
return res1, res2
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _interleave_imgs(img1, img2):
|
| 55 |
+
res = {}
|
| 56 |
+
for key, value1 in img1.items():
|
| 57 |
+
value2 = img2[key]
|
| 58 |
+
if isinstance(value1, torch.Tensor):
|
| 59 |
+
value = torch.stack((value1, value2), dim=1).flatten(0, 1)
|
| 60 |
+
else:
|
| 61 |
+
value = [x for pair in zip(value1, value2) for x in pair]
|
| 62 |
+
res[key] = value
|
| 63 |
+
return res
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def make_batch_symmetric(view1, view2):
|
| 67 |
+
view1, view2 = (_interleave_imgs(view1, view2), _interleave_imgs(view2, view1))
|
| 68 |
+
return view1, view2
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def transpose_to_landscape(head, activate=True):
|
| 72 |
+
""" Predict in the correct aspect-ratio,
|
| 73 |
+
then transpose the result in landscape
|
| 74 |
+
and stack everything back together.
|
| 75 |
+
"""
|
| 76 |
+
def wrapper_no(decout, true_shape, ray_embedding=None):
|
| 77 |
+
B = len(true_shape)
|
| 78 |
+
assert true_shape[0:1].allclose(true_shape), 'true_shape must be all identical'
|
| 79 |
+
H, W = true_shape[0].cpu().tolist()
|
| 80 |
+
res = head(decout, (H, W), ray_embedding=ray_embedding)
|
| 81 |
+
return res
|
| 82 |
+
|
| 83 |
+
def wrapper_yes(decout, true_shape, ray_embedding=None):
|
| 84 |
+
B = len(true_shape)
|
| 85 |
+
# by definition, the batch is in landscape mode so W >= H
|
| 86 |
+
H, W = int(true_shape.min()), int(true_shape.max())
|
| 87 |
+
|
| 88 |
+
height, width = true_shape.T
|
| 89 |
+
is_landscape = (width >= height)
|
| 90 |
+
is_portrait = ~is_landscape
|
| 91 |
+
|
| 92 |
+
# true_shape = true_shape.cpu()
|
| 93 |
+
if is_landscape.all():
|
| 94 |
+
return head(decout, (H, W), ray_embedding=ray_embedding)
|
| 95 |
+
if is_portrait.all():
|
| 96 |
+
return transposed(head(decout, (W, H), ray_embedding=ray_embedding))
|
| 97 |
+
|
| 98 |
+
# batch is a mix of both portraint & landscape
|
| 99 |
+
def selout(ar): return [d[ar] for d in decout]
|
| 100 |
+
l_result = head(selout(is_landscape), (H, W), ray_embedding=ray_embedding)
|
| 101 |
+
p_result = transposed(head(selout(is_portrait), (W, H), ray_embedding=ray_embedding))
|
| 102 |
+
|
| 103 |
+
# allocate full result
|
| 104 |
+
result = {}
|
| 105 |
+
for k in l_result | p_result:
|
| 106 |
+
x = l_result[k].new(B, *l_result[k].shape[1:])
|
| 107 |
+
x[is_landscape] = l_result[k]
|
| 108 |
+
x[is_portrait] = p_result[k]
|
| 109 |
+
result[k] = x
|
| 110 |
+
|
| 111 |
+
return result
|
| 112 |
+
|
| 113 |
+
return wrapper_yes if activate else wrapper_no
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def transposed(dic):
|
| 117 |
+
return {k: v.swapaxes(1, 2) for k, v in dic.items()}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def invalid_to_nans(arr, valid_mask, ndim=999):
|
| 121 |
+
if valid_mask is not None:
|
| 122 |
+
arr = arr.clone()
|
| 123 |
+
arr[~valid_mask] = float('nan')
|
| 124 |
+
if arr.ndim > ndim:
|
| 125 |
+
arr = arr.flatten(-2 - (arr.ndim - ndim), -2)
|
| 126 |
+
return arr
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def invalid_to_zeros(arr, valid_mask, ndim=999):
|
| 130 |
+
if valid_mask is not None:
|
| 131 |
+
arr = arr.clone()
|
| 132 |
+
arr[~valid_mask] = 0
|
| 133 |
+
nnz = valid_mask.view(len(valid_mask), -1).sum(1)
|
| 134 |
+
else:
|
| 135 |
+
nnz = arr.numel() // len(arr) if len(arr) else 0 # number of point per image
|
| 136 |
+
if arr.ndim > ndim:
|
| 137 |
+
arr = arr.flatten(-2 - (arr.ndim - ndim), -2)
|
| 138 |
+
return arr, nnz
|
src/model/encoder/backbone/croco/patch_embed.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# PatchEmbed implementation for DUST3R,
|
| 6 |
+
# in particular ManyAR_PatchEmbed that Handle images with non-square aspect ratio
|
| 7 |
+
# --------------------------------------------------------
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from .blocks import PatchEmbed
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_patch_embed(patch_embed_cls, img_size, patch_size, enc_embed_dim, in_chans=3):
|
| 14 |
+
assert patch_embed_cls in ['PatchEmbedDust3R', 'ManyAR_PatchEmbed']
|
| 15 |
+
patch_embed = eval(patch_embed_cls)(img_size, patch_size, in_chans, enc_embed_dim)
|
| 16 |
+
return patch_embed
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PatchEmbedDust3R(PatchEmbed):
|
| 20 |
+
def forward(self, x, **kw):
|
| 21 |
+
B, C, H, W = x.shape
|
| 22 |
+
assert H % self.patch_size[0] == 0, f"Input image height ({H}) is not a multiple of patch size ({self.patch_size[0]})."
|
| 23 |
+
assert W % self.patch_size[1] == 0, f"Input image width ({W}) is not a multiple of patch size ({self.patch_size[1]})."
|
| 24 |
+
x = self.proj(x)
|
| 25 |
+
pos = self.position_getter(B, x.size(2), x.size(3), x.device)
|
| 26 |
+
if self.flatten:
|
| 27 |
+
x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
|
| 28 |
+
x = self.norm(x)
|
| 29 |
+
return x, pos
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ManyAR_PatchEmbed (PatchEmbed):
|
| 33 |
+
""" Handle images with non-square aspect ratio.
|
| 34 |
+
All images in the same batch have the same aspect ratio.
|
| 35 |
+
true_shape = [(height, width) ...] indicates the actual shape of each image.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
|
| 39 |
+
self.embed_dim = embed_dim
|
| 40 |
+
super().__init__(img_size, patch_size, in_chans, embed_dim, norm_layer, flatten)
|
| 41 |
+
|
| 42 |
+
def forward(self, img, true_shape):
|
| 43 |
+
B, C, H, W = img.shape
|
| 44 |
+
assert W >= H, f'img should be in landscape mode, but got {W=} {H=}'
|
| 45 |
+
assert H % self.patch_size[0] == 0, f"Input image height ({H}) is not a multiple of patch size ({self.patch_size[0]})."
|
| 46 |
+
assert W % self.patch_size[1] == 0, f"Input image width ({W}) is not a multiple of patch size ({self.patch_size[1]})."
|
| 47 |
+
assert true_shape.shape == (B, 2), f"true_shape has the wrong shape={true_shape.shape}"
|
| 48 |
+
|
| 49 |
+
# size expressed in tokens
|
| 50 |
+
W //= self.patch_size[0]
|
| 51 |
+
H //= self.patch_size[1]
|
| 52 |
+
n_tokens = H * W
|
| 53 |
+
|
| 54 |
+
height, width = true_shape.T
|
| 55 |
+
is_landscape = (width >= height)
|
| 56 |
+
is_portrait = ~is_landscape
|
| 57 |
+
|
| 58 |
+
# allocate result
|
| 59 |
+
x = img.new_zeros((B, n_tokens, self.embed_dim))
|
| 60 |
+
pos = img.new_zeros((B, n_tokens, 2), dtype=torch.int64)
|
| 61 |
+
|
| 62 |
+
# linear projection, transposed if necessary
|
| 63 |
+
x[is_landscape] = self.proj(img[is_landscape]).permute(0, 2, 3, 1).flatten(1, 2).float()
|
| 64 |
+
x[is_portrait] = self.proj(img[is_portrait].swapaxes(-1, -2)).permute(0, 2, 3, 1).flatten(1, 2).float()
|
| 65 |
+
|
| 66 |
+
pos[is_landscape] = self.position_getter(1, H, W, pos.device)
|
| 67 |
+
pos[is_portrait] = self.position_getter(1, W, H, pos.device)
|
| 68 |
+
|
| 69 |
+
x = self.norm(x)
|
| 70 |
+
return x, pos
|
src/model/encoder/backbone/croco/pos_embed.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# --------------------------------------------------------
|
| 6 |
+
# Position embedding utils
|
| 7 |
+
# --------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
# --------------------------------------------------------
|
| 16 |
+
# 2D sine-cosine position embedding
|
| 17 |
+
# References:
|
| 18 |
+
# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
|
| 19 |
+
# Transformer: https://github.com/tensorflow/models/blob/master/official/nlp/transformer/model_utils.py
|
| 20 |
+
# MoCo v3: https://github.com/facebookresearch/moco-v3
|
| 21 |
+
# --------------------------------------------------------
|
| 22 |
+
def get_2d_sincos_pos_embed(embed_dim, grid_size, n_cls_token=0):
|
| 23 |
+
"""
|
| 24 |
+
grid_size: int of the grid height and width
|
| 25 |
+
return:
|
| 26 |
+
pos_embed: [grid_size*grid_size, embed_dim] or [n_cls_token+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
|
| 27 |
+
"""
|
| 28 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 29 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 30 |
+
grid = np.meshgrid(grid_w, grid_h) # here w goes first
|
| 31 |
+
grid = np.stack(grid, axis=0)
|
| 32 |
+
|
| 33 |
+
grid = grid.reshape([2, 1, grid_size, grid_size])
|
| 34 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 35 |
+
if n_cls_token>0:
|
| 36 |
+
pos_embed = np.concatenate([np.zeros([n_cls_token, embed_dim]), pos_embed], axis=0)
|
| 37 |
+
return pos_embed
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
|
| 41 |
+
assert embed_dim % 2 == 0
|
| 42 |
+
|
| 43 |
+
# use half of dimensions to encode grid_h
|
| 44 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
|
| 45 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
|
| 46 |
+
|
| 47 |
+
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
|
| 48 |
+
return emb
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
| 52 |
+
"""
|
| 53 |
+
embed_dim: output dimension for each position
|
| 54 |
+
pos: a list of positions to be encoded: size (M,)
|
| 55 |
+
out: (M, D)
|
| 56 |
+
"""
|
| 57 |
+
assert embed_dim % 2 == 0
|
| 58 |
+
omega = np.arange(embed_dim // 2, dtype=float)
|
| 59 |
+
omega /= embed_dim / 2.
|
| 60 |
+
omega = 1. / 10000**omega # (D/2,)
|
| 61 |
+
|
| 62 |
+
pos = pos.reshape(-1) # (M,)
|
| 63 |
+
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
|
| 64 |
+
|
| 65 |
+
emb_sin = np.sin(out) # (M, D/2)
|
| 66 |
+
emb_cos = np.cos(out) # (M, D/2)
|
| 67 |
+
|
| 68 |
+
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
|
| 69 |
+
return emb
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# --------------------------------------------------------
|
| 73 |
+
# Interpolate position embeddings for high-resolution
|
| 74 |
+
# References:
|
| 75 |
+
# MAE: https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
|
| 76 |
+
# DeiT: https://github.com/facebookresearch/deit
|
| 77 |
+
# --------------------------------------------------------
|
| 78 |
+
def interpolate_pos_embed(model, checkpoint_model):
|
| 79 |
+
if 'pos_embed' in checkpoint_model:
|
| 80 |
+
pos_embed_checkpoint = checkpoint_model['pos_embed']
|
| 81 |
+
embedding_size = pos_embed_checkpoint.shape[-1]
|
| 82 |
+
num_patches = model.patch_embed.num_patches
|
| 83 |
+
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
|
| 84 |
+
# height (== width) for the checkpoint position embedding
|
| 85 |
+
orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
|
| 86 |
+
# height (== width) for the new position embedding
|
| 87 |
+
new_size = int(num_patches ** 0.5)
|
| 88 |
+
# class_token and dist_token are kept unchanged
|
| 89 |
+
if orig_size != new_size:
|
| 90 |
+
print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size))
|
| 91 |
+
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
|
| 92 |
+
# only the position tokens are interpolated
|
| 93 |
+
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
|
| 94 |
+
pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
|
| 95 |
+
pos_tokens = torch.nn.functional.interpolate(
|
| 96 |
+
pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
|
| 97 |
+
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
|
| 98 |
+
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
|
| 99 |
+
checkpoint_model['pos_embed'] = new_pos_embed
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
#----------------------------------------------------------
|
| 103 |
+
# RoPE2D: RoPE implementation in 2D
|
| 104 |
+
#----------------------------------------------------------
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
from .curope import cuRoPE2D
|
| 108 |
+
RoPE2D = cuRoPE2D
|
| 109 |
+
except ImportError:
|
| 110 |
+
print('Warning, cannot find cuda-compiled version of RoPE2D, using a slow pytorch version instead')
|
| 111 |
+
|
| 112 |
+
class RoPE2D(torch.nn.Module):
|
| 113 |
+
|
| 114 |
+
def __init__(self, freq=100.0, F0=1.0):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.base = freq
|
| 117 |
+
self.F0 = F0
|
| 118 |
+
self.cache = {}
|
| 119 |
+
|
| 120 |
+
def get_cos_sin(self, D, seq_len, device, dtype):
|
| 121 |
+
if (D,seq_len,device,dtype) not in self.cache:
|
| 122 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D))
|
| 123 |
+
t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype)
|
| 124 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype)
|
| 125 |
+
freqs = torch.cat((freqs, freqs), dim=-1)
|
| 126 |
+
cos = freqs.cos() # (Seq, Dim)
|
| 127 |
+
sin = freqs.sin()
|
| 128 |
+
self.cache[D,seq_len,device,dtype] = (cos,sin)
|
| 129 |
+
return self.cache[D,seq_len,device,dtype]
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def rotate_half(x):
|
| 133 |
+
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 134 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 135 |
+
|
| 136 |
+
def apply_rope1d(self, tokens, pos1d, cos, sin):
|
| 137 |
+
assert pos1d.ndim==2
|
| 138 |
+
cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :]
|
| 139 |
+
sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :]
|
| 140 |
+
return (tokens * cos) + (self.rotate_half(tokens) * sin)
|
| 141 |
+
|
| 142 |
+
def forward(self, tokens, positions):
|
| 143 |
+
"""
|
| 144 |
+
input:
|
| 145 |
+
* tokens: batch_size x nheads x ntokens x dim
|
| 146 |
+
* positions: batch_size x ntokens x 2 (y and x position of each token)
|
| 147 |
+
output:
|
| 148 |
+
* tokens after appplying RoPE2D (batch_size x nheads x ntokens x dim)
|
| 149 |
+
"""
|
| 150 |
+
assert tokens.size(3)%2==0, "number of dimensions should be a multiple of two"
|
| 151 |
+
D = tokens.size(3) // 2
|
| 152 |
+
assert positions.ndim==3 and positions.shape[-1] == 2 # Batch, Seq, 2
|
| 153 |
+
cos, sin = self.get_cos_sin(D, int(positions.max())+1, tokens.device, tokens.dtype)
|
| 154 |
+
# split features into two along the feature dimension, and apply rope1d on each half
|
| 155 |
+
y, x = tokens.chunk(2, dim=-1)
|
| 156 |
+
y = self.apply_rope1d(y, positions[:,:,0], cos, sin)
|
| 157 |
+
x = self.apply_rope1d(x, positions[:,:,1], cos, sin)
|
| 158 |
+
tokens = torch.cat((y, x), dim=-1)
|
| 159 |
+
return tokens
|
src/model/encoder/common/gaussian_adapter.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from einops import einsum, rearrange
|
| 7 |
+
from jaxtyping import Float
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
|
| 10 |
+
from src.geometry.projection import get_world_rays
|
| 11 |
+
from src.misc.sh_rotation import rotate_sh
|
| 12 |
+
from .gaussians import build_covariance
|
| 13 |
+
|
| 14 |
+
from ...types import Gaussians
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class GaussianAdapterCfg:
|
| 18 |
+
gaussian_scale_min: float
|
| 19 |
+
gaussian_scale_max: float
|
| 20 |
+
sh_degree: int
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class GaussianAdapter(nn.Module):
|
| 24 |
+
cfg: GaussianAdapterCfg
|
| 25 |
+
|
| 26 |
+
def __init__(self, cfg: GaussianAdapterCfg):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.cfg = cfg
|
| 29 |
+
|
| 30 |
+
# Create a mask for the spherical harmonics coefficients. This ensures that at
|
| 31 |
+
# initialization, the coefficients are biased towards having a large DC
|
| 32 |
+
# component and small view-dependent components.
|
| 33 |
+
self.register_buffer(
|
| 34 |
+
"sh_mask",
|
| 35 |
+
torch.ones((self.d_sh,), dtype=torch.float32),
|
| 36 |
+
persistent=False,
|
| 37 |
+
)
|
| 38 |
+
for degree in range(1, self.cfg.sh_degree + 1):
|
| 39 |
+
self.sh_mask[degree**2 : (degree + 1) ** 2] = 0.1 * 0.25**degree
|
| 40 |
+
|
| 41 |
+
def forward(
|
| 42 |
+
self,
|
| 43 |
+
extrinsics: Float[Tensor, "*#batch 4 4"],
|
| 44 |
+
intrinsics: Float[Tensor, "*#batch 3 3"],
|
| 45 |
+
coordinates: Float[Tensor, "*#batch 2"],
|
| 46 |
+
depths: Float[Tensor, "*#batch"],
|
| 47 |
+
opacities: Float[Tensor, "*#batch"],
|
| 48 |
+
raw_gaussians: Float[Tensor, "*#batch _"],
|
| 49 |
+
image_shape: tuple[int, int],
|
| 50 |
+
eps: float = 1e-8,
|
| 51 |
+
) -> Gaussians:
|
| 52 |
+
device = extrinsics.device
|
| 53 |
+
scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1)
|
| 54 |
+
|
| 55 |
+
# Map scale features to valid scale range.
|
| 56 |
+
scale_min = self.cfg.gaussian_scale_min
|
| 57 |
+
scale_max = self.cfg.gaussian_scale_max
|
| 58 |
+
scales = scale_min + (scale_max - scale_min) * scales.sigmoid()
|
| 59 |
+
h, w = image_shape
|
| 60 |
+
pixel_size = 1 / torch.tensor((w, h), dtype=torch.float32, device=device)
|
| 61 |
+
multiplier = self.get_scale_multiplier(intrinsics, pixel_size)
|
| 62 |
+
scales = scales * depths[..., None] * multiplier[..., None]
|
| 63 |
+
|
| 64 |
+
# Normalize the quaternion features to yield a valid quaternion.
|
| 65 |
+
rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps)
|
| 66 |
+
|
| 67 |
+
sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3)
|
| 68 |
+
sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask
|
| 69 |
+
|
| 70 |
+
# Create world-space covariance matrices.
|
| 71 |
+
covariances = build_covariance(scales, rotations)
|
| 72 |
+
c2w_rotations = extrinsics[..., :3, :3]
|
| 73 |
+
covariances = c2w_rotations @ covariances @ c2w_rotations.transpose(-1, -2)
|
| 74 |
+
|
| 75 |
+
# Compute Gaussian means.
|
| 76 |
+
origins, directions = get_world_rays(coordinates, extrinsics, intrinsics)
|
| 77 |
+
means = origins + directions * depths[..., None]
|
| 78 |
+
|
| 79 |
+
return Gaussians(
|
| 80 |
+
means=means,
|
| 81 |
+
covariances=covariances,
|
| 82 |
+
# harmonics=rotate_sh(sh, c2w_rotations[..., None, :, :]),
|
| 83 |
+
harmonics=sh,
|
| 84 |
+
opacities=opacities,
|
| 85 |
+
# Note: These aren't yet rotated into world space, but they're only used for
|
| 86 |
+
# exporting Gaussians to ply files. This needs to be fixed...
|
| 87 |
+
scales=scales,
|
| 88 |
+
rotations=rotations.broadcast_to((*scales.shape[:-1], 4)),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def get_scale_multiplier(
|
| 92 |
+
self,
|
| 93 |
+
intrinsics: Float[Tensor, "*#batch 3 3"],
|
| 94 |
+
pixel_size: Float[Tensor, "*#batch 2"],
|
| 95 |
+
multiplier: float = 0.1,
|
| 96 |
+
) -> Float[Tensor, " *batch"]:
|
| 97 |
+
xy_multipliers = multiplier * einsum(
|
| 98 |
+
intrinsics[..., :2, :2].inverse(),
|
| 99 |
+
pixel_size,
|
| 100 |
+
"... i j, j -> ... i",
|
| 101 |
+
)
|
| 102 |
+
return xy_multipliers.sum(dim=-1)
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def d_sh(self) -> int:
|
| 106 |
+
return (self.cfg.sh_degree + 1) ** 2
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def d_in(self) -> int:
|
| 110 |
+
return 7 + 3 * self.d_sh
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class UnifiedGaussianAdapter(GaussianAdapter):
|
| 114 |
+
def forward(
|
| 115 |
+
self,
|
| 116 |
+
means: Float[Tensor, "*#batch 3"],
|
| 117 |
+
# levels: Float[Tensor, "*#batch"],
|
| 118 |
+
depths: Float[Tensor, "*#batch"],
|
| 119 |
+
opacities: Float[Tensor, "*#batch"],
|
| 120 |
+
raw_gaussians: Float[Tensor, "*#batch _"],
|
| 121 |
+
eps: float = 1e-8,
|
| 122 |
+
intrinsics: Optional[Float[Tensor, "*#batch 3 3"]] = None,
|
| 123 |
+
coordinates: Optional[Float[Tensor, "*#batch 2"]] = None,
|
| 124 |
+
) -> Gaussians:
|
| 125 |
+
scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1)
|
| 126 |
+
|
| 127 |
+
scales = 0.001 * F.softplus(scales)
|
| 128 |
+
scales = scales.clamp_max(0.3)
|
| 129 |
+
|
| 130 |
+
# Normalize the quaternion features to yield a valid quaternion.
|
| 131 |
+
rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps)
|
| 132 |
+
|
| 133 |
+
sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3)
|
| 134 |
+
sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask
|
| 135 |
+
# print(scales.max())
|
| 136 |
+
covariances = build_covariance(scales, rotations)
|
| 137 |
+
|
| 138 |
+
return Gaussians(
|
| 139 |
+
means=means.float(),
|
| 140 |
+
# levels=levels.int(),
|
| 141 |
+
covariances=covariances.float(),
|
| 142 |
+
harmonics=sh.float(),
|
| 143 |
+
opacities=opacities.float(),
|
| 144 |
+
scales=scales.float(),
|
| 145 |
+
rotations=rotations.float(),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
class Unet3dGaussianAdapter(GaussianAdapter):
|
| 149 |
+
def forward(
|
| 150 |
+
self,
|
| 151 |
+
means: Float[Tensor, "*#batch 3"],
|
| 152 |
+
depths: Float[Tensor, "*#batch"],
|
| 153 |
+
opacities: Float[Tensor, "*#batch"],
|
| 154 |
+
raw_gaussians: Float[Tensor, "*#batch _"],
|
| 155 |
+
eps: float = 1e-8,
|
| 156 |
+
intrinsics: Optional[Float[Tensor, "*#batch 3 3"]] = None,
|
| 157 |
+
coordinates: Optional[Float[Tensor, "*#batch 2"]] = None,
|
| 158 |
+
) -> Gaussians:
|
| 159 |
+
scales, rotations, sh = raw_gaussians.split((3, 4, 3 * self.d_sh), dim=-1)
|
| 160 |
+
|
| 161 |
+
scales = 0.001 * F.softplus(scales)
|
| 162 |
+
scales = scales.clamp_max(0.3)
|
| 163 |
+
|
| 164 |
+
# Normalize the quaternion features to yield a valid quaternion.
|
| 165 |
+
rotations = rotations / (rotations.norm(dim=-1, keepdim=True) + eps)
|
| 166 |
+
|
| 167 |
+
sh = rearrange(sh, "... (xyz d_sh) -> ... xyz d_sh", xyz=3)
|
| 168 |
+
sh = sh.broadcast_to((*opacities.shape, 3, self.d_sh)) * self.sh_mask
|
| 169 |
+
|
| 170 |
+
covariances = build_covariance(scales, rotations)
|
| 171 |
+
|
| 172 |
+
return Gaussians(
|
| 173 |
+
means=means,
|
| 174 |
+
covariances=covariances,
|
| 175 |
+
harmonics=sh,
|
| 176 |
+
opacities=opacities,
|
| 177 |
+
scales=scales,
|
| 178 |
+
rotations=rotations,
|
| 179 |
+
)
|
| 180 |
+
|
src/model/encoder/common/gaussians.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from einops import rearrange
|
| 3 |
+
from jaxtyping import Float
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# https://github.com/facebookresearch/pytorch3d/blob/main/pytorch3d/transforms/rotation_conversions.py
|
| 8 |
+
def quaternion_to_matrix(
|
| 9 |
+
quaternions: Float[Tensor, "*batch 4"],
|
| 10 |
+
eps: float = 1e-8,
|
| 11 |
+
) -> Float[Tensor, "*batch 3 3"]:
|
| 12 |
+
# Order changed to match scipy format!
|
| 13 |
+
i, j, k, r = torch.unbind(quaternions, dim=-1)
|
| 14 |
+
two_s = 2 / ((quaternions * quaternions).sum(dim=-1) + eps)
|
| 15 |
+
|
| 16 |
+
o = torch.stack(
|
| 17 |
+
(
|
| 18 |
+
1 - two_s * (j * j + k * k),
|
| 19 |
+
two_s * (i * j - k * r),
|
| 20 |
+
two_s * (i * k + j * r),
|
| 21 |
+
two_s * (i * j + k * r),
|
| 22 |
+
1 - two_s * (i * i + k * k),
|
| 23 |
+
two_s * (j * k - i * r),
|
| 24 |
+
two_s * (i * k - j * r),
|
| 25 |
+
two_s * (j * k + i * r),
|
| 26 |
+
1 - two_s * (i * i + j * j),
|
| 27 |
+
),
|
| 28 |
+
-1,
|
| 29 |
+
)
|
| 30 |
+
return rearrange(o, "... (i j) -> ... i j", i=3, j=3)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def build_covariance(
|
| 34 |
+
scale: Float[Tensor, "*#batch 3"],
|
| 35 |
+
rotation_xyzw: Float[Tensor, "*#batch 4"],
|
| 36 |
+
) -> Float[Tensor, "*batch 3 3"]:
|
| 37 |
+
scale = scale.diag_embed()
|
| 38 |
+
rotation = quaternion_to_matrix(rotation_xyzw)
|
| 39 |
+
return (
|
| 40 |
+
rotation
|
| 41 |
+
@ scale
|
| 42 |
+
@ rearrange(scale, "... i j -> ... j i")
|
| 43 |
+
@ rearrange(rotation, "... i j -> ... j i")
|
| 44 |
+
)
|
src/model/encoder/encoder.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Generic, TypeVar
|
| 3 |
+
|
| 4 |
+
from torch import nn
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from src.dataset.types import BatchedViews, DataShim
|
| 7 |
+
from ..types import Gaussians
|
| 8 |
+
from jaxtyping import Float
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
T = TypeVar("T")
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class EncoderOutput:
|
| 15 |
+
gaussians: Gaussians
|
| 16 |
+
pred_pose_enc_list: list[Float[Tensor, "batch view 6"]] | None
|
| 17 |
+
pred_context_pose: dict | None
|
| 18 |
+
depth_dict: dict | None
|
| 19 |
+
infos: dict | None
|
| 20 |
+
distill_infos: dict | None
|
| 21 |
+
|
| 22 |
+
class Encoder(nn.Module, ABC, Generic[T]):
|
| 23 |
+
cfg: T
|
| 24 |
+
|
| 25 |
+
def __init__(self, cfg: T) -> None:
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.cfg = cfg
|
| 28 |
+
|
| 29 |
+
@abstractmethod
|
| 30 |
+
def forward(
|
| 31 |
+
self,
|
| 32 |
+
context: BatchedViews,
|
| 33 |
+
) -> Gaussians:
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
def get_data_shim(self) -> DataShim:
|
| 37 |
+
"""The default shim doesn't modify the batch."""
|
| 38 |
+
return lambda x: x
|
src/model/encoder/heads/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# head factory
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
from .dpt_gs_head import create_gs_dpt_head
|
| 8 |
+
from .linear_head import LinearPts3d
|
| 9 |
+
from .linear_gs_head import create_gs_linear_head
|
| 10 |
+
from .dpt_head import create_dpt_head
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def head_factory(head_type, output_mode, net, has_conf=False, out_nchan=3):
|
| 14 |
+
"""" build a prediction head for the decoder
|
| 15 |
+
"""
|
| 16 |
+
if head_type == 'linear' and output_mode == 'pts3d':
|
| 17 |
+
return LinearPts3d(net, has_conf)
|
| 18 |
+
elif head_type == 'dpt' and output_mode == 'pts3d':
|
| 19 |
+
return create_dpt_head(net, has_conf=has_conf)
|
| 20 |
+
elif head_type == 'dpt' and output_mode == 'gs_params':
|
| 21 |
+
return create_dpt_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None)
|
| 22 |
+
elif head_type == 'dpt_gs' and output_mode == 'gs_params':
|
| 23 |
+
return create_gs_dpt_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None)
|
| 24 |
+
elif head_type == 'linear' and output_mode == 'ga_params':
|
| 25 |
+
return create_gs_linear_head(net, has_conf=False, out_nchan=out_nchan, postprocess_func=None)
|
| 26 |
+
else:
|
| 27 |
+
raise NotImplementedError(f"unexpected {head_type=} and {output_mode=}")
|
src/model/encoder/heads/dpt_block.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2022-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# DPT head for ViTs
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/isl-org/DPT
|
| 9 |
+
# https://github.com/EPFL-VILAB/MultiMAE/blob/main/multimae/output_adapters.py
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from einops import rearrange, repeat
|
| 15 |
+
from typing import Union, Tuple, Iterable, List, Optional, Dict
|
| 16 |
+
|
| 17 |
+
def pair(t):
|
| 18 |
+
return t if isinstance(t, tuple) else (t, t)
|
| 19 |
+
|
| 20 |
+
def make_scratch(in_shape, out_shape, groups=1, expand=False):
|
| 21 |
+
scratch = nn.Module()
|
| 22 |
+
|
| 23 |
+
out_shape1 = out_shape
|
| 24 |
+
out_shape2 = out_shape
|
| 25 |
+
out_shape3 = out_shape
|
| 26 |
+
out_shape4 = out_shape
|
| 27 |
+
if expand == True:
|
| 28 |
+
out_shape1 = out_shape
|
| 29 |
+
out_shape2 = out_shape * 2
|
| 30 |
+
out_shape3 = out_shape * 4
|
| 31 |
+
out_shape4 = out_shape * 8
|
| 32 |
+
|
| 33 |
+
scratch.layer1_rn = nn.Conv2d(
|
| 34 |
+
in_shape[0],
|
| 35 |
+
out_shape1,
|
| 36 |
+
kernel_size=3,
|
| 37 |
+
stride=1,
|
| 38 |
+
padding=1,
|
| 39 |
+
bias=False,
|
| 40 |
+
groups=groups,
|
| 41 |
+
)
|
| 42 |
+
scratch.layer2_rn = nn.Conv2d(
|
| 43 |
+
in_shape[1],
|
| 44 |
+
out_shape2,
|
| 45 |
+
kernel_size=3,
|
| 46 |
+
stride=1,
|
| 47 |
+
padding=1,
|
| 48 |
+
bias=False,
|
| 49 |
+
groups=groups,
|
| 50 |
+
)
|
| 51 |
+
scratch.layer3_rn = nn.Conv2d(
|
| 52 |
+
in_shape[2],
|
| 53 |
+
out_shape3,
|
| 54 |
+
kernel_size=3,
|
| 55 |
+
stride=1,
|
| 56 |
+
padding=1,
|
| 57 |
+
bias=False,
|
| 58 |
+
groups=groups,
|
| 59 |
+
)
|
| 60 |
+
scratch.layer4_rn = nn.Conv2d(
|
| 61 |
+
in_shape[3],
|
| 62 |
+
out_shape4,
|
| 63 |
+
kernel_size=3,
|
| 64 |
+
stride=1,
|
| 65 |
+
padding=1,
|
| 66 |
+
bias=False,
|
| 67 |
+
groups=groups,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
scratch.layer_rn = nn.ModuleList([
|
| 71 |
+
scratch.layer1_rn,
|
| 72 |
+
scratch.layer2_rn,
|
| 73 |
+
scratch.layer3_rn,
|
| 74 |
+
scratch.layer4_rn,
|
| 75 |
+
])
|
| 76 |
+
|
| 77 |
+
return scratch
|
| 78 |
+
|
| 79 |
+
class ResidualConvUnit_custom(nn.Module):
|
| 80 |
+
"""Residual convolution module."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, features, activation, bn):
|
| 83 |
+
"""Init.
|
| 84 |
+
Args:
|
| 85 |
+
features (int): number of features
|
| 86 |
+
"""
|
| 87 |
+
super().__init__()
|
| 88 |
+
|
| 89 |
+
self.bn = bn
|
| 90 |
+
|
| 91 |
+
self.groups = 1
|
| 92 |
+
|
| 93 |
+
self.conv1 = nn.Conv2d(
|
| 94 |
+
features,
|
| 95 |
+
features,
|
| 96 |
+
kernel_size=3,
|
| 97 |
+
stride=1,
|
| 98 |
+
padding=1,
|
| 99 |
+
bias=not self.bn,
|
| 100 |
+
groups=self.groups,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
self.conv2 = nn.Conv2d(
|
| 104 |
+
features,
|
| 105 |
+
features,
|
| 106 |
+
kernel_size=3,
|
| 107 |
+
stride=1,
|
| 108 |
+
padding=1,
|
| 109 |
+
bias=not self.bn,
|
| 110 |
+
groups=self.groups,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
if self.bn == True:
|
| 114 |
+
self.bn1 = nn.BatchNorm2d(features)
|
| 115 |
+
self.bn2 = nn.BatchNorm2d(features)
|
| 116 |
+
|
| 117 |
+
self.activation = activation
|
| 118 |
+
|
| 119 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 120 |
+
|
| 121 |
+
def forward(self, x):
|
| 122 |
+
"""Forward pass.
|
| 123 |
+
Args:
|
| 124 |
+
x (tensor): input
|
| 125 |
+
Returns:
|
| 126 |
+
tensor: output
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
out = self.activation(x)
|
| 130 |
+
out = self.conv1(out)
|
| 131 |
+
if self.bn == True:
|
| 132 |
+
out = self.bn1(out)
|
| 133 |
+
|
| 134 |
+
out = self.activation(out)
|
| 135 |
+
out = self.conv2(out)
|
| 136 |
+
if self.bn == True:
|
| 137 |
+
out = self.bn2(out)
|
| 138 |
+
|
| 139 |
+
if self.groups > 1:
|
| 140 |
+
out = self.conv_merge(out)
|
| 141 |
+
|
| 142 |
+
return self.skip_add.add(out, x)
|
| 143 |
+
|
| 144 |
+
class FeatureFusionBlock_custom(nn.Module):
|
| 145 |
+
"""Feature fusion block."""
|
| 146 |
+
|
| 147 |
+
def __init__(
|
| 148 |
+
self,
|
| 149 |
+
features,
|
| 150 |
+
activation,
|
| 151 |
+
deconv=False,
|
| 152 |
+
bn=False,
|
| 153 |
+
expand=False,
|
| 154 |
+
align_corners=True,
|
| 155 |
+
width_ratio=1,
|
| 156 |
+
):
|
| 157 |
+
"""Init.
|
| 158 |
+
Args:
|
| 159 |
+
features (int): number of features
|
| 160 |
+
"""
|
| 161 |
+
super(FeatureFusionBlock_custom, self).__init__()
|
| 162 |
+
self.width_ratio = width_ratio
|
| 163 |
+
|
| 164 |
+
self.deconv = deconv
|
| 165 |
+
self.align_corners = align_corners
|
| 166 |
+
|
| 167 |
+
self.groups = 1
|
| 168 |
+
|
| 169 |
+
self.expand = expand
|
| 170 |
+
out_features = features
|
| 171 |
+
if self.expand == True:
|
| 172 |
+
out_features = features // 2
|
| 173 |
+
|
| 174 |
+
self.out_conv = nn.Conv2d(
|
| 175 |
+
features,
|
| 176 |
+
out_features,
|
| 177 |
+
kernel_size=1,
|
| 178 |
+
stride=1,
|
| 179 |
+
padding=0,
|
| 180 |
+
bias=True,
|
| 181 |
+
groups=1,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn)
|
| 185 |
+
self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)
|
| 186 |
+
|
| 187 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 188 |
+
|
| 189 |
+
def forward(self, *xs):
|
| 190 |
+
"""Forward pass.
|
| 191 |
+
Returns:
|
| 192 |
+
tensor: output
|
| 193 |
+
"""
|
| 194 |
+
output = xs[0]
|
| 195 |
+
|
| 196 |
+
if len(xs) == 2:
|
| 197 |
+
res = self.resConfUnit1(xs[1])
|
| 198 |
+
if self.width_ratio != 1:
|
| 199 |
+
res = F.interpolate(res, size=(output.shape[2], output.shape[3]), mode='bilinear')
|
| 200 |
+
|
| 201 |
+
output = self.skip_add.add(output, res)
|
| 202 |
+
# output += res
|
| 203 |
+
|
| 204 |
+
output = self.resConfUnit2(output)
|
| 205 |
+
|
| 206 |
+
if self.width_ratio != 1:
|
| 207 |
+
# and output.shape[3] < self.width_ratio * output.shape[2]
|
| 208 |
+
#size=(image.shape[])
|
| 209 |
+
if (output.shape[3] / output.shape[2]) < (2 / 3) * self.width_ratio:
|
| 210 |
+
shape = 3 * output.shape[3]
|
| 211 |
+
else:
|
| 212 |
+
shape = int(self.width_ratio * 2 * output.shape[2])
|
| 213 |
+
output = F.interpolate(output, size=(2* output.shape[2], shape), mode='bilinear')
|
| 214 |
+
else:
|
| 215 |
+
output = nn.functional.interpolate(output, scale_factor=2,
|
| 216 |
+
mode="bilinear", align_corners=self.align_corners)
|
| 217 |
+
output = self.out_conv(output)
|
| 218 |
+
return output
|
| 219 |
+
|
| 220 |
+
def make_fusion_block(features, use_bn, width_ratio=1, expand=False):
|
| 221 |
+
return FeatureFusionBlock_custom(
|
| 222 |
+
features,
|
| 223 |
+
nn.ReLU(False),
|
| 224 |
+
deconv=False,
|
| 225 |
+
bn=use_bn,
|
| 226 |
+
expand=expand,
|
| 227 |
+
align_corners=True,
|
| 228 |
+
width_ratio=width_ratio,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
class Interpolate(nn.Module):
|
| 232 |
+
"""Interpolation module."""
|
| 233 |
+
|
| 234 |
+
def __init__(self, scale_factor, mode, align_corners=False):
|
| 235 |
+
"""Init.
|
| 236 |
+
Args:
|
| 237 |
+
scale_factor (float): scaling
|
| 238 |
+
mode (str): interpolation mode
|
| 239 |
+
"""
|
| 240 |
+
super(Interpolate, self).__init__()
|
| 241 |
+
|
| 242 |
+
self.interp = nn.functional.interpolate
|
| 243 |
+
self.scale_factor = scale_factor
|
| 244 |
+
self.mode = mode
|
| 245 |
+
self.align_corners = align_corners
|
| 246 |
+
|
| 247 |
+
def forward(self, x):
|
| 248 |
+
"""Forward pass.
|
| 249 |
+
Args:
|
| 250 |
+
x (tensor): input
|
| 251 |
+
Returns:
|
| 252 |
+
tensor: interpolated data
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
x = self.interp(
|
| 256 |
+
x,
|
| 257 |
+
scale_factor=self.scale_factor,
|
| 258 |
+
mode=self.mode,
|
| 259 |
+
align_corners=self.align_corners,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
return x
|
| 263 |
+
|
| 264 |
+
class DPTOutputAdapter(nn.Module):
|
| 265 |
+
"""DPT output adapter.
|
| 266 |
+
|
| 267 |
+
:param num_cahnnels: Number of output channels
|
| 268 |
+
:param stride_level: tride level compared to the full-sized image.
|
| 269 |
+
E.g. 4 for 1/4th the size of the image.
|
| 270 |
+
:param patch_size_full: Int or tuple of the patch size over the full image size.
|
| 271 |
+
Patch size for smaller inputs will be computed accordingly.
|
| 272 |
+
:param hooks: Index of intermediate layers
|
| 273 |
+
:param layer_dims: Dimension of intermediate layers
|
| 274 |
+
:param feature_dim: Feature dimension
|
| 275 |
+
:param last_dim: out_channels/in_channels for the last two Conv2d when head_type == regression
|
| 276 |
+
:param use_bn: If set to True, activates batch norm
|
| 277 |
+
:param dim_tokens_enc: Dimension of tokens coming from encoder
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(self,
|
| 281 |
+
num_channels: int = 1,
|
| 282 |
+
stride_level: int = 1,
|
| 283 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
| 284 |
+
main_tasks: Iterable[str] = ('rgb',),
|
| 285 |
+
hooks: List[int] = [2, 5, 8, 11],
|
| 286 |
+
layer_dims: List[int] = [96, 192, 384, 768],
|
| 287 |
+
feature_dim: int = 256,
|
| 288 |
+
last_dim: int = 32,
|
| 289 |
+
use_bn: bool = False,
|
| 290 |
+
dim_tokens_enc: Optional[int] = None,
|
| 291 |
+
head_type: str = 'regression',
|
| 292 |
+
output_width_ratio=1,
|
| 293 |
+
**kwargs):
|
| 294 |
+
super().__init__()
|
| 295 |
+
self.num_channels = num_channels
|
| 296 |
+
self.stride_level = stride_level
|
| 297 |
+
self.patch_size = pair(patch_size)
|
| 298 |
+
self.main_tasks = main_tasks
|
| 299 |
+
self.hooks = hooks
|
| 300 |
+
self.layer_dims = layer_dims
|
| 301 |
+
self.feature_dim = feature_dim
|
| 302 |
+
self.dim_tokens_enc = dim_tokens_enc * len(self.main_tasks) if dim_tokens_enc is not None else None
|
| 303 |
+
self.head_type = head_type
|
| 304 |
+
|
| 305 |
+
# Actual patch height and width, taking into account stride of input
|
| 306 |
+
self.P_H = max(1, self.patch_size[0] // stride_level)
|
| 307 |
+
self.P_W = max(1, self.patch_size[1] // stride_level)
|
| 308 |
+
|
| 309 |
+
self.scratch = make_scratch(layer_dims, feature_dim, groups=1, expand=False)
|
| 310 |
+
|
| 311 |
+
self.scratch.refinenet1 = make_fusion_block(feature_dim, use_bn, output_width_ratio)
|
| 312 |
+
self.scratch.refinenet2 = make_fusion_block(feature_dim, use_bn, output_width_ratio)
|
| 313 |
+
self.scratch.refinenet3 = make_fusion_block(feature_dim, use_bn, output_width_ratio)
|
| 314 |
+
self.scratch.refinenet4 = make_fusion_block(feature_dim, use_bn, output_width_ratio)
|
| 315 |
+
|
| 316 |
+
if self.head_type == 'regression':
|
| 317 |
+
# The "DPTDepthModel" head
|
| 318 |
+
self.head = nn.Sequential(
|
| 319 |
+
nn.Conv2d(feature_dim, feature_dim // 2, kernel_size=3, stride=1, padding=1),
|
| 320 |
+
Interpolate(scale_factor=2, mode="bilinear", align_corners=True),
|
| 321 |
+
nn.Conv2d(feature_dim // 2, last_dim, kernel_size=3, stride=1, padding=1),
|
| 322 |
+
nn.ReLU(True),
|
| 323 |
+
nn.Conv2d(last_dim, self.num_channels, kernel_size=1, stride=1, padding=0)
|
| 324 |
+
)
|
| 325 |
+
elif self.head_type == 'semseg':
|
| 326 |
+
# The "DPTSegmentationModel" head
|
| 327 |
+
self.head = nn.Sequential(
|
| 328 |
+
nn.Conv2d(feature_dim, feature_dim, kernel_size=3, padding=1, bias=False),
|
| 329 |
+
nn.BatchNorm2d(feature_dim) if use_bn else nn.Identity(),
|
| 330 |
+
nn.ReLU(True),
|
| 331 |
+
nn.Dropout(0.1, False),
|
| 332 |
+
nn.Conv2d(feature_dim, self.num_channels, kernel_size=1),
|
| 333 |
+
Interpolate(scale_factor=2, mode="bilinear", align_corners=True),
|
| 334 |
+
)
|
| 335 |
+
elif self.head_type == 'gs_params':
|
| 336 |
+
# The "DPTSegmentationModel" head
|
| 337 |
+
self.head = nn.Sequential(
|
| 338 |
+
nn.Conv2d(feature_dim, feature_dim, kernel_size=3, padding=1, bias=False),
|
| 339 |
+
nn.BatchNorm2d(feature_dim) if use_bn else nn.Identity(),
|
| 340 |
+
nn.ReLU(True),
|
| 341 |
+
nn.Dropout(0.1, False),
|
| 342 |
+
nn.Conv2d(feature_dim, self.num_channels, kernel_size=1),
|
| 343 |
+
)
|
| 344 |
+
else:
|
| 345 |
+
raise ValueError('DPT head_type must be "regression" or "semseg".')
|
| 346 |
+
|
| 347 |
+
if self.dim_tokens_enc is not None:
|
| 348 |
+
self.init(dim_tokens_enc=dim_tokens_enc)
|
| 349 |
+
|
| 350 |
+
def init(self, dim_tokens_enc=768):
|
| 351 |
+
"""
|
| 352 |
+
Initialize parts of decoder that are dependent on dimension of encoder tokens.
|
| 353 |
+
Should be called when setting up MultiMAE.
|
| 354 |
+
|
| 355 |
+
:param dim_tokens_enc: Dimension of tokens coming from encoder
|
| 356 |
+
"""
|
| 357 |
+
#print(dim_tokens_enc)
|
| 358 |
+
|
| 359 |
+
# Set up activation postprocessing layers
|
| 360 |
+
if isinstance(dim_tokens_enc, int):
|
| 361 |
+
dim_tokens_enc = 4 * [dim_tokens_enc]
|
| 362 |
+
|
| 363 |
+
self.dim_tokens_enc = [dt * len(self.main_tasks) for dt in dim_tokens_enc]
|
| 364 |
+
|
| 365 |
+
self.act_1_postprocess = nn.Sequential(
|
| 366 |
+
nn.Conv2d(
|
| 367 |
+
in_channels=self.dim_tokens_enc[0],
|
| 368 |
+
out_channels=self.layer_dims[0],
|
| 369 |
+
kernel_size=1, stride=1, padding=0,
|
| 370 |
+
),
|
| 371 |
+
nn.ConvTranspose2d(
|
| 372 |
+
in_channels=self.layer_dims[0],
|
| 373 |
+
out_channels=self.layer_dims[0],
|
| 374 |
+
kernel_size=4, stride=4, padding=0,
|
| 375 |
+
bias=True, dilation=1, groups=1,
|
| 376 |
+
)
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
self.act_2_postprocess = nn.Sequential(
|
| 380 |
+
nn.Conv2d(
|
| 381 |
+
in_channels=self.dim_tokens_enc[1],
|
| 382 |
+
out_channels=self.layer_dims[1],
|
| 383 |
+
kernel_size=1, stride=1, padding=0,
|
| 384 |
+
),
|
| 385 |
+
nn.ConvTranspose2d(
|
| 386 |
+
in_channels=self.layer_dims[1],
|
| 387 |
+
out_channels=self.layer_dims[1],
|
| 388 |
+
kernel_size=2, stride=2, padding=0,
|
| 389 |
+
bias=True, dilation=1, groups=1,
|
| 390 |
+
)
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
self.act_3_postprocess = nn.Sequential(
|
| 394 |
+
nn.Conv2d(
|
| 395 |
+
in_channels=self.dim_tokens_enc[2],
|
| 396 |
+
out_channels=self.layer_dims[2],
|
| 397 |
+
kernel_size=1, stride=1, padding=0,
|
| 398 |
+
)
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
self.act_4_postprocess = nn.Sequential(
|
| 402 |
+
nn.Conv2d(
|
| 403 |
+
in_channels=self.dim_tokens_enc[3],
|
| 404 |
+
out_channels=self.layer_dims[3],
|
| 405 |
+
kernel_size=1, stride=1, padding=0,
|
| 406 |
+
),
|
| 407 |
+
nn.Conv2d(
|
| 408 |
+
in_channels=self.layer_dims[3],
|
| 409 |
+
out_channels=self.layer_dims[3],
|
| 410 |
+
kernel_size=3, stride=2, padding=1,
|
| 411 |
+
)
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
self.act_postprocess = nn.ModuleList([
|
| 415 |
+
self.act_1_postprocess,
|
| 416 |
+
self.act_2_postprocess,
|
| 417 |
+
self.act_3_postprocess,
|
| 418 |
+
self.act_4_postprocess
|
| 419 |
+
])
|
| 420 |
+
|
| 421 |
+
def adapt_tokens(self, encoder_tokens):
|
| 422 |
+
# Adapt tokens
|
| 423 |
+
x = []
|
| 424 |
+
x.append(encoder_tokens[:, :])
|
| 425 |
+
x = torch.cat(x, dim=-1)
|
| 426 |
+
return x
|
| 427 |
+
|
| 428 |
+
def forward(self, encoder_tokens: List[torch.Tensor], image_size):
|
| 429 |
+
#input_info: Dict):
|
| 430 |
+
assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 431 |
+
H, W = image_size
|
| 432 |
+
|
| 433 |
+
# Number of patches in height and width
|
| 434 |
+
N_H = H // (self.stride_level * self.P_H)
|
| 435 |
+
N_W = W // (self.stride_level * self.P_W)
|
| 436 |
+
|
| 437 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 438 |
+
layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 439 |
+
|
| 440 |
+
# Extract only task-relevant tokens and ignore global tokens.
|
| 441 |
+
layers = [self.adapt_tokens(l) for l in layers]
|
| 442 |
+
|
| 443 |
+
# Reshape tokens to spatial representation
|
| 444 |
+
layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 445 |
+
|
| 446 |
+
layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 447 |
+
# Project layers to chosen feature dim
|
| 448 |
+
layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 449 |
+
|
| 450 |
+
# Fuse layers using refinement stages
|
| 451 |
+
path_4 = self.scratch.refinenet4(layers[3])
|
| 452 |
+
path_3 = self.scratch.refinenet3(path_4, layers[2])
|
| 453 |
+
path_2 = self.scratch.refinenet2(path_3, layers[1])
|
| 454 |
+
path_1 = self.scratch.refinenet1(path_2, layers[0])
|
| 455 |
+
|
| 456 |
+
# Output head
|
| 457 |
+
out = self.head(path_1)
|
| 458 |
+
|
| 459 |
+
return out
|
src/model/encoder/heads/dpt_gs_head.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# dpt head implementation for DUST3R
|
| 6 |
+
# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ;
|
| 7 |
+
# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True
|
| 8 |
+
# the forward function also takes as input a dictionnary img_info with key "height" and "width"
|
| 9 |
+
# for PixelwiseTask, the output will be of dimension B x num_channels x H x W
|
| 10 |
+
# --------------------------------------------------------
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from typing import List
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
# import dust3r.utils.path_to_croco
|
| 17 |
+
from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block
|
| 18 |
+
from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights
|
| 19 |
+
from .postprocess import postprocess
|
| 20 |
+
|
| 21 |
+
# class DPTOutputAdapter_fix(DPTOutputAdapter):
|
| 22 |
+
# """
|
| 23 |
+
# Adapt croco's DPTOutputAdapter implementation for dust3r:
|
| 24 |
+
# remove duplicated weigths, and fix forward for dust3r
|
| 25 |
+
# """
|
| 26 |
+
#
|
| 27 |
+
# def init(self, dim_tokens_enc=768):
|
| 28 |
+
# super().init(dim_tokens_enc)
|
| 29 |
+
# # these are duplicated weights
|
| 30 |
+
# del self.act_1_postprocess
|
| 31 |
+
# del self.act_2_postprocess
|
| 32 |
+
# del self.act_3_postprocess
|
| 33 |
+
# del self.act_4_postprocess
|
| 34 |
+
#
|
| 35 |
+
# self.scratch.refinenet1 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 36 |
+
# self.scratch.refinenet2 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 37 |
+
# self.scratch.refinenet3 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 38 |
+
# # self.scratch.refinenet4 = make_fusion_block(256 * 2, False, 1)
|
| 39 |
+
#
|
| 40 |
+
# self.depth_encoder = UnetExtractor(in_channel=3)
|
| 41 |
+
# self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True)
|
| 42 |
+
# self.out_conv = nn.Conv2d(256+3+4, 256, kernel_size=3, padding=1)
|
| 43 |
+
# self.out_relu = nn.ReLU(inplace=True)
|
| 44 |
+
#
|
| 45 |
+
# self.input_merger = nn.Sequential(
|
| 46 |
+
# # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1),
|
| 47 |
+
# nn.Conv2d(256+3+3, 256, kernel_size=3, padding=1),
|
| 48 |
+
# nn.ReLU(),
|
| 49 |
+
# )
|
| 50 |
+
#
|
| 51 |
+
# def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None):
|
| 52 |
+
# assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 53 |
+
# # H, W = input_info['image_size']
|
| 54 |
+
# image_size = self.image_size if image_size is None else image_size
|
| 55 |
+
# H, W = image_size
|
| 56 |
+
# # Number of patches in height and width
|
| 57 |
+
# N_H = H // (self.stride_level * self.P_H)
|
| 58 |
+
# N_W = W // (self.stride_level * self.P_W)
|
| 59 |
+
#
|
| 60 |
+
# # Hook decoder onto 4 layers from specified ViT layers
|
| 61 |
+
# layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 62 |
+
#
|
| 63 |
+
# # Extract only task-relevant tokens and ignore global tokens.
|
| 64 |
+
# layers = [self.adapt_tokens(l) for l in layers]
|
| 65 |
+
#
|
| 66 |
+
# # Reshape tokens to spatial representation
|
| 67 |
+
# layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 68 |
+
#
|
| 69 |
+
# layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 70 |
+
# # Project layers to chosen feature dim
|
| 71 |
+
# layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 72 |
+
#
|
| 73 |
+
# # get depth features
|
| 74 |
+
# depth_features = self.depth_encoder(depths)
|
| 75 |
+
# depth_feature1, depth_feature2, depth_feature3 = depth_features
|
| 76 |
+
#
|
| 77 |
+
# # Fuse layers using refinement stages
|
| 78 |
+
# path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]]
|
| 79 |
+
# path_3 = self.scratch.refinenet3(torch.cat([path_4, depth_feature3], dim=1), torch.cat([layers[2], depth_feature3], dim=1))
|
| 80 |
+
# path_2 = self.scratch.refinenet2(torch.cat([path_3, depth_feature2], dim=1), torch.cat([layers[1], depth_feature2], dim=1))
|
| 81 |
+
# path_1 = self.scratch.refinenet1(torch.cat([path_2, depth_feature1], dim=1), torch.cat([layers[0], depth_feature1], dim=1))
|
| 82 |
+
# # path_3 = self.scratch.refinenet3(path_4, layers[2], depth_feature3)
|
| 83 |
+
# # path_2 = self.scratch.refinenet2(path_3, layers[1], depth_feature2)
|
| 84 |
+
# # path_1 = self.scratch.refinenet1(path_2, layers[0], depth_feature1)
|
| 85 |
+
#
|
| 86 |
+
# path_1 = self.feat_up(path_1)
|
| 87 |
+
# path_1 = torch.cat([path_1, imgs, depths], dim=1)
|
| 88 |
+
# if conf is not None:
|
| 89 |
+
# path_1 = torch.cat([path_1, conf], dim=1)
|
| 90 |
+
# path_1 = self.input_merger(path_1)
|
| 91 |
+
#
|
| 92 |
+
# # Output head
|
| 93 |
+
# out = self.head(path_1)
|
| 94 |
+
#
|
| 95 |
+
# return out
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class DPTOutputAdapter_fix(DPTOutputAdapter):
|
| 99 |
+
"""
|
| 100 |
+
Adapt croco's DPTOutputAdapter implementation for dust3r:
|
| 101 |
+
remove duplicated weigths, and fix forward for dust3r
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def init(self, dim_tokens_enc=768):
|
| 105 |
+
super().init(dim_tokens_enc)
|
| 106 |
+
# these are duplicated weights
|
| 107 |
+
del self.act_1_postprocess
|
| 108 |
+
del self.act_2_postprocess
|
| 109 |
+
del self.act_3_postprocess
|
| 110 |
+
del self.act_4_postprocess
|
| 111 |
+
|
| 112 |
+
self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True)
|
| 113 |
+
self.input_merger = nn.Sequential(
|
| 114 |
+
# nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1),
|
| 115 |
+
# nn.Conv2d(3+6, 256, 7, 1, 3),
|
| 116 |
+
nn.Conv2d(3, 256, 7, 1, 3),
|
| 117 |
+
nn.ReLU(),
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None):
|
| 121 |
+
assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 122 |
+
# H, W = input_info['image_size']
|
| 123 |
+
image_size = self.image_size if image_size is None else image_size
|
| 124 |
+
H, W = image_size
|
| 125 |
+
# Number of patches in height and width
|
| 126 |
+
N_H = H // (self.stride_level * self.P_H)
|
| 127 |
+
N_W = W // (self.stride_level * self.P_W)
|
| 128 |
+
|
| 129 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 130 |
+
layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 131 |
+
|
| 132 |
+
# Extract only task-relevant tokens and ignore global tokens.
|
| 133 |
+
layers = [self.adapt_tokens(l) for l in layers]
|
| 134 |
+
|
| 135 |
+
# Reshape tokens to spatial representation
|
| 136 |
+
layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 137 |
+
|
| 138 |
+
layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 139 |
+
# Project layers to chosen feature dim
|
| 140 |
+
layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 141 |
+
|
| 142 |
+
# Fuse layers using refinement stages
|
| 143 |
+
path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]]
|
| 144 |
+
path_3 = self.scratch.refinenet3(path_4, layers[2])
|
| 145 |
+
path_2 = self.scratch.refinenet2(path_3, layers[1])
|
| 146 |
+
path_1 = self.scratch.refinenet1(path_2, layers[0])
|
| 147 |
+
|
| 148 |
+
direct_img_feat = self.input_merger(imgs)
|
| 149 |
+
# imgs = imgs.permute(0, 2, 3, 1).flatten(1, 2).contiguous()
|
| 150 |
+
# # Pachify
|
| 151 |
+
# patch_size = self.patch_size
|
| 152 |
+
# hh = H // patch_size[0]
|
| 153 |
+
# ww = W // patch_size[1]
|
| 154 |
+
# 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])
|
| 155 |
+
|
| 156 |
+
# actually, we just do interpolate here
|
| 157 |
+
# path_1 = self.feat_up(path_1)
|
| 158 |
+
path_1 = F.interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True)
|
| 159 |
+
path_1 = path_1 + direct_img_feat
|
| 160 |
+
|
| 161 |
+
# path_1 = torch.cat([path_1, imgs], dim=1)
|
| 162 |
+
|
| 163 |
+
# Output head
|
| 164 |
+
out = self.head(path_1)
|
| 165 |
+
|
| 166 |
+
return out, [path_4, path_3, path_2]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class PixelwiseTaskWithDPT(nn.Module):
|
| 170 |
+
""" DPT module for dust3r, can return 3D points + confidence for all pixels"""
|
| 171 |
+
|
| 172 |
+
def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None,
|
| 173 |
+
output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs):
|
| 174 |
+
super(PixelwiseTaskWithDPT, self).__init__()
|
| 175 |
+
self.return_all_layers = True # backbone needs to return all layers
|
| 176 |
+
self.postprocess = postprocess
|
| 177 |
+
self.depth_mode = depth_mode
|
| 178 |
+
self.conf_mode = conf_mode
|
| 179 |
+
|
| 180 |
+
assert n_cls_token == 0, "Not implemented"
|
| 181 |
+
dpt_args = dict(output_width_ratio=output_width_ratio,
|
| 182 |
+
num_channels=num_channels,
|
| 183 |
+
**kwargs)
|
| 184 |
+
if hooks_idx is not None:
|
| 185 |
+
dpt_args.update(hooks=hooks_idx)
|
| 186 |
+
self.dpt = DPTOutputAdapter_fix(**dpt_args)
|
| 187 |
+
dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens}
|
| 188 |
+
self.dpt.init(**dpt_init_args)
|
| 189 |
+
|
| 190 |
+
def forward(self, x, depths, imgs, img_info, conf=None):
|
| 191 |
+
out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf)
|
| 192 |
+
if self.postprocess:
|
| 193 |
+
out = self.postprocess(out, self.depth_mode, self.conf_mode)
|
| 194 |
+
return out, interm_feats
|
| 195 |
+
|
| 196 |
+
class AttnBasedAppearanceHead(nn.Module):
|
| 197 |
+
"""
|
| 198 |
+
Attention head Appearence Reconstruction
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def __init__(self, num_channels, patch_size, feature_dim, last_dim, hooks_idx, dim_tokens, postprocess, depth_mode, conf_mode, head_type='gs_params'):
|
| 202 |
+
super().__init__()
|
| 203 |
+
|
| 204 |
+
self.num_channels = num_channels
|
| 205 |
+
self.patch_size = patch_size
|
| 206 |
+
|
| 207 |
+
self.hooks = hooks_idx
|
| 208 |
+
|
| 209 |
+
assert len(set(dim_tokens)) == 1
|
| 210 |
+
|
| 211 |
+
self.tokenizer = nn.Linear(3 * self.patch_size[0] ** 2, dim_tokens[0], bias=False)
|
| 212 |
+
|
| 213 |
+
self.attn_processor = AppearanceTransformer(num_layers=4, attn_dim=dim_tokens[0] * 2, head_dim=feature_dim)
|
| 214 |
+
|
| 215 |
+
self.token_decoder = nn.Sequential(
|
| 216 |
+
nn.LayerNorm(dim_tokens[0] * 2, bias=False),
|
| 217 |
+
nn.Linear(
|
| 218 |
+
dim_tokens[0] * 2, self.num_channels * (self.patch_size[0] ** 2),
|
| 219 |
+
bias=False,
|
| 220 |
+
)
|
| 221 |
+
)
|
| 222 |
+
self.token_decoder.apply(_init_weights)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def img_pts_tokenizer(self, imgs, pts3d):
|
| 226 |
+
B, V, _, H, W = imgs.shape
|
| 227 |
+
pts3d = pts3d.flatten(2, 3).contiguous()
|
| 228 |
+
imgs = imgs.permute(0, 1, 3, 4, 2).flatten(2, 3).contiguous()
|
| 229 |
+
mean = pts3d.mean(dim=-2, keepdim=True) # (B, V, 1, 3)
|
| 230 |
+
z_median = torch.median(torch.norm(pts3d, dim=-1, keepdim=True), dim=2, keepdim=True)[0] # (B, V, 1, 1)
|
| 231 |
+
pts3d_normed = (pts3d - mean) / (z_median + 1e-8) # (B, V, N, 3)
|
| 232 |
+
|
| 233 |
+
input = imgs #torch.cat([pts3d_normed, imgs], dim=-1) # (B, V, H*W, 9)
|
| 234 |
+
# Pachify
|
| 235 |
+
patch_size = self.patch_size
|
| 236 |
+
hh = H // patch_size[0]
|
| 237 |
+
ww = W // patch_size[1]
|
| 238 |
+
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])
|
| 239 |
+
# Tokenize the input images
|
| 240 |
+
input_tokens = self.tokenizer(input)
|
| 241 |
+
return input_tokens
|
| 242 |
+
|
| 243 |
+
def forward(self, x, depths, imgs, img_info, conf=None):
|
| 244 |
+
B, V, H, W = img_info
|
| 245 |
+
input_tokens = rearrange(self.img_pts_tokenizer(imgs, depths), "(b v) l d -> b (v l) d", b=B, v=V)
|
| 246 |
+
|
| 247 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 248 |
+
layer_tokens = [rearrange(x[hook].detach(), "(b v) l d -> b (v l) d", b=B, v=V) for hook in self.hooks]
|
| 249 |
+
|
| 250 |
+
tokens = self.attn_processor(torch.cat([input_tokens, layer_tokens[-1]], dim=-1))
|
| 251 |
+
|
| 252 |
+
gaussian_params = self.token_decoder(tokens)
|
| 253 |
+
|
| 254 |
+
patch_size = self.patch_size
|
| 255 |
+
hh = H // patch_size[0]
|
| 256 |
+
ww = W // patch_size[1]
|
| 257 |
+
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])
|
| 258 |
+
return gaussians.view(B, V, H*W, -1)
|
| 259 |
+
|
| 260 |
+
def create_gs_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess):
|
| 261 |
+
"""
|
| 262 |
+
return PixelwiseTaskWithDPT for given net params
|
| 263 |
+
"""
|
| 264 |
+
assert net.dec_depth > 9
|
| 265 |
+
l2 = net.dec_depth
|
| 266 |
+
feature_dim = net.feature_dim
|
| 267 |
+
last_dim = feature_dim//2
|
| 268 |
+
ed = net.enc_embed_dim
|
| 269 |
+
dd = net.dec_embed_dim
|
| 270 |
+
try:
|
| 271 |
+
patch_size = net.patch_size
|
| 272 |
+
except:
|
| 273 |
+
patch_size = (16, 16)
|
| 274 |
+
|
| 275 |
+
return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf,
|
| 276 |
+
patch_size=patch_size,
|
| 277 |
+
feature_dim=feature_dim,
|
| 278 |
+
last_dim=last_dim,
|
| 279 |
+
hooks_idx=[0, l2*2//4, l2*3//4, l2],
|
| 280 |
+
dim_tokens=[ed, dd, dd, dd],
|
| 281 |
+
postprocess=postprocess_func,
|
| 282 |
+
depth_mode=net.depth_mode,
|
| 283 |
+
conf_mode=net.conf_mode,
|
| 284 |
+
head_type='gs_params')
|
src/model/encoder/heads/dpt_head.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# dpt head implementation for DUST3R
|
| 6 |
+
# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ;
|
| 7 |
+
# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True
|
| 8 |
+
# the forward function also takes as input a dictionnary img_info with key "height" and "width"
|
| 9 |
+
# for PixelwiseTask, the output will be of dimension B x num_channels x H x W
|
| 10 |
+
# --------------------------------------------------------
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from typing import List
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
# import dust3r.utils.path_to_croco
|
| 17 |
+
from .dpt_block import DPTOutputAdapter
|
| 18 |
+
from .postprocess import postprocess
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DPTOutputAdapter_fix(DPTOutputAdapter):
|
| 22 |
+
"""
|
| 23 |
+
Adapt croco's DPTOutputAdapter implementation for dust3r:
|
| 24 |
+
remove duplicated weigths, and fix forward for dust3r
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def init(self, dim_tokens_enc=768):
|
| 28 |
+
super().init(dim_tokens_enc)
|
| 29 |
+
# these are duplicated weights
|
| 30 |
+
del self.act_1_postprocess
|
| 31 |
+
del self.act_2_postprocess
|
| 32 |
+
del self.act_3_postprocess
|
| 33 |
+
del self.act_4_postprocess
|
| 34 |
+
|
| 35 |
+
def forward(self, encoder_tokens: List[torch.Tensor], image_size=None, ray_embedding=None):
|
| 36 |
+
assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 37 |
+
# H, W = input_info['image_size']
|
| 38 |
+
image_size = self.image_size if image_size is None else image_size
|
| 39 |
+
H, W = image_size
|
| 40 |
+
# Number of patches in height and width
|
| 41 |
+
N_H = H // (self.stride_level * self.P_H)
|
| 42 |
+
N_W = W // (self.stride_level * self.P_W)
|
| 43 |
+
|
| 44 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 45 |
+
layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 46 |
+
|
| 47 |
+
# Extract only task-relevant tokens and ignore global tokens.
|
| 48 |
+
layers = [self.adapt_tokens(l) for l in layers]
|
| 49 |
+
|
| 50 |
+
# Reshape tokens to spatial representation
|
| 51 |
+
layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 52 |
+
|
| 53 |
+
layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 54 |
+
# Project layers to chosen feature dim
|
| 55 |
+
layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 56 |
+
|
| 57 |
+
# Fuse layers using refinement stages
|
| 58 |
+
path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]]
|
| 59 |
+
path_3 = self.scratch.refinenet3(path_4, layers[2])
|
| 60 |
+
path_2 = self.scratch.refinenet2(path_3, layers[1])
|
| 61 |
+
path_1 = self.scratch.refinenet1(path_2, layers[0])
|
| 62 |
+
|
| 63 |
+
# if ray_embedding is not None:
|
| 64 |
+
# ray_embedding = F.interpolate(ray_embedding, size=(path_1.shape[2], path_1.shape[3]), mode='bilinear')
|
| 65 |
+
# path_1 = torch.cat([path_1, ray_embedding], dim=1)
|
| 66 |
+
|
| 67 |
+
# Output head
|
| 68 |
+
out = self.head(path_1)
|
| 69 |
+
|
| 70 |
+
return out
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PixelwiseTaskWithDPT(nn.Module):
|
| 74 |
+
""" DPT module for dust3r, can return 3D points + confidence for all pixels"""
|
| 75 |
+
|
| 76 |
+
def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None,
|
| 77 |
+
output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs):
|
| 78 |
+
super(PixelwiseTaskWithDPT, self).__init__()
|
| 79 |
+
self.return_all_layers = True # backbone needs to return all layers
|
| 80 |
+
self.postprocess = postprocess
|
| 81 |
+
self.depth_mode = depth_mode
|
| 82 |
+
self.conf_mode = conf_mode
|
| 83 |
+
|
| 84 |
+
assert n_cls_token == 0, "Not implemented"
|
| 85 |
+
dpt_args = dict(output_width_ratio=output_width_ratio,
|
| 86 |
+
num_channels=num_channels,
|
| 87 |
+
**kwargs)
|
| 88 |
+
if hooks_idx is not None:
|
| 89 |
+
dpt_args.update(hooks=hooks_idx)
|
| 90 |
+
self.dpt = DPTOutputAdapter_fix(**dpt_args)
|
| 91 |
+
dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens}
|
| 92 |
+
self.dpt.init(**dpt_init_args)
|
| 93 |
+
|
| 94 |
+
def forward(self, x, img_info, ray_embedding=None):
|
| 95 |
+
out = self.dpt(x, image_size=(img_info[0], img_info[1]), ray_embedding=ray_embedding)
|
| 96 |
+
if self.postprocess:
|
| 97 |
+
out = self.postprocess(out, self.depth_mode, self.conf_mode)
|
| 98 |
+
return out
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def create_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess):
|
| 102 |
+
"""
|
| 103 |
+
return PixelwiseTaskWithDPT for given net params
|
| 104 |
+
"""
|
| 105 |
+
assert net.dec_depth > 9
|
| 106 |
+
l2 = net.dec_depth
|
| 107 |
+
feature_dim = 256
|
| 108 |
+
last_dim = feature_dim//2
|
| 109 |
+
ed = net.enc_embed_dim
|
| 110 |
+
dd = net.dec_embed_dim
|
| 111 |
+
return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf,
|
| 112 |
+
feature_dim=feature_dim,
|
| 113 |
+
last_dim=last_dim,
|
| 114 |
+
hooks_idx=[0, l2*2//4, l2*3//4, l2],
|
| 115 |
+
dim_tokens=[ed, dd, dd, dd],
|
| 116 |
+
postprocess=postprocess_func,
|
| 117 |
+
depth_mode=net.depth_mode,
|
| 118 |
+
conf_mode=net.conf_mode,
|
| 119 |
+
head_type='regression')
|
src/model/encoder/heads/head_modules.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from einops import rearrange
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
import numbers
|
| 6 |
+
|
| 7 |
+
class RMSNorm(nn.Module):
|
| 8 |
+
def __init__(self, dim, eps=1e-6):
|
| 9 |
+
super(RMSNorm, self).__init__()
|
| 10 |
+
self.eps = eps
|
| 11 |
+
self.scale = nn.Parameter(torch.ones(dim))
|
| 12 |
+
|
| 13 |
+
def forward(self, x):
|
| 14 |
+
rms = torch.sqrt(torch.mean(x**2, dim=-1, keepdim=True) + self.eps)
|
| 15 |
+
return self.scale * x / rms
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ResidualBlock(nn.Module):
|
| 19 |
+
def __init__(self, in_planes, planes, norm_fn='group', stride=1):
|
| 20 |
+
super(ResidualBlock, self).__init__()
|
| 21 |
+
|
| 22 |
+
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride)
|
| 23 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)
|
| 24 |
+
self.relu = nn.ReLU(inplace=True)
|
| 25 |
+
|
| 26 |
+
num_groups = planes // 8
|
| 27 |
+
|
| 28 |
+
if norm_fn == 'group':
|
| 29 |
+
self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
|
| 30 |
+
self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
|
| 31 |
+
if not (stride == 1 and in_planes == planes):
|
| 32 |
+
self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
|
| 33 |
+
|
| 34 |
+
elif norm_fn == 'batch':
|
| 35 |
+
self.norm1 = nn.BatchNorm2d(planes)
|
| 36 |
+
self.norm2 = nn.BatchNorm2d(planes)
|
| 37 |
+
if not (stride == 1 and in_planes == planes):
|
| 38 |
+
self.norm3 = nn.BatchNorm2d(planes)
|
| 39 |
+
|
| 40 |
+
elif norm_fn == 'instance':
|
| 41 |
+
self.norm1 = nn.InstanceNorm2d(planes)
|
| 42 |
+
self.norm2 = nn.InstanceNorm2d(planes)
|
| 43 |
+
if not (stride == 1 and in_planes == planes):
|
| 44 |
+
self.norm3 = nn.InstanceNorm2d(planes)
|
| 45 |
+
|
| 46 |
+
elif norm_fn == 'none':
|
| 47 |
+
self.norm1 = nn.Sequential()
|
| 48 |
+
self.norm2 = nn.Sequential()
|
| 49 |
+
if not (stride == 1 and in_planes == planes):
|
| 50 |
+
self.norm3 = nn.Sequential()
|
| 51 |
+
|
| 52 |
+
if stride == 1 and in_planes == planes:
|
| 53 |
+
self.downsample = None
|
| 54 |
+
|
| 55 |
+
else:
|
| 56 |
+
self.downsample = nn.Sequential(
|
| 57 |
+
nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3)
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
y = x
|
| 61 |
+
y = self.conv1(y)
|
| 62 |
+
y = self.norm1(y)
|
| 63 |
+
y = self.relu(y)
|
| 64 |
+
y = self.conv2(y)
|
| 65 |
+
y = self.norm2(y)
|
| 66 |
+
y = self.relu(y)
|
| 67 |
+
|
| 68 |
+
if self.downsample is not None:
|
| 69 |
+
x = self.downsample(x)
|
| 70 |
+
|
| 71 |
+
return self.relu(x + y)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class UnetExtractor(nn.Module):
|
| 75 |
+
def __init__(self, in_channel=3, encoder_dim=[256, 256, 256], norm_fn='group'):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.in_ds = nn.Sequential(
|
| 78 |
+
nn.Conv2d(in_channel, 64, kernel_size=7, stride=2, padding=3),
|
| 79 |
+
nn.GroupNorm(num_groups=8, num_channels=64),
|
| 80 |
+
nn.ReLU(inplace=True)
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
self.res1 = nn.Sequential(
|
| 84 |
+
ResidualBlock(64, encoder_dim[0], stride=2, norm_fn=norm_fn),
|
| 85 |
+
ResidualBlock(encoder_dim[0], encoder_dim[0], norm_fn=norm_fn)
|
| 86 |
+
)
|
| 87 |
+
self.res2 = nn.Sequential(
|
| 88 |
+
ResidualBlock(encoder_dim[0], encoder_dim[1], stride=2, norm_fn=norm_fn),
|
| 89 |
+
ResidualBlock(encoder_dim[1], encoder_dim[1], norm_fn=norm_fn)
|
| 90 |
+
)
|
| 91 |
+
self.res3 = nn.Sequential(
|
| 92 |
+
ResidualBlock(encoder_dim[1], encoder_dim[2], stride=2, norm_fn=norm_fn),
|
| 93 |
+
ResidualBlock(encoder_dim[2], encoder_dim[2], norm_fn=norm_fn),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
def forward(self, x):
|
| 97 |
+
x = self.in_ds(x)
|
| 98 |
+
x1 = self.res1(x)
|
| 99 |
+
x2 = self.res2(x1)
|
| 100 |
+
x3 = self.res3(x2)
|
| 101 |
+
|
| 102 |
+
return x1, x2, x3
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class MultiBasicEncoder(nn.Module):
|
| 106 |
+
def __init__(self, output_dim=[128], encoder_dim=[64, 96, 128]):
|
| 107 |
+
super(MultiBasicEncoder, self).__init__()
|
| 108 |
+
|
| 109 |
+
# output convolution for feature
|
| 110 |
+
self.conv2 = nn.Sequential(
|
| 111 |
+
ResidualBlock(encoder_dim[2], encoder_dim[2], stride=1),
|
| 112 |
+
nn.Conv2d(encoder_dim[2], encoder_dim[2] * 2, 3, padding=1))
|
| 113 |
+
|
| 114 |
+
# output convolution for context
|
| 115 |
+
output_list = []
|
| 116 |
+
for dim in output_dim:
|
| 117 |
+
conv_out = nn.Sequential(
|
| 118 |
+
ResidualBlock(encoder_dim[2], encoder_dim[2], stride=1),
|
| 119 |
+
nn.Conv2d(encoder_dim[2], dim[2], 3, padding=1))
|
| 120 |
+
output_list.append(conv_out)
|
| 121 |
+
|
| 122 |
+
self.outputs08 = nn.ModuleList(output_list)
|
| 123 |
+
|
| 124 |
+
def forward(self, x):
|
| 125 |
+
feat1, feat2 = self.conv2(x).split(dim=0, split_size=x.shape[0] // 2)
|
| 126 |
+
|
| 127 |
+
outputs08 = [f(x) for f in self.outputs08]
|
| 128 |
+
return outputs08, feat1, feat2
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# attention processor for appreaance head
|
| 133 |
+
|
| 134 |
+
def _init_weights(m):
|
| 135 |
+
if isinstance(m, nn.Linear):
|
| 136 |
+
nn.init.normal_(m.weight, std=.02)
|
| 137 |
+
if m.bias is not None:
|
| 138 |
+
nn.init.constant_(m.bias, 0)
|
| 139 |
+
|
| 140 |
+
class Mlp(nn.Module):
|
| 141 |
+
def __init__(self, in_features, mlp_ratio=4., mlp_bias=False, out_features=None, act_layer=nn.GELU, drop=0.):
|
| 142 |
+
super().__init__()
|
| 143 |
+
out_features = out_features or in_features
|
| 144 |
+
hidden_features = int(in_features * mlp_ratio)
|
| 145 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=mlp_bias)
|
| 146 |
+
self.act = act_layer()
|
| 147 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=mlp_bias)
|
| 148 |
+
self.drop = nn.Dropout(drop)
|
| 149 |
+
|
| 150 |
+
def forward(self, x):
|
| 151 |
+
"""
|
| 152 |
+
x: (B, L, D)
|
| 153 |
+
Returns: same shape as input
|
| 154 |
+
"""
|
| 155 |
+
x = self.fc1(x)
|
| 156 |
+
x = self.act(x)
|
| 157 |
+
x = self.drop(x)
|
| 158 |
+
x = self.fc2(x)
|
| 159 |
+
x = self.drop(x)
|
| 160 |
+
return x
|
| 161 |
+
|
| 162 |
+
class SelfAttention(nn.Module):
|
| 163 |
+
def __init__(self, dim, head_dim=64, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., use_flashatt_v2=True):
|
| 164 |
+
super().__init__()
|
| 165 |
+
assert dim % head_dim == 0, 'dim must be divisible by head_dim'
|
| 166 |
+
self.num_heads = dim // head_dim
|
| 167 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 168 |
+
|
| 169 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 170 |
+
self.attn_drop_p = attn_drop
|
| 171 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 172 |
+
self.proj = nn.Linear(dim, dim, bias=False)
|
| 173 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 174 |
+
|
| 175 |
+
self.norm_q = RMSNorm(head_dim, eps=1e-5)
|
| 176 |
+
self.norm_k = RMSNorm(head_dim, eps=1e-5)
|
| 177 |
+
|
| 178 |
+
self.use_flashatt_v2 = use_flashatt_v2
|
| 179 |
+
|
| 180 |
+
def forward(self, x):
|
| 181 |
+
"""
|
| 182 |
+
x: (B, L, D)
|
| 183 |
+
Returns: same shape as input
|
| 184 |
+
"""
|
| 185 |
+
B, N, C = x.shape
|
| 186 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 187 |
+
|
| 188 |
+
if self.use_flashatt_v2:
|
| 189 |
+
qkv = qkv.permute(2, 0, 1, 3, 4)
|
| 190 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # (B, N, H, C)
|
| 191 |
+
q, k = self.norm_q(q).to(v.dtype), self.norm_k(k).to(v.dtype)
|
| 192 |
+
x = xops.memory_efficient_attention(q, k, v, op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp), p=self.attn_drop_p)
|
| 193 |
+
x = rearrange(x, 'b n h d -> b n (h d)')
|
| 194 |
+
|
| 195 |
+
x = self.proj(x)
|
| 196 |
+
x = self.proj_drop(x)
|
| 197 |
+
return x
|
| 198 |
+
|
| 199 |
+
class CrossAttention(nn.Module):
|
| 200 |
+
def __init__(self, dim, head_dim=64, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., use_flashatt_v2=True):
|
| 201 |
+
super().__init__()
|
| 202 |
+
assert dim % head_dim == 0, 'dim must be divisible by head_dim'
|
| 203 |
+
self.num_heads = dim // head_dim
|
| 204 |
+
self.scale = qk_scale or head_dim ** -0.5
|
| 205 |
+
|
| 206 |
+
self.q = nn.Linear(dim, dim, bias=qkv_bias)
|
| 207 |
+
self.k = nn.Linear(dim, dim, bias=qkv_bias)
|
| 208 |
+
self.v = nn.Linear(dim, dim, bias=qkv_bias)
|
| 209 |
+
|
| 210 |
+
self.attn_drop_p = attn_drop
|
| 211 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 212 |
+
self.proj = nn.Linear(dim, dim, bias=False)
|
| 213 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 214 |
+
|
| 215 |
+
self.norm_q = RMSNorm(head_dim, eps=1e-5)
|
| 216 |
+
self.norm_k = RMSNorm(head_dim, eps=1e-5)
|
| 217 |
+
|
| 218 |
+
self.use_flashatt_v2 = use_flashatt_v2
|
| 219 |
+
|
| 220 |
+
def forward(self, x_q, x_kv):
|
| 221 |
+
"""
|
| 222 |
+
x_q: query input (B, L_q, D)
|
| 223 |
+
x_kv: key-value input (B, L_kv, D)
|
| 224 |
+
Returns: same shape as query input (B, L_q, D)
|
| 225 |
+
"""
|
| 226 |
+
B, N_q, C = x_q.shape
|
| 227 |
+
_, N_kv, _ = x_kv.shape
|
| 228 |
+
|
| 229 |
+
q = self.q(x_q).reshape(B, N_q, self.num_heads, C // self.num_heads)
|
| 230 |
+
k = self.k(x_kv).reshape(B, N_kv, self.num_heads, C // self.num_heads)
|
| 231 |
+
v = self.v(x_kv).reshape(B, N_kv, self.num_heads, C // self.num_heads)
|
| 232 |
+
|
| 233 |
+
if self.use_flashatt_v2:
|
| 234 |
+
q, k = self.norm_q(q).to(v.dtype), self.norm_k(k).to(v.dtype)
|
| 235 |
+
x = xops.memory_efficient_attention(
|
| 236 |
+
q, k, v,
|
| 237 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 238 |
+
p=self.attn_drop_p
|
| 239 |
+
)
|
| 240 |
+
x = rearrange(x, 'b n h d -> b n (h d)')
|
| 241 |
+
|
| 242 |
+
x = self.proj(x)
|
| 243 |
+
x = self.proj_drop(x)
|
| 244 |
+
return x
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class TransformerBlockSelfAttn(nn.Module):
|
| 248 |
+
def __init__(self, dim, head_dim, mlp_ratio=4., mlp_bias=False, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
| 249 |
+
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flashatt_v2=True):
|
| 250 |
+
super().__init__()
|
| 251 |
+
self.norm1 = norm_layer(dim, bias=False)
|
| 252 |
+
self.attn = SelfAttention(
|
| 253 |
+
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)
|
| 254 |
+
self.norm2 = norm_layer(dim, bias=False)
|
| 255 |
+
self.mlp = Mlp(in_features=dim, mlp_ratio=mlp_ratio, mlp_bias=mlp_bias, act_layer=act_layer, drop=drop)
|
| 256 |
+
|
| 257 |
+
def forward(self, x):
|
| 258 |
+
"""
|
| 259 |
+
x: (B, L, D)
|
| 260 |
+
Returns: same shape as input
|
| 261 |
+
"""
|
| 262 |
+
y = self.attn(self.norm1(x))
|
| 263 |
+
x = x + y
|
| 264 |
+
x = x + self.mlp(self.norm2(x))
|
| 265 |
+
return x
|
| 266 |
+
|
| 267 |
+
class TransformerBlockCrossAttn(nn.Module):
|
| 268 |
+
def __init__(self, dim, head_dim, mlp_ratio=4., mlp_bias=False, qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
| 269 |
+
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_flashatt_v2=True):
|
| 270 |
+
super().__init__()
|
| 271 |
+
self.norm1 = norm_layer(dim, bias=False)
|
| 272 |
+
self.attn = CrossAttention(
|
| 273 |
+
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)
|
| 274 |
+
self.norm2 = norm_layer(dim, bias=False)
|
| 275 |
+
self.mlp = Mlp(in_features=dim, mlp_ratio=mlp_ratio, mlp_bias=mlp_bias, act_layer=act_layer, drop=drop)
|
| 276 |
+
|
| 277 |
+
def forward(self, x_list):
|
| 278 |
+
"""
|
| 279 |
+
x_q: (B, L_q, D)
|
| 280 |
+
x_kv: (B, L_kv, D)
|
| 281 |
+
Returns: same shape as input
|
| 282 |
+
"""
|
| 283 |
+
x_q, x_kv = x_list
|
| 284 |
+
y = self.attn(self.norm1(x_q), self.norm1(x_kv))
|
| 285 |
+
x = x_q + y
|
| 286 |
+
x = x + self.mlp(self.norm2(x))
|
| 287 |
+
return x
|
| 288 |
+
|
| 289 |
+
class AppearanceTransformer(nn.Module):
|
| 290 |
+
def __init__(self, num_layers, attn_dim, head_dim, ca_incides=[1, 3, 5, 7]):
|
| 291 |
+
super().__init__()
|
| 292 |
+
self.attn_dim = attn_dim
|
| 293 |
+
self.num_layers = num_layers
|
| 294 |
+
self.blocks = nn.ModuleList()
|
| 295 |
+
self.ca_incides = ca_incides
|
| 296 |
+
|
| 297 |
+
for attn_index in range(num_layers):
|
| 298 |
+
self.blocks.append(TransformerBlockSelfAttn(self.attn_dim, head_dim))
|
| 299 |
+
self.blocks[-1].apply(_init_weights)
|
| 300 |
+
|
| 301 |
+
def forward(self, x, use_checkpoint=True):
|
| 302 |
+
"""
|
| 303 |
+
input_tokens: (B, L, D)
|
| 304 |
+
aggregated_tokens: List of (B, L, D)
|
| 305 |
+
Returns: B and D remain the same, L might change if there are merge layers
|
| 306 |
+
"""
|
| 307 |
+
for block in self.blocks:
|
| 308 |
+
if use_checkpoint:
|
| 309 |
+
x = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False)
|
| 310 |
+
else:
|
| 311 |
+
x = block(x)
|
| 312 |
+
|
| 313 |
+
return x
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
if __name__ == '__main__':
|
| 317 |
+
data = torch.ones((1, 3, 1024, 1024))
|
| 318 |
+
|
| 319 |
+
model = UnetExtractor(in_channel=3, encoder_dim=[64, 96, 128])
|
| 320 |
+
|
| 321 |
+
x1, x2, x3 = model(data)
|
| 322 |
+
print(x1.shape, x2.shape, x3.shape)
|
src/model/encoder/heads/linear_gs_head.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# dpt head implementation for DUST3R
|
| 6 |
+
# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ;
|
| 7 |
+
# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True
|
| 8 |
+
# the forward function also takes as input a dictionnary img_info with key "height" and "width"
|
| 9 |
+
# for PixelwiseTask, the output will be of dimension B x num_channels x H x W
|
| 10 |
+
# --------------------------------------------------------
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from typing import List, Tuple
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
# import dust3r.utils.path_to_croco
|
| 17 |
+
from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block
|
| 18 |
+
from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights
|
| 19 |
+
from .postprocess import postprocess
|
| 20 |
+
import torchvision
|
| 21 |
+
|
| 22 |
+
def custom_interpolate(
|
| 23 |
+
x: torch.Tensor,
|
| 24 |
+
size: Tuple[int, int] = None,
|
| 25 |
+
scale_factor: float = None,
|
| 26 |
+
mode: str = "bilinear",
|
| 27 |
+
align_corners: bool = True,
|
| 28 |
+
) -> torch.Tensor:
|
| 29 |
+
"""
|
| 30 |
+
Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate.
|
| 31 |
+
"""
|
| 32 |
+
if size is None:
|
| 33 |
+
size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
|
| 34 |
+
|
| 35 |
+
INT_MAX = 1610612736
|
| 36 |
+
|
| 37 |
+
input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
|
| 38 |
+
|
| 39 |
+
if input_elements > INT_MAX:
|
| 40 |
+
chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
|
| 41 |
+
interpolated_chunks = [
|
| 42 |
+
nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks
|
| 43 |
+
]
|
| 44 |
+
x = torch.cat(interpolated_chunks, dim=0)
|
| 45 |
+
return x.contiguous()
|
| 46 |
+
else:
|
| 47 |
+
return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners)
|
| 48 |
+
|
| 49 |
+
# class DPTOutputAdapter_fix(DPTOutputAdapter):
|
| 50 |
+
# """
|
| 51 |
+
# Adapt croco's DPTOutputAdapter implementation for dust3r:
|
| 52 |
+
# remove duplicated weigths, and fix forward for dust3r
|
| 53 |
+
# """
|
| 54 |
+
#
|
| 55 |
+
# def init(self, dim_tokens_enc=768):
|
| 56 |
+
# super().init(dim_tokens_enc)
|
| 57 |
+
# # these are duplicated weights
|
| 58 |
+
# del self.act_1_postprocess
|
| 59 |
+
# del self.act_2_postprocess
|
| 60 |
+
# del self.act_3_postprocess
|
| 61 |
+
# del self.act_4_postprocess
|
| 62 |
+
#
|
| 63 |
+
# self.scratch.refinenet1 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 64 |
+
# self.scratch.refinenet2 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 65 |
+
# self.scratch.refinenet3 = make_fusion_block(256 * 2, False, 1, expand=True)
|
| 66 |
+
# # self.scratch.refinenet4 = make_fusion_block(256 * 2, False, 1)
|
| 67 |
+
#
|
| 68 |
+
# self.depth_encoder = UnetExtractor(in_channel=3)
|
| 69 |
+
# self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True)
|
| 70 |
+
# self.out_conv = nn.Conv2d(256+3+4, 256, kernel_size=3, padding=1)
|
| 71 |
+
# self.out_relu = nn.ReLU(inplace=True)
|
| 72 |
+
#
|
| 73 |
+
# self.input_merger = nn.Sequential(
|
| 74 |
+
# # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1),
|
| 75 |
+
# nn.Conv2d(256+3+3, 256, kernel_size=3, padding=1),
|
| 76 |
+
# nn.ReLU(),
|
| 77 |
+
# )
|
| 78 |
+
#
|
| 79 |
+
# def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None):
|
| 80 |
+
# assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 81 |
+
# # H, W = input_info['image_size']
|
| 82 |
+
# image_size = self.image_size if image_size is None else image_size
|
| 83 |
+
# H, W = image_size
|
| 84 |
+
# # Number of patches in height and width
|
| 85 |
+
# N_H = H // (self.stride_level * self.P_H)
|
| 86 |
+
# N_W = W // (self.stride_level * self.P_W)
|
| 87 |
+
#
|
| 88 |
+
# # Hook decoder onto 4 layers from specified ViT layers
|
| 89 |
+
# layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 90 |
+
#
|
| 91 |
+
# # Extract only task-relevant tokens and ignore global tokens.
|
| 92 |
+
# layers = [self.adapt_tokens(l) for l in layers]
|
| 93 |
+
#
|
| 94 |
+
# # Reshape tokens to spatial representation
|
| 95 |
+
# layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 96 |
+
#
|
| 97 |
+
# layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 98 |
+
# # Project layers to chosen feature dim
|
| 99 |
+
# layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 100 |
+
#
|
| 101 |
+
# # get depth features
|
| 102 |
+
# depth_features = self.depth_encoder(depths)
|
| 103 |
+
# depth_feature1, depth_feature2, depth_feature3 = depth_features
|
| 104 |
+
#
|
| 105 |
+
# # Fuse layers using refinement stages
|
| 106 |
+
# path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]]
|
| 107 |
+
# path_3 = self.scratch.refinenet3(torch.cat([path_4, depth_feature3], dim=1), torch.cat([layers[2], depth_feature3], dim=1))
|
| 108 |
+
# path_2 = self.scratch.refinenet2(torch.cat([path_3, depth_feature2], dim=1), torch.cat([layers[1], depth_feature2], dim=1))
|
| 109 |
+
# path_1 = self.scratch.refinenet1(torch.cat([path_2, depth_feature1], dim=1), torch.cat([layers[0], depth_feature1], dim=1))
|
| 110 |
+
# # path_3 = self.scratch.refinenet3(path_4, layers[2], depth_feature3)
|
| 111 |
+
# # path_2 = self.scratch.refinenet2(path_3, layers[1], depth_feature2)
|
| 112 |
+
# # path_1 = self.scratch.refinenet1(path_2, layers[0], depth_feature1)
|
| 113 |
+
#
|
| 114 |
+
# path_1 = self.feat_up(path_1)
|
| 115 |
+
# path_1 = torch.cat([path_1, imgs, depths], dim=1)
|
| 116 |
+
# if conf is not None:
|
| 117 |
+
# path_1 = torch.cat([path_1, conf], dim=1)
|
| 118 |
+
# path_1 = self.input_merger(path_1)
|
| 119 |
+
#
|
| 120 |
+
# # Output head
|
| 121 |
+
# out = self.head(path_1)
|
| 122 |
+
#
|
| 123 |
+
# return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class DPTOutputAdapter_fix(DPTOutputAdapter):
|
| 127 |
+
"""
|
| 128 |
+
Adapt croco's DPTOutputAdapter implementation for dust3r:
|
| 129 |
+
remove duplicated weigths, and fix forward for dust3r
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def init(self, dim_tokens_enc=768):
|
| 133 |
+
super().init(dim_tokens_enc)
|
| 134 |
+
# these are duplicated weights
|
| 135 |
+
del self.act_1_postprocess
|
| 136 |
+
del self.act_2_postprocess
|
| 137 |
+
del self.act_3_postprocess
|
| 138 |
+
del self.act_4_postprocess
|
| 139 |
+
|
| 140 |
+
self.feat_up = Interpolate(scale_factor=2, mode="bilinear", align_corners=True)
|
| 141 |
+
# self.input_merger = nn.Sequential(
|
| 142 |
+
# # nn.Conv2d(256+3+3+1, 256, kernel_size=3, padding=1),
|
| 143 |
+
# # nn.Conv2d(3+6, 256, 7, 1, 3),
|
| 144 |
+
# nn.Conv2d(3, 256, 7, 1, 3),
|
| 145 |
+
# nn.ReLU(),
|
| 146 |
+
# )
|
| 147 |
+
|
| 148 |
+
def forward(self, encoder_tokens: List[torch.Tensor], depths, imgs, image_size=None, conf=None):
|
| 149 |
+
assert self.dim_tokens_enc is not None, 'Need to call init(dim_tokens_enc) function first'
|
| 150 |
+
# H, W = input_info['image_size']
|
| 151 |
+
image_size = self.image_size if image_size is None else image_size
|
| 152 |
+
H, W = image_size
|
| 153 |
+
# Number of patches in height and width
|
| 154 |
+
N_H = H // (self.stride_level * self.P_H)
|
| 155 |
+
N_W = W // (self.stride_level * self.P_W)
|
| 156 |
+
|
| 157 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 158 |
+
layers = [encoder_tokens[hook] for hook in self.hooks]
|
| 159 |
+
|
| 160 |
+
# Extract only task-relevant tokens and ignore global tokens.
|
| 161 |
+
layers = [self.adapt_tokens(l) for l in layers]
|
| 162 |
+
|
| 163 |
+
# Reshape tokens to spatial representation
|
| 164 |
+
layers = [rearrange(l, 'b (nh nw) c -> b c nh nw', nh=N_H, nw=N_W) for l in layers]
|
| 165 |
+
|
| 166 |
+
layers = [self.act_postprocess[idx](l) for idx, l in enumerate(layers)]
|
| 167 |
+
# Project layers to chosen feature dim
|
| 168 |
+
layers = [self.scratch.layer_rn[idx](l) for idx, l in enumerate(layers)]
|
| 169 |
+
|
| 170 |
+
# Fuse layers using refinement stages
|
| 171 |
+
path_4 = self.scratch.refinenet4(layers[3])[:, :, :layers[2].shape[2], :layers[2].shape[3]]
|
| 172 |
+
path_3 = self.scratch.refinenet3(path_4, layers[2])
|
| 173 |
+
path_2 = self.scratch.refinenet2(path_3, layers[1])
|
| 174 |
+
path_1 = self.scratch.refinenet1(path_2, layers[0])
|
| 175 |
+
|
| 176 |
+
# direct_img_feat = self.input_merger(imgs)
|
| 177 |
+
# actually, we just do interpolate here
|
| 178 |
+
# path_1 = self.feat_up(path_1)
|
| 179 |
+
path_1 = custom_interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True)
|
| 180 |
+
# path_1 = F.interpolate(path_1, size=(H, W), mode='bilinear', align_corners=True)
|
| 181 |
+
# path_1 = path_1 + direct_img_feat
|
| 182 |
+
|
| 183 |
+
# path_1 = torch.cat([path_1, imgs], dim=1)
|
| 184 |
+
|
| 185 |
+
# Output head
|
| 186 |
+
# out = self.head(path_1)
|
| 187 |
+
out = path_1
|
| 188 |
+
return out, [path_4, path_3, path_2]
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class PixelwiseTaskWithDPT(nn.Module):
|
| 192 |
+
""" DPT module for dust3r, can return 3D points + confidence for all pixels"""
|
| 193 |
+
|
| 194 |
+
def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None,
|
| 195 |
+
output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs):
|
| 196 |
+
super(PixelwiseTaskWithDPT, self).__init__()
|
| 197 |
+
self.return_all_layers = True # backbone needs to return all layers
|
| 198 |
+
self.postprocess = postprocess
|
| 199 |
+
self.depth_mode = depth_mode
|
| 200 |
+
self.conf_mode = conf_mode
|
| 201 |
+
|
| 202 |
+
assert n_cls_token == 0, "Not implemented"
|
| 203 |
+
dpt_args = dict(output_width_ratio=output_width_ratio,
|
| 204 |
+
num_channels=num_channels,
|
| 205 |
+
**kwargs)
|
| 206 |
+
if hooks_idx is not None:
|
| 207 |
+
dpt_args.update(hooks=hooks_idx)
|
| 208 |
+
self.dpt = DPTOutputAdapter_fix(**dpt_args)
|
| 209 |
+
dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens}
|
| 210 |
+
self.dpt.init(**dpt_init_args)
|
| 211 |
+
|
| 212 |
+
def forward(self, x, depths, imgs, img_info, conf=None):
|
| 213 |
+
out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf)
|
| 214 |
+
if self.postprocess:
|
| 215 |
+
out = self.postprocess(out, self.depth_mode, self.conf_mode)
|
| 216 |
+
return out, interm_feats
|
| 217 |
+
|
| 218 |
+
class AttnBasedAppearanceHead(nn.Module):
|
| 219 |
+
"""
|
| 220 |
+
Attention head Appearence Reconstruction
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
def __init__(self, num_channels, patch_size, feature_dim, last_dim, hooks_idx, dim_tokens, postprocess, depth_mode, conf_mode, head_type='gs_params'):
|
| 224 |
+
super().__init__()
|
| 225 |
+
|
| 226 |
+
self.num_channels = num_channels
|
| 227 |
+
self.patch_size = patch_size
|
| 228 |
+
|
| 229 |
+
self.hooks = hooks_idx
|
| 230 |
+
|
| 231 |
+
assert len(set(dim_tokens)) == 1
|
| 232 |
+
|
| 233 |
+
self.tokenizer = nn.Linear(3 * self.patch_size[0] ** 2 + 512, dim_tokens[0], bias=False)
|
| 234 |
+
self.C_feat = 128
|
| 235 |
+
|
| 236 |
+
self.vgg_feature_extractor = torchvision.models.vgg16(pretrained=True).features
|
| 237 |
+
# Freeze the VGG parameters
|
| 238 |
+
for param in self.vgg_feature_extractor.parameters():
|
| 239 |
+
param.requires_grad = False
|
| 240 |
+
|
| 241 |
+
self.token_decoder = nn.Sequential(
|
| 242 |
+
nn.Linear(dim_tokens[0] * (len(self.hooks) + 1), self.C_feat * (self.patch_size[0] ** 2)),
|
| 243 |
+
nn.SiLU(),
|
| 244 |
+
nn.Linear(self.C_feat * (self.patch_size[0] ** 2), self.C_feat * (self.patch_size[0] ** 2)),
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
self.pixel_linear = nn.Linear(self.C_feat, self.num_channels)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def img_pts_tokenizer(self, imgs):
|
| 251 |
+
_, _, H, W = imgs.shape
|
| 252 |
+
# Process images through VGG to extract features
|
| 253 |
+
# imgs = imgs.permute(0, 2, 3, 1).contiguous()
|
| 254 |
+
with torch.no_grad():
|
| 255 |
+
vgg_features = self.vgg_feature_extractor(imgs)
|
| 256 |
+
|
| 257 |
+
# 1. concat original images with vgg features and then patchify
|
| 258 |
+
vgg_features = F.interpolate(vgg_features, size=(H, W), mode='bilinear', align_corners=False)
|
| 259 |
+
combined = torch.cat([imgs, vgg_features], dim=1) # [B, C+512, H, W]
|
| 260 |
+
combined = combined.permute(0, 2, 3, 1).contiguous()
|
| 261 |
+
|
| 262 |
+
patch_size = self.patch_size
|
| 263 |
+
hh = H // patch_size[0]
|
| 264 |
+
ww = W // patch_size[1]
|
| 265 |
+
input_patches = rearrange(combined, "b (hh ph) (ww pw) c -> b (hh ww) (ph pw c)",
|
| 266 |
+
hh=hh, ww=ww, ph=patch_size[0], pw=patch_size[1])
|
| 267 |
+
|
| 268 |
+
input_tokens = self.tokenizer(input_patches)
|
| 269 |
+
|
| 270 |
+
# 2. only use vgg features, use a shallow conv to get the token
|
| 271 |
+
|
| 272 |
+
# # Combine original images with VGG features
|
| 273 |
+
# imgs = torch.cat([imgs, vgg_features], dim=1)
|
| 274 |
+
# imgs = imgs.permute(0, 2, 3, 1).flatten(1, 2).contiguous()
|
| 275 |
+
|
| 276 |
+
# # Pachify
|
| 277 |
+
# patch_size = self.patch_size
|
| 278 |
+
# hh = H // patch_size[0]
|
| 279 |
+
# ww = W // patch_size[1]
|
| 280 |
+
# 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])
|
| 281 |
+
# Tokenize the input images
|
| 282 |
+
input_tokens = self.tokenizer(input)
|
| 283 |
+
return input_tokens
|
| 284 |
+
|
| 285 |
+
def forward(self, x, depths, imgs, img_info, conf=None):
|
| 286 |
+
B, V, H, W = img_info
|
| 287 |
+
input_tokens = self.img_pts_tokenizer(imgs)
|
| 288 |
+
# Hook decoder onto 4 layers from specified ViT layers
|
| 289 |
+
layer_tokens = [x[hook] for hook in self.hooks] # [B, S, D]
|
| 290 |
+
# layer_tokens.append(input_tokens)
|
| 291 |
+
|
| 292 |
+
x = self.token_decoder(torch.cat(layer_tokens, dim=-1))
|
| 293 |
+
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()
|
| 294 |
+
out_flat = self.pixel_linear(x)
|
| 295 |
+
|
| 296 |
+
return out_flat.view(B*V, H, W, -1).permute(0, 3, 1, 2)
|
| 297 |
+
|
| 298 |
+
# class Pixellevel_Linear_Pts3d(nn.Module):
|
| 299 |
+
# """
|
| 300 |
+
# Pixel-level linear head for DUST3R
|
| 301 |
+
# Each pixel outputs: 3D point (+ confidence)
|
| 302 |
+
# """
|
| 303 |
+
|
| 304 |
+
# def __init__(self, dec_embed_dim, patch_size, depth_mode, conf_mode, has_conf=False, index_hook=[-1]):
|
| 305 |
+
# super().__init__()
|
| 306 |
+
# self.patch_size = patch_size
|
| 307 |
+
# self.depth_mode = depth_mode
|
| 308 |
+
# self.conf_mode = conf_mode
|
| 309 |
+
# self.has_conf = has_conf
|
| 310 |
+
# self.dec_embed_dim = dec_embed_dim
|
| 311 |
+
# self.index_hook = index_hook
|
| 312 |
+
|
| 313 |
+
# # Total embedding dimension per token (possibly concatenated)
|
| 314 |
+
# D = self.dec_embed_dim * len(self.index_hook)
|
| 315 |
+
# # Ensure divisible into pixel-level features
|
| 316 |
+
# assert D % (self.patch_size**2) == 0, \
|
| 317 |
+
# f"Embedding dim {D} not divisible by patch_size^2 ({self.patch_size**2})"
|
| 318 |
+
# # Feature dimension for each pixel
|
| 319 |
+
# self.C_feat = D // (self.patch_size**2) * 4
|
| 320 |
+
# # Output channels: x,y,z (+ confidence)
|
| 321 |
+
# self.out_dim = 3 + int(self.has_conf)
|
| 322 |
+
|
| 323 |
+
# self.feat_expand = nn.Sequential(nn.Linear(D, 4*D),
|
| 324 |
+
# nn.SiLU(),
|
| 325 |
+
# nn.Linear(4*D, 4*D)
|
| 326 |
+
# )
|
| 327 |
+
# # Per-pixel linear head
|
| 328 |
+
# self.pixel_linear = nn.Linear(self.C_feat, self.out_dim)
|
| 329 |
+
|
| 330 |
+
# def setup(self, croconet):
|
| 331 |
+
# pass
|
| 332 |
+
|
| 333 |
+
# def forward(self, decout, img_shape):
|
| 334 |
+
# H, W = img_shape
|
| 335 |
+
# # Combine specified decoder tokens: B x num_patches x D
|
| 336 |
+
# tokens = [decout[i] for i in self.index_hook]
|
| 337 |
+
# x = torch.cat(tokens, dim=-1) # B, S, D
|
| 338 |
+
# x = self.feat_expand(x)
|
| 339 |
+
# B, S, D = x.shape
|
| 340 |
+
|
| 341 |
+
# # Validate pixel count
|
| 342 |
+
# assert S * (self.patch_size**2) == H * W, \
|
| 343 |
+
# f"Mismatch: S*ps^2 ({S*self.patch_size**2}) != H*W ({H*W})"
|
| 344 |
+
|
| 345 |
+
# # 1. Reshape embedding into pixel features
|
| 346 |
+
# # x -> B, S, (ps^2), C_feat -> flatten to B, (S*ps^2), C_feat
|
| 347 |
+
# x = x.view(B, S, self.patch_size**2, self.C_feat)
|
| 348 |
+
# x = x.reshape(B, S * self.patch_size**2, self.C_feat)
|
| 349 |
+
|
| 350 |
+
# # 2. Per-pixel linear output
|
| 351 |
+
# out_flat = self.pixel_linear(x) # B, S*ps^2, out_dim
|
| 352 |
+
|
| 353 |
+
# # 3. Reshape to image map: B x out_dim x H x W
|
| 354 |
+
# out = out_flat.permute(0, 2, 1).view(B, self.out_dim, H, W)
|
| 355 |
+
|
| 356 |
+
# # 4. Postprocess depth/conf
|
| 357 |
+
# return out
|
| 358 |
+
|
| 359 |
+
def create_gs_linear_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess):
|
| 360 |
+
"""
|
| 361 |
+
return PixelwiseTaskWithDPT for given net params
|
| 362 |
+
"""
|
| 363 |
+
assert net.dec_depth > 9
|
| 364 |
+
l2 = net.dec_depth
|
| 365 |
+
feature_dim = net.feature_dim
|
| 366 |
+
last_dim = feature_dim//2
|
| 367 |
+
ed = net.enc_embed_dim
|
| 368 |
+
dd = net.dec_embed_dim
|
| 369 |
+
try:
|
| 370 |
+
patch_size = net.patch_size
|
| 371 |
+
except:
|
| 372 |
+
patch_size = (16, 16)
|
| 373 |
+
|
| 374 |
+
return AttnBasedAppearanceHead(num_channels=out_nchan + has_conf,
|
| 375 |
+
patch_size=patch_size,
|
| 376 |
+
feature_dim=feature_dim,
|
| 377 |
+
last_dim=last_dim,
|
| 378 |
+
hooks_idx=[0, l2*2//4, l2*3//4, l2],
|
| 379 |
+
dim_tokens=[ed, dd, dd, dd],
|
| 380 |
+
postprocess=postprocess_func,
|
| 381 |
+
depth_mode=net.depth_mode,
|
| 382 |
+
conf_mode=net.conf_mode,
|
| 383 |
+
head_type='gs_params')
|
src/model/encoder/heads/linear_head.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# linear head implementation for DUST3R
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from .postprocess import postprocess
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LinearPts3d (nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
Linear head for dust3r
|
| 15 |
+
Each token outputs: - 16x16 3D points (+ confidence)
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, net, has_conf=False):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.patch_size = net.patch_embed.patch_size[0]
|
| 21 |
+
self.depth_mode = net.depth_mode
|
| 22 |
+
self.conf_mode = net.conf_mode
|
| 23 |
+
self.has_conf = has_conf
|
| 24 |
+
|
| 25 |
+
self.proj = nn.Linear(net.dec_embed_dim, (3 + has_conf)*self.patch_size**2)
|
| 26 |
+
|
| 27 |
+
def setup(self, croconet):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
def forward(self, decout, img_shape):
|
| 31 |
+
H, W = img_shape
|
| 32 |
+
tokens = decout[-1]
|
| 33 |
+
B, S, D = tokens.shape
|
| 34 |
+
|
| 35 |
+
# extract 3D points
|
| 36 |
+
feat = self.proj(tokens) # B,S,D
|
| 37 |
+
feat = feat.transpose(-1, -2).view(B, -1, H//self.patch_size, W//self.patch_size)
|
| 38 |
+
feat = F.pixel_shuffle(feat, self.patch_size) # B,3,H,W
|
| 39 |
+
|
| 40 |
+
# permute + norm depth
|
| 41 |
+
return postprocess(feat, self.depth_mode, self.conf_mode)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class LinearGS(nn.Module):
|
| 45 |
+
"""
|
| 46 |
+
Linear head for GS parameter prediction
|
| 47 |
+
Each token outputs: - 16x16 3D points (+ confidence)
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, net, has_conf=False):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.patch_size = net.patch_embed.patch_size[0]
|
| 53 |
+
self.depth_mode = net.depth_mode
|
| 54 |
+
self.conf_mode = net.conf_mode
|
| 55 |
+
self.has_conf = has_conf
|
| 56 |
+
|
| 57 |
+
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
|
| 58 |
+
|
| 59 |
+
def setup(self, croconet):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
def forward(self, decout, img_shape):
|
| 63 |
+
H, W = img_shape
|
| 64 |
+
tokens = decout[-1]
|
| 65 |
+
B, S, D = tokens.shape
|
| 66 |
+
|
| 67 |
+
# extract 3D points
|
| 68 |
+
feat = self.proj(tokens) # B,S,D
|
| 69 |
+
feat = feat.transpose(-1, -2).view(B, -1, H//self.patch_size, W//self.patch_size)
|
| 70 |
+
feat = F.pixel_shuffle(feat, self.patch_size) # B,3,H,W
|
| 71 |
+
|
| 72 |
+
# permute + norm depth
|
| 73 |
+
return postprocess(feat, self.depth_mode, self.conf_mode)
|
src/model/encoder/heads/postprocess.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# post process function for all heads: extract 3D points/confidence from output
|
| 6 |
+
# --------------------------------------------------------
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def postprocess(out, depth_mode, conf_mode):
|
| 11 |
+
"""
|
| 12 |
+
extract 3D points/confidence from prediction head output
|
| 13 |
+
"""
|
| 14 |
+
fmap = out.permute(0, 2, 3, 1) # B,H,W,3
|
| 15 |
+
res = dict(pts3d=reg_dense_depth(fmap[:, :, :, 0:3], mode=depth_mode))
|
| 16 |
+
|
| 17 |
+
if conf_mode is not None:
|
| 18 |
+
res['conf'] = reg_dense_conf(fmap[:, :, :, 3], mode=conf_mode)
|
| 19 |
+
return res
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def reg_dense_depth(xyz, mode):
|
| 23 |
+
"""
|
| 24 |
+
extract 3D points from prediction head output
|
| 25 |
+
"""
|
| 26 |
+
mode, vmin, vmax = mode
|
| 27 |
+
|
| 28 |
+
no_bounds = (vmin == -float('inf')) and (vmax == float('inf'))
|
| 29 |
+
# assert no_bounds
|
| 30 |
+
|
| 31 |
+
if mode == 'range':
|
| 32 |
+
xyz = xyz.sigmoid()
|
| 33 |
+
xyz = (1 - xyz) * vmin + xyz * vmax
|
| 34 |
+
return xyz
|
| 35 |
+
|
| 36 |
+
if mode == 'linear':
|
| 37 |
+
if no_bounds:
|
| 38 |
+
return xyz # [-inf, +inf]
|
| 39 |
+
return xyz.clip(min=vmin, max=vmax)
|
| 40 |
+
|
| 41 |
+
if mode == 'exp_direct':
|
| 42 |
+
xyz = xyz.expm1()
|
| 43 |
+
return xyz.clip(min=vmin, max=vmax)
|
| 44 |
+
|
| 45 |
+
# distance to origin
|
| 46 |
+
d = xyz.norm(dim=-1, keepdim=True)
|
| 47 |
+
xyz = xyz / d.clip(min=1e-8)
|
| 48 |
+
|
| 49 |
+
if mode == 'square':
|
| 50 |
+
return xyz * d.square()
|
| 51 |
+
|
| 52 |
+
if mode == 'exp':
|
| 53 |
+
exp_d = d.expm1()
|
| 54 |
+
if not no_bounds:
|
| 55 |
+
exp_d = exp_d.clip(min=vmin, max=vmax)
|
| 56 |
+
xyz = xyz * exp_d
|
| 57 |
+
# if not no_bounds:
|
| 58 |
+
# # xyz = xyz.clip(min=vmin, max=vmax)
|
| 59 |
+
# depth = xyz.clone()[..., 2].clip(min=vmin, max=vmax)
|
| 60 |
+
# xyz = torch.cat([xyz[..., :2], depth.unsqueeze(-1)], dim=-1)
|
| 61 |
+
return xyz
|
| 62 |
+
|
| 63 |
+
raise ValueError(f'bad {mode=}')
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def reg_dense_conf(x, mode):
|
| 67 |
+
"""
|
| 68 |
+
extract confidence from prediction head output
|
| 69 |
+
"""
|
| 70 |
+
mode, vmin, vmax = mode
|
| 71 |
+
if mode == 'opacity':
|
| 72 |
+
return x.sigmoid()
|
| 73 |
+
if mode == 'exp':
|
| 74 |
+
return vmin + x.exp().clip(max=vmax-vmin)
|
| 75 |
+
if mode == 'sigmoid':
|
| 76 |
+
return (vmax - vmin) * torch.sigmoid(x) + vmin
|
| 77 |
+
raise ValueError(f'bad {mode=}')
|
src/model/encoder/heads/vggt_dpt_gs_head.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024-present Naver Corporation. All rights reserved.
|
| 2 |
+
# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
|
| 3 |
+
#
|
| 4 |
+
# --------------------------------------------------------
|
| 5 |
+
# dpt head implementation for DUST3R
|
| 6 |
+
# Downstream heads assume inputs of size B x N x C (where N is the number of tokens) ;
|
| 7 |
+
# or if it takes as input the output at every layer, the attribute return_all_layers should be set to True
|
| 8 |
+
# the forward function also takes as input a dictionnary img_info with key "height" and "width"
|
| 9 |
+
# for PixelwiseTask, the output will be of dimension B x num_channels x H x W
|
| 10 |
+
# --------------------------------------------------------
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from typing import List
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
# import dust3r.utils.path_to_croco
|
| 17 |
+
from .dpt_block import DPTOutputAdapter, Interpolate, make_fusion_block
|
| 18 |
+
from src.model.encoder.vggt.heads.dpt_head import DPTHead
|
| 19 |
+
from .head_modules import UnetExtractor, AppearanceTransformer, _init_weights
|
| 20 |
+
from .postprocess import postprocess
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# def __init__(self,
|
| 24 |
+
# num_channels: int = 1,
|
| 25 |
+
# stride_level: int = 1,
|
| 26 |
+
# patch_size: Union[int, Tuple[int, int]] = 16,
|
| 27 |
+
# main_tasks: Iterable[str] = ('rgb',),
|
| 28 |
+
# hooks: List[int] = [2, 5, 8, 11],
|
| 29 |
+
# layer_dims: List[int] = [96, 192, 384, 768],
|
| 30 |
+
# feature_dim: int = 256,
|
| 31 |
+
# last_dim: int = 32,
|
| 32 |
+
# use_bn: bool = False,
|
| 33 |
+
# dim_tokens_enc: Optional[int] = None,
|
| 34 |
+
# head_type: str = 'regression',
|
| 35 |
+
# output_width_ratio=1,
|
| 36 |
+
|
| 37 |
+
class VGGT_DPT_GS_Head(DPTHead):
|
| 38 |
+
def __init__(self,
|
| 39 |
+
dim_in: int,
|
| 40 |
+
patch_size: int = 14,
|
| 41 |
+
output_dim: int = 83,
|
| 42 |
+
activation: str = "inv_log",
|
| 43 |
+
conf_activation: str = "expp1",
|
| 44 |
+
features: int = 256,
|
| 45 |
+
out_channels: List[int] = [256, 512, 1024, 1024],
|
| 46 |
+
intermediate_layer_idx: List[int] = [4, 11, 17, 23],
|
| 47 |
+
pos_embed: bool = True,
|
| 48 |
+
feature_only: bool = False,
|
| 49 |
+
down_ratio: int = 1,
|
| 50 |
+
):
|
| 51 |
+
super().__init__(dim_in, patch_size, output_dim, activation, conf_activation, features, out_channels, intermediate_layer_idx, pos_embed, feature_only, down_ratio)
|
| 52 |
+
|
| 53 |
+
head_features_1 = 128
|
| 54 |
+
head_features_2 = 128 if output_dim > 50 else 32 # sh=0, head_features_2 = 32; sh=4, head_features_2 = 128
|
| 55 |
+
self.input_merger = nn.Sequential(
|
| 56 |
+
nn.Conv2d(3, head_features_2, 7, 1, 3),
|
| 57 |
+
nn.ReLU(),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 61 |
+
nn.Conv2d(head_features_1, head_features_2, kernel_size=3, stride=1, padding=1),
|
| 62 |
+
nn.ReLU(inplace=True),
|
| 63 |
+
nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
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):
|
| 67 |
+
# H, W = input_info['image_size']
|
| 68 |
+
B, S, _, H, W = imgs.shape
|
| 69 |
+
image_size = self.image_size if image_size is None else image_size
|
| 70 |
+
|
| 71 |
+
# If frames_chunk_size is not specified or greater than S, process all frames at once
|
| 72 |
+
if frames_chunk_size is None or frames_chunk_size >= S:
|
| 73 |
+
return self._forward_impl(encoder_tokens, imgs, patch_start_idx)
|
| 74 |
+
|
| 75 |
+
# Otherwise, process frames in chunks to manage memory usage
|
| 76 |
+
assert frames_chunk_size > 0
|
| 77 |
+
|
| 78 |
+
# Process frames in batches
|
| 79 |
+
all_preds = []
|
| 80 |
+
|
| 81 |
+
for frames_start_idx in range(0, S, frames_chunk_size):
|
| 82 |
+
frames_end_idx = min(frames_start_idx + frames_chunk_size, S)
|
| 83 |
+
|
| 84 |
+
# Process batch of frames
|
| 85 |
+
chunk_output = self._forward_impl(
|
| 86 |
+
encoder_tokens, imgs, patch_start_idx, frames_start_idx, frames_end_idx
|
| 87 |
+
)
|
| 88 |
+
all_preds.append(chunk_output)
|
| 89 |
+
|
| 90 |
+
# Concatenate results along the sequence dimension
|
| 91 |
+
return torch.cat(all_preds, dim=1)
|
| 92 |
+
|
| 93 |
+
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):
|
| 94 |
+
|
| 95 |
+
if frames_start_idx is not None and frames_end_idx is not None:
|
| 96 |
+
imgs = imgs[:, frames_start_idx:frames_end_idx]
|
| 97 |
+
|
| 98 |
+
B, S, _, H, W = imgs.shape
|
| 99 |
+
|
| 100 |
+
patch_h, patch_w = H // self.patch_size[0], W // self.patch_size[1]
|
| 101 |
+
|
| 102 |
+
out = []
|
| 103 |
+
dpt_idx = 0
|
| 104 |
+
for layer_idx in self.intermediate_layer_idx:
|
| 105 |
+
# x = encoder_tokens[layer_idx][:, :, patch_start_idx:]
|
| 106 |
+
if len(encoder_tokens) > 10:
|
| 107 |
+
x = encoder_tokens[layer_idx][:, :, patch_start_idx:]
|
| 108 |
+
else:
|
| 109 |
+
list_idx = self.intermediate_layer_idx.index(layer_idx)
|
| 110 |
+
x = encoder_tokens[list_idx][:, :, patch_start_idx:]
|
| 111 |
+
|
| 112 |
+
# Select frames if processing a chunk
|
| 113 |
+
if frames_start_idx is not None and frames_end_idx is not None:
|
| 114 |
+
x = x[:, frames_start_idx:frames_end_idx].contiguous()
|
| 115 |
+
|
| 116 |
+
x = x.view(B * S, -1, x.shape[-1])
|
| 117 |
+
|
| 118 |
+
x = self.norm(x)
|
| 119 |
+
|
| 120 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
| 121 |
+
|
| 122 |
+
x = self.projects[dpt_idx](x)
|
| 123 |
+
if self.pos_embed:
|
| 124 |
+
x = self._apply_pos_embed(x, W, H)
|
| 125 |
+
x = self.resize_layers[dpt_idx](x)
|
| 126 |
+
|
| 127 |
+
out.append(x)
|
| 128 |
+
dpt_idx += 1
|
| 129 |
+
|
| 130 |
+
# Fuse features from multiple layers.
|
| 131 |
+
out = self.scratch_forward(out)
|
| 132 |
+
direct_img_feat = self.input_merger(imgs.flatten(0,1))
|
| 133 |
+
out = F.interpolate(out, size=(H, W), mode='bilinear', align_corners=True)
|
| 134 |
+
out = out + direct_img_feat
|
| 135 |
+
|
| 136 |
+
if self.pos_embed:
|
| 137 |
+
out = self._apply_pos_embed(out, W, H)
|
| 138 |
+
|
| 139 |
+
out = self.scratch.output_conv2(out)
|
| 140 |
+
out = out.view(B, S, *out.shape[1:])
|
| 141 |
+
return out
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class PixelwiseTaskWithDPT(nn.Module):
|
| 145 |
+
""" DPT module for dust3r, can return 3D points + confidence for all pixels"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, *, n_cls_token=0, hooks_idx=None, dim_tokens=None,
|
| 148 |
+
output_width_ratio=1, num_channels=1, postprocess=None, depth_mode=None, conf_mode=None, **kwargs):
|
| 149 |
+
super(PixelwiseTaskWithDPT, self).__init__()
|
| 150 |
+
self.return_all_layers = True # backbone needs to return all layers
|
| 151 |
+
self.postprocess = postprocess
|
| 152 |
+
self.depth_mode = depth_mode
|
| 153 |
+
self.conf_mode = conf_mode
|
| 154 |
+
|
| 155 |
+
assert n_cls_token == 0, "Not implemented"
|
| 156 |
+
dpt_args = dict(output_width_ratio=output_width_ratio,
|
| 157 |
+
num_channels=num_channels,
|
| 158 |
+
**kwargs)
|
| 159 |
+
if hooks_idx is not None:
|
| 160 |
+
dpt_args.update(hooks=hooks_idx)
|
| 161 |
+
self.dpt = DPTOutputAdapter_fix(**dpt_args)
|
| 162 |
+
dpt_init_args = {} if dim_tokens is None else {'dim_tokens_enc': dim_tokens}
|
| 163 |
+
self.dpt.init(**dpt_init_args)
|
| 164 |
+
|
| 165 |
+
def forward(self, x, depths, imgs, img_info, conf=None):
|
| 166 |
+
out, interm_feats = self.dpt(x, depths, imgs, image_size=(img_info[0], img_info[1]), conf=conf)
|
| 167 |
+
if self.postprocess:
|
| 168 |
+
out = self.postprocess(out, self.depth_mode, self.conf_mode)
|
| 169 |
+
return out, interm_feats
|
| 170 |
+
|
| 171 |
+
def create_gs_dpt_head(net, has_conf=False, out_nchan=3, postprocess_func=postprocess):
|
| 172 |
+
"""
|
| 173 |
+
return PixelwiseTaskWithDPT for given net params
|
| 174 |
+
"""
|
| 175 |
+
assert net.dec_depth > 9
|
| 176 |
+
l2 = net.dec_depth
|
| 177 |
+
feature_dim = net.feature_dim
|
| 178 |
+
last_dim = feature_dim//2
|
| 179 |
+
ed = net.enc_embed_dim
|
| 180 |
+
dd = net.dec_embed_dim
|
| 181 |
+
try:
|
| 182 |
+
patch_size = net.patch_size
|
| 183 |
+
except:
|
| 184 |
+
patch_size = (16, 16)
|
| 185 |
+
|
| 186 |
+
return PixelwiseTaskWithDPT(num_channels=out_nchan + has_conf,
|
| 187 |
+
patch_size=patch_size,
|
| 188 |
+
feature_dim=feature_dim,
|
| 189 |
+
last_dim=last_dim,
|
| 190 |
+
hooks_idx=[0, l2*2//4, l2*3//4, l2],
|
| 191 |
+
dim_tokens=[ed, dd, dd, dd],
|
| 192 |
+
postprocess=postprocess_func,
|
| 193 |
+
depth_mode=net.depth_mode,
|
| 194 |
+
conf_mode=net.conf_mode,
|
| 195 |
+
head_type='gs_params')
|
src/model/encoder/vggt/heads/camera_head.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from src.model.encoder.vggt.layers import Mlp
|
| 15 |
+
from src.model.encoder.vggt.layers.block import Block
|
| 16 |
+
from src.model.encoder.vggt.heads.head_act import activate_pose
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CameraHead(nn.Module):
|
| 20 |
+
"""
|
| 21 |
+
CameraHead predicts camera parameters from token representations using iterative refinement.
|
| 22 |
+
|
| 23 |
+
It applies a series of transformer blocks (the "trunk") to dedicated camera tokens.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
dim_in: int = 2048,
|
| 29 |
+
trunk_depth: int = 4,
|
| 30 |
+
pose_encoding_type: str = "absT_quaR_FoV",
|
| 31 |
+
num_heads: int = 16,
|
| 32 |
+
mlp_ratio: int = 4,
|
| 33 |
+
init_values: float = 0.01,
|
| 34 |
+
trans_act: str = "linear",
|
| 35 |
+
quat_act: str = "linear",
|
| 36 |
+
fl_act: str = "relu", # Field of view activations: ensures FOV values are positive.
|
| 37 |
+
):
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
if pose_encoding_type == "absT_quaR_FoV":
|
| 41 |
+
self.target_dim = 9
|
| 42 |
+
else:
|
| 43 |
+
raise ValueError(f"Unsupported camera encoding type: {pose_encoding_type}")
|
| 44 |
+
|
| 45 |
+
self.trans_act = trans_act
|
| 46 |
+
self.quat_act = quat_act
|
| 47 |
+
self.fl_act = fl_act
|
| 48 |
+
self.trunk_depth = trunk_depth
|
| 49 |
+
|
| 50 |
+
# Build the trunk using a sequence of transformer blocks.
|
| 51 |
+
self.trunk = nn.Sequential(
|
| 52 |
+
*[
|
| 53 |
+
Block(
|
| 54 |
+
dim=dim_in,
|
| 55 |
+
num_heads=num_heads,
|
| 56 |
+
mlp_ratio=mlp_ratio,
|
| 57 |
+
init_values=init_values,
|
| 58 |
+
)
|
| 59 |
+
for _ in range(trunk_depth)
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Normalizations for camera token and trunk output.
|
| 64 |
+
self.token_norm = nn.LayerNorm(dim_in)
|
| 65 |
+
self.trunk_norm = nn.LayerNorm(dim_in)
|
| 66 |
+
|
| 67 |
+
# Learnable empty camera pose token.
|
| 68 |
+
self.empty_pose_tokens = nn.Parameter(torch.zeros(1, 1, self.target_dim))
|
| 69 |
+
self.embed_pose = nn.Linear(self.target_dim, dim_in)
|
| 70 |
+
|
| 71 |
+
# Module for producing modulation parameters: shift, scale, and a gate.
|
| 72 |
+
self.poseLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim_in, 3 * dim_in, bias=True))
|
| 73 |
+
|
| 74 |
+
# Adaptive layer normalization without affine parameters.
|
| 75 |
+
self.adaln_norm = nn.LayerNorm(dim_in, elementwise_affine=False, eps=1e-6)
|
| 76 |
+
self.pose_branch = Mlp(
|
| 77 |
+
in_features=dim_in,
|
| 78 |
+
hidden_features=dim_in // 2,
|
| 79 |
+
out_features=self.target_dim,
|
| 80 |
+
drop=0,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def forward(self, aggregated_tokens_list: list, num_iterations: int = 4) -> list:
|
| 84 |
+
"""
|
| 85 |
+
Forward pass to predict camera parameters.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
aggregated_tokens_list (list): List of token tensors from the network;
|
| 89 |
+
the last tensor is used for prediction.
|
| 90 |
+
num_iterations (int, optional): Number of iterative refinement steps. Defaults to 4.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
list: A list of predicted camera encodings (post-activation) from each iteration.
|
| 94 |
+
"""
|
| 95 |
+
# Use tokens from the last block for camera prediction.
|
| 96 |
+
tokens = aggregated_tokens_list[-1]
|
| 97 |
+
|
| 98 |
+
# Extract the camera tokens
|
| 99 |
+
pose_tokens = tokens[:, :, 0]
|
| 100 |
+
|
| 101 |
+
pose_tokens = self.token_norm(pose_tokens)
|
| 102 |
+
|
| 103 |
+
pred_pose_enc_list = self.trunk_fn(pose_tokens, num_iterations)
|
| 104 |
+
return pred_pose_enc_list
|
| 105 |
+
|
| 106 |
+
def trunk_fn(self, pose_tokens: torch.Tensor, num_iterations: int) -> list:
|
| 107 |
+
"""
|
| 108 |
+
Iteratively refine camera pose predictions.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
pose_tokens (torch.Tensor): Normalized camera tokens with shape [B, 1, C].
|
| 112 |
+
num_iterations (int): Number of refinement iterations.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
list: List of activated camera encodings from each iteration.
|
| 116 |
+
"""
|
| 117 |
+
B, S, C = pose_tokens.shape # S is expected to be 1.
|
| 118 |
+
pred_pose_enc = None
|
| 119 |
+
pred_pose_enc_list = []
|
| 120 |
+
|
| 121 |
+
for _ in range(num_iterations):
|
| 122 |
+
# Use a learned empty pose for the first iteration.
|
| 123 |
+
if pred_pose_enc is None:
|
| 124 |
+
module_input = self.embed_pose(self.empty_pose_tokens.expand(B, S, -1))
|
| 125 |
+
else:
|
| 126 |
+
# Detach the previous prediction to avoid backprop through time.
|
| 127 |
+
pred_pose_enc = pred_pose_enc.detach()
|
| 128 |
+
module_input = self.embed_pose(pred_pose_enc)
|
| 129 |
+
|
| 130 |
+
# Generate modulation parameters and split them into shift, scale, and gate components.
|
| 131 |
+
shift_msa, scale_msa, gate_msa = self.poseLN_modulation(module_input).chunk(3, dim=-1)
|
| 132 |
+
|
| 133 |
+
# Adaptive layer normalization and modulation.
|
| 134 |
+
pose_tokens_modulated = gate_msa * modulate(self.adaln_norm(pose_tokens), shift_msa, scale_msa)
|
| 135 |
+
pose_tokens_modulated = pose_tokens_modulated + pose_tokens
|
| 136 |
+
|
| 137 |
+
pose_tokens_modulated = torch.utils.checkpoint.checkpoint(
|
| 138 |
+
self.trunk,
|
| 139 |
+
pose_tokens_modulated,
|
| 140 |
+
use_reentrant=False,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# Compute the delta update for the pose encoding.
|
| 144 |
+
pred_pose_enc_delta = self.pose_branch(self.trunk_norm(pose_tokens_modulated))
|
| 145 |
+
|
| 146 |
+
if pred_pose_enc is None:
|
| 147 |
+
pred_pose_enc = pred_pose_enc_delta
|
| 148 |
+
else:
|
| 149 |
+
pred_pose_enc = pred_pose_enc + pred_pose_enc_delta
|
| 150 |
+
|
| 151 |
+
# Apply final activation functions for translation, quaternion, and field-of-view.
|
| 152 |
+
activated_pose = activate_pose(
|
| 153 |
+
pred_pose_enc,
|
| 154 |
+
trans_act=self.trans_act,
|
| 155 |
+
quat_act=self.quat_act,
|
| 156 |
+
fl_act=self.fl_act,
|
| 157 |
+
)
|
| 158 |
+
pred_pose_enc_list.append(activated_pose)
|
| 159 |
+
|
| 160 |
+
return pred_pose_enc_list
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
|
| 164 |
+
"""
|
| 165 |
+
Modulate the input tensor using scaling and shifting parameters.
|
| 166 |
+
"""
|
| 167 |
+
# modified from https://github.com/facebookresearch/DiT/blob/796c29e532f47bba17c5b9c5eb39b9354b8b7c64/models.py#L19
|
| 168 |
+
return x * (1 + scale) + shift
|
src/model/encoder/vggt/heads/dpt_head.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# Inspired by https://github.com/DepthAnything/Depth-Anything-V2
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
from typing import List, Dict, Tuple, Union
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from .head_act import activate_head
|
| 18 |
+
from .utils import create_uv_grid, position_grid_to_embed
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DPTHead(nn.Module):
|
| 22 |
+
"""
|
| 23 |
+
DPT Head for dense prediction tasks.
|
| 24 |
+
|
| 25 |
+
This implementation follows the architecture described in "Vision Transformers for Dense Prediction"
|
| 26 |
+
(https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer
|
| 27 |
+
backbone and produces dense predictions by fusing multi-scale features.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
dim_in (int): Input dimension (channels).
|
| 31 |
+
patch_size (int, optional): Patch size. Default is 14.
|
| 32 |
+
output_dim (int, optional): Number of output channels. Default is 4.
|
| 33 |
+
activation (str, optional): Activation type. Default is "inv_log".
|
| 34 |
+
conf_activation (str, optional): Confidence activation type. Default is "expp1".
|
| 35 |
+
features (int, optional): Feature channels for intermediate representations. Default is 256.
|
| 36 |
+
out_channels (List[int], optional): Output channels for each intermediate layer.
|
| 37 |
+
intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT.
|
| 38 |
+
pos_embed (bool, optional): Whether to use positional embedding. Default is True.
|
| 39 |
+
feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False.
|
| 40 |
+
down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
dim_in: int,
|
| 46 |
+
patch_size: int = 14,
|
| 47 |
+
output_dim: int = 4,
|
| 48 |
+
activation: str = "inv_log",
|
| 49 |
+
conf_activation: str = "expp1",
|
| 50 |
+
features: int = 256,
|
| 51 |
+
out_channels: List[int] = [256, 512, 1024, 1024],
|
| 52 |
+
intermediate_layer_idx: List[int] = [4, 11, 17, 23],
|
| 53 |
+
pos_embed: bool = True,
|
| 54 |
+
feature_only: bool = False,
|
| 55 |
+
down_ratio: int = 1,
|
| 56 |
+
) -> None:
|
| 57 |
+
super(DPTHead, self).__init__()
|
| 58 |
+
self.patch_size = patch_size
|
| 59 |
+
self.activation = activation
|
| 60 |
+
self.conf_activation = conf_activation
|
| 61 |
+
self.pos_embed = pos_embed
|
| 62 |
+
self.feature_only = feature_only
|
| 63 |
+
self.down_ratio = down_ratio
|
| 64 |
+
self.intermediate_layer_idx = intermediate_layer_idx
|
| 65 |
+
|
| 66 |
+
self.norm = nn.LayerNorm(dim_in)
|
| 67 |
+
|
| 68 |
+
# Projection layers for each output channel from tokens.
|
| 69 |
+
self.projects = nn.ModuleList(
|
| 70 |
+
[
|
| 71 |
+
nn.Conv2d(
|
| 72 |
+
in_channels=dim_in,
|
| 73 |
+
out_channels=oc,
|
| 74 |
+
kernel_size=1,
|
| 75 |
+
stride=1,
|
| 76 |
+
padding=0,
|
| 77 |
+
)
|
| 78 |
+
for oc in out_channels
|
| 79 |
+
]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Resize layers for upsampling feature maps.
|
| 83 |
+
self.resize_layers = nn.ModuleList(
|
| 84 |
+
[
|
| 85 |
+
nn.ConvTranspose2d(
|
| 86 |
+
in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0
|
| 87 |
+
),
|
| 88 |
+
nn.ConvTranspose2d(
|
| 89 |
+
in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0
|
| 90 |
+
),
|
| 91 |
+
nn.Identity(),
|
| 92 |
+
nn.Conv2d(
|
| 93 |
+
in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1
|
| 94 |
+
),
|
| 95 |
+
]
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
self.scratch = _make_scratch(
|
| 99 |
+
out_channels,
|
| 100 |
+
features,
|
| 101 |
+
expand=False,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Attach additional modules to scratch.
|
| 105 |
+
self.scratch.stem_transpose = None
|
| 106 |
+
self.scratch.refinenet1 = _make_fusion_block(features)
|
| 107 |
+
self.scratch.refinenet2 = _make_fusion_block(features)
|
| 108 |
+
self.scratch.refinenet3 = _make_fusion_block(features)
|
| 109 |
+
self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False)
|
| 110 |
+
|
| 111 |
+
head_features_1 = features
|
| 112 |
+
head_features_2 = 32
|
| 113 |
+
|
| 114 |
+
if feature_only:
|
| 115 |
+
self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1)
|
| 116 |
+
else:
|
| 117 |
+
self.scratch.output_conv1 = nn.Conv2d(
|
| 118 |
+
head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1
|
| 119 |
+
)
|
| 120 |
+
conv2_in_channels = head_features_1 // 2
|
| 121 |
+
|
| 122 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 123 |
+
nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1),
|
| 124 |
+
nn.ReLU(inplace=True),
|
| 125 |
+
nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
aggregated_tokens_list: List[torch.Tensor],
|
| 131 |
+
images: torch.Tensor,
|
| 132 |
+
patch_start_idx: int,
|
| 133 |
+
frames_chunk_size: int = 8,
|
| 134 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
| 135 |
+
"""
|
| 136 |
+
Forward pass through the DPT head, supports processing by chunking frames.
|
| 137 |
+
Args:
|
| 138 |
+
aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
|
| 139 |
+
images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1].
|
| 140 |
+
patch_start_idx (int): Starting index for patch tokens in the token sequence.
|
| 141 |
+
Used to separate patch tokens from other tokens (e.g., camera or register tokens).
|
| 142 |
+
frames_chunk_size (int, optional): Number of frames to process in each chunk.
|
| 143 |
+
If None or larger than S, all frames are processed at once. Default: 8.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
Tensor or Tuple[Tensor, Tensor]:
|
| 147 |
+
- If feature_only=True: Feature maps with shape [B, S, C, H, W]
|
| 148 |
+
- Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W]
|
| 149 |
+
"""
|
| 150 |
+
B, S, _, H, W = images.shape
|
| 151 |
+
|
| 152 |
+
# If frames_chunk_size is not specified or greater than S, process all frames at once
|
| 153 |
+
if frames_chunk_size is None or frames_chunk_size >= S:
|
| 154 |
+
return self._forward_impl(aggregated_tokens_list, images, patch_start_idx)
|
| 155 |
+
|
| 156 |
+
# Otherwise, process frames in chunks to manage memory usage
|
| 157 |
+
assert frames_chunk_size > 0
|
| 158 |
+
|
| 159 |
+
# Process frames in batches
|
| 160 |
+
all_preds = []
|
| 161 |
+
all_conf = []
|
| 162 |
+
|
| 163 |
+
for frames_start_idx in range(0, S, frames_chunk_size):
|
| 164 |
+
frames_end_idx = min(frames_start_idx + frames_chunk_size, S)
|
| 165 |
+
|
| 166 |
+
# Process batch of frames
|
| 167 |
+
if self.feature_only:
|
| 168 |
+
chunk_output = self._forward_impl(
|
| 169 |
+
aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx
|
| 170 |
+
)
|
| 171 |
+
all_preds.append(chunk_output)
|
| 172 |
+
else:
|
| 173 |
+
chunk_preds, chunk_conf = self._forward_impl(
|
| 174 |
+
aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx
|
| 175 |
+
)
|
| 176 |
+
all_preds.append(chunk_preds)
|
| 177 |
+
all_conf.append(chunk_conf)
|
| 178 |
+
|
| 179 |
+
# Concatenate results along the sequence dimension
|
| 180 |
+
if self.feature_only:
|
| 181 |
+
return torch.cat(all_preds, dim=1)
|
| 182 |
+
else:
|
| 183 |
+
return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1)
|
| 184 |
+
|
| 185 |
+
def _forward_impl(
|
| 186 |
+
self,
|
| 187 |
+
aggregated_tokens_list: List[torch.Tensor],
|
| 188 |
+
images: torch.Tensor,
|
| 189 |
+
patch_start_idx: int,
|
| 190 |
+
frames_start_idx: int = None,
|
| 191 |
+
frames_end_idx: int = None,
|
| 192 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
| 193 |
+
"""
|
| 194 |
+
Implementation of the forward pass through the DPT head.
|
| 195 |
+
|
| 196 |
+
This method processes a specific chunk of frames from the sequence.
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers.
|
| 200 |
+
images (Tensor): Input images with shape [B, S, 3, H, W].
|
| 201 |
+
patch_start_idx (int): Starting index for patch tokens.
|
| 202 |
+
frames_start_idx (int, optional): Starting index for frames to process.
|
| 203 |
+
frames_end_idx (int, optional): Ending index for frames to process.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence).
|
| 207 |
+
"""
|
| 208 |
+
if frames_start_idx is not None and frames_end_idx is not None:
|
| 209 |
+
images = images[:, frames_start_idx:frames_end_idx]
|
| 210 |
+
|
| 211 |
+
B, S, _, H, W = images.shape
|
| 212 |
+
|
| 213 |
+
patch_h, patch_w = H // self.patch_size, W // self.patch_size
|
| 214 |
+
|
| 215 |
+
out = []
|
| 216 |
+
dpt_idx = 0
|
| 217 |
+
|
| 218 |
+
for layer_idx in self.intermediate_layer_idx:
|
| 219 |
+
# x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:]
|
| 220 |
+
if len(aggregated_tokens_list) > 10:
|
| 221 |
+
x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:]
|
| 222 |
+
else:
|
| 223 |
+
list_idx = self.intermediate_layer_idx.index(layer_idx)
|
| 224 |
+
x = aggregated_tokens_list[list_idx][:, :, patch_start_idx:]
|
| 225 |
+
|
| 226 |
+
# Select frames if processing a chunk
|
| 227 |
+
if frames_start_idx is not None and frames_end_idx is not None:
|
| 228 |
+
x = x[:, frames_start_idx:frames_end_idx].contiguous()
|
| 229 |
+
|
| 230 |
+
x = x.view(B * S, -1, x.shape[-1])
|
| 231 |
+
x = self.norm(x)
|
| 232 |
+
|
| 233 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
| 234 |
+
|
| 235 |
+
x = x.to(self.projects[dpt_idx].weight.dtype)
|
| 236 |
+
x = self.projects[dpt_idx](x)
|
| 237 |
+
if self.pos_embed:
|
| 238 |
+
x = self._apply_pos_embed(x, W, H)
|
| 239 |
+
|
| 240 |
+
x = self.resize_layers[dpt_idx](x)
|
| 241 |
+
|
| 242 |
+
out.append(x)
|
| 243 |
+
dpt_idx += 1
|
| 244 |
+
|
| 245 |
+
# Fuse features from multiple layers.
|
| 246 |
+
out = self.scratch_forward(out)
|
| 247 |
+
# Interpolate fused output to match target image resolution.
|
| 248 |
+
out = custom_interpolate(
|
| 249 |
+
out,
|
| 250 |
+
(int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)),
|
| 251 |
+
mode="bilinear",
|
| 252 |
+
align_corners=True,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if self.pos_embed:
|
| 256 |
+
out = self._apply_pos_embed(out, W, H)
|
| 257 |
+
|
| 258 |
+
if self.feature_only:
|
| 259 |
+
return out.view(B, S, *out.shape[1:])
|
| 260 |
+
|
| 261 |
+
out = self.scratch.output_conv2(out)
|
| 262 |
+
preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation)
|
| 263 |
+
|
| 264 |
+
preds = preds.view(B, S, *preds.shape[1:])
|
| 265 |
+
conf = conf.view(B, S, *conf.shape[1:])
|
| 266 |
+
return preds, conf
|
| 267 |
+
|
| 268 |
+
def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
|
| 269 |
+
"""
|
| 270 |
+
Apply positional embedding to tensor x.
|
| 271 |
+
"""
|
| 272 |
+
patch_w = x.shape[-1]
|
| 273 |
+
patch_h = x.shape[-2]
|
| 274 |
+
pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
|
| 275 |
+
pos_embed = position_grid_to_embed(pos_embed, x.shape[1])
|
| 276 |
+
pos_embed = pos_embed * ratio
|
| 277 |
+
pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
|
| 278 |
+
return x + pos_embed
|
| 279 |
+
|
| 280 |
+
def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor:
|
| 281 |
+
"""
|
| 282 |
+
Forward pass through the fusion blocks.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
features (List[Tensor]): List of feature maps from different layers.
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
Tensor: Fused feature map.
|
| 289 |
+
"""
|
| 290 |
+
layer_1, layer_2, layer_3, layer_4 = features
|
| 291 |
+
|
| 292 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 293 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 294 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 295 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 296 |
+
|
| 297 |
+
out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
| 298 |
+
del layer_4_rn, layer_4
|
| 299 |
+
|
| 300 |
+
out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:])
|
| 301 |
+
del layer_3_rn, layer_3
|
| 302 |
+
|
| 303 |
+
out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:])
|
| 304 |
+
del layer_2_rn, layer_2
|
| 305 |
+
|
| 306 |
+
out = self.scratch.refinenet1(out, layer_1_rn)
|
| 307 |
+
del layer_1_rn, layer_1
|
| 308 |
+
|
| 309 |
+
out = self.scratch.output_conv1(out)
|
| 310 |
+
return out
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
################################################################################
|
| 314 |
+
# Modules
|
| 315 |
+
################################################################################
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module:
|
| 319 |
+
return FeatureFusionBlock(
|
| 320 |
+
features,
|
| 321 |
+
nn.ReLU(inplace=True),
|
| 322 |
+
deconv=False,
|
| 323 |
+
bn=False,
|
| 324 |
+
expand=False,
|
| 325 |
+
align_corners=True,
|
| 326 |
+
size=size,
|
| 327 |
+
has_residual=has_residual,
|
| 328 |
+
groups=groups,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module:
|
| 333 |
+
scratch = nn.Module()
|
| 334 |
+
out_shape1 = out_shape
|
| 335 |
+
out_shape2 = out_shape
|
| 336 |
+
out_shape3 = out_shape
|
| 337 |
+
if len(in_shape) >= 4:
|
| 338 |
+
out_shape4 = out_shape
|
| 339 |
+
|
| 340 |
+
if expand:
|
| 341 |
+
out_shape1 = out_shape
|
| 342 |
+
out_shape2 = out_shape * 2
|
| 343 |
+
out_shape3 = out_shape * 4
|
| 344 |
+
if len(in_shape) >= 4:
|
| 345 |
+
out_shape4 = out_shape * 8
|
| 346 |
+
|
| 347 |
+
scratch.layer1_rn = nn.Conv2d(
|
| 348 |
+
in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 349 |
+
)
|
| 350 |
+
scratch.layer2_rn = nn.Conv2d(
|
| 351 |
+
in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 352 |
+
)
|
| 353 |
+
scratch.layer3_rn = nn.Conv2d(
|
| 354 |
+
in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 355 |
+
)
|
| 356 |
+
if len(in_shape) >= 4:
|
| 357 |
+
scratch.layer4_rn = nn.Conv2d(
|
| 358 |
+
in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 359 |
+
)
|
| 360 |
+
return scratch
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class ResidualConvUnit(nn.Module):
|
| 364 |
+
"""Residual convolution module."""
|
| 365 |
+
|
| 366 |
+
def __init__(self, features, activation, bn, groups=1):
|
| 367 |
+
"""Init.
|
| 368 |
+
|
| 369 |
+
Args:
|
| 370 |
+
features (int): number of features
|
| 371 |
+
"""
|
| 372 |
+
super().__init__()
|
| 373 |
+
|
| 374 |
+
self.bn = bn
|
| 375 |
+
self.groups = groups
|
| 376 |
+
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 377 |
+
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 378 |
+
|
| 379 |
+
self.norm1 = None
|
| 380 |
+
self.norm2 = None
|
| 381 |
+
|
| 382 |
+
self.activation = activation
|
| 383 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 384 |
+
|
| 385 |
+
def forward(self, x):
|
| 386 |
+
"""Forward pass.
|
| 387 |
+
|
| 388 |
+
Args:
|
| 389 |
+
x (tensor): input
|
| 390 |
+
|
| 391 |
+
Returns:
|
| 392 |
+
tensor: output
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
out = self.activation(x)
|
| 396 |
+
out = self.conv1(out)
|
| 397 |
+
if self.norm1 is not None:
|
| 398 |
+
out = self.norm1(out)
|
| 399 |
+
|
| 400 |
+
out = self.activation(out)
|
| 401 |
+
out = self.conv2(out)
|
| 402 |
+
if self.norm2 is not None:
|
| 403 |
+
out = self.norm2(out)
|
| 404 |
+
|
| 405 |
+
return self.skip_add.add(out, x)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class FeatureFusionBlock(nn.Module):
|
| 409 |
+
"""Feature fusion block."""
|
| 410 |
+
|
| 411 |
+
def __init__(
|
| 412 |
+
self,
|
| 413 |
+
features,
|
| 414 |
+
activation,
|
| 415 |
+
deconv=False,
|
| 416 |
+
bn=False,
|
| 417 |
+
expand=False,
|
| 418 |
+
align_corners=True,
|
| 419 |
+
size=None,
|
| 420 |
+
has_residual=True,
|
| 421 |
+
groups=1,
|
| 422 |
+
):
|
| 423 |
+
"""Init.
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
features (int): number of features
|
| 427 |
+
"""
|
| 428 |
+
super(FeatureFusionBlock, self).__init__()
|
| 429 |
+
|
| 430 |
+
self.deconv = deconv
|
| 431 |
+
self.align_corners = align_corners
|
| 432 |
+
self.groups = groups
|
| 433 |
+
self.expand = expand
|
| 434 |
+
out_features = features
|
| 435 |
+
if self.expand == True:
|
| 436 |
+
out_features = features // 2
|
| 437 |
+
|
| 438 |
+
self.out_conv = nn.Conv2d(
|
| 439 |
+
features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if has_residual:
|
| 443 |
+
self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups)
|
| 444 |
+
|
| 445 |
+
self.has_residual = has_residual
|
| 446 |
+
self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups)
|
| 447 |
+
|
| 448 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 449 |
+
self.size = size
|
| 450 |
+
|
| 451 |
+
def forward(self, *xs, size=None):
|
| 452 |
+
"""Forward pass.
|
| 453 |
+
|
| 454 |
+
Returns:
|
| 455 |
+
tensor: output
|
| 456 |
+
"""
|
| 457 |
+
output = xs[0]
|
| 458 |
+
|
| 459 |
+
if self.has_residual:
|
| 460 |
+
res = self.resConfUnit1(xs[1])
|
| 461 |
+
output = self.skip_add.add(output, res)
|
| 462 |
+
|
| 463 |
+
output = self.resConfUnit2(output)
|
| 464 |
+
|
| 465 |
+
if (size is None) and (self.size is None):
|
| 466 |
+
modifier = {"scale_factor": 2}
|
| 467 |
+
elif size is None:
|
| 468 |
+
modifier = {"size": self.size}
|
| 469 |
+
else:
|
| 470 |
+
modifier = {"size": size}
|
| 471 |
+
|
| 472 |
+
output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
|
| 473 |
+
output = self.out_conv(output)
|
| 474 |
+
|
| 475 |
+
return output
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def custom_interpolate(
|
| 479 |
+
x: torch.Tensor,
|
| 480 |
+
size: Tuple[int, int] = None,
|
| 481 |
+
scale_factor: float = None,
|
| 482 |
+
mode: str = "bilinear",
|
| 483 |
+
align_corners: bool = True,
|
| 484 |
+
) -> torch.Tensor:
|
| 485 |
+
"""
|
| 486 |
+
Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate.
|
| 487 |
+
"""
|
| 488 |
+
if size is None:
|
| 489 |
+
size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor))
|
| 490 |
+
|
| 491 |
+
INT_MAX = 1610612736
|
| 492 |
+
|
| 493 |
+
input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
|
| 494 |
+
|
| 495 |
+
if input_elements > INT_MAX:
|
| 496 |
+
chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
|
| 497 |
+
interpolated_chunks = [
|
| 498 |
+
nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks
|
| 499 |
+
]
|
| 500 |
+
x = torch.cat(interpolated_chunks, dim=0)
|
| 501 |
+
return x.contiguous()
|
| 502 |
+
else:
|
| 503 |
+
return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners)
|
src/model/encoder/vggt/heads/head_act.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"):
|
| 13 |
+
"""
|
| 14 |
+
Activate pose parameters with specified activation functions.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length]
|
| 18 |
+
trans_act: Activation type for translation component
|
| 19 |
+
quat_act: Activation type for quaternion component
|
| 20 |
+
fl_act: Activation type for focal length component
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
Activated pose parameters tensor
|
| 24 |
+
"""
|
| 25 |
+
T = pred_pose_enc[..., :3]
|
| 26 |
+
quat = pred_pose_enc[..., 3:7]
|
| 27 |
+
fl = pred_pose_enc[..., 7:] # or fov
|
| 28 |
+
|
| 29 |
+
T = base_pose_act(T, trans_act)
|
| 30 |
+
quat = base_pose_act(quat, quat_act)
|
| 31 |
+
fl = base_pose_act(fl, fl_act) # or fov
|
| 32 |
+
|
| 33 |
+
pred_pose_enc = torch.cat([T, quat, fl], dim=-1)
|
| 34 |
+
|
| 35 |
+
return pred_pose_enc
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def base_pose_act(pose_enc, act_type="linear"):
|
| 39 |
+
"""
|
| 40 |
+
Apply basic activation function to pose parameters.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
pose_enc: Tensor containing encoded pose parameters
|
| 44 |
+
act_type: Activation type ("linear", "inv_log", "exp", "relu")
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
Activated pose parameters
|
| 48 |
+
"""
|
| 49 |
+
if act_type == "linear":
|
| 50 |
+
return pose_enc
|
| 51 |
+
elif act_type == "inv_log":
|
| 52 |
+
return inverse_log_transform(pose_enc)
|
| 53 |
+
elif act_type == "exp":
|
| 54 |
+
return torch.exp(pose_enc)
|
| 55 |
+
elif act_type == "relu":
|
| 56 |
+
return F.relu(pose_enc)
|
| 57 |
+
else:
|
| 58 |
+
raise ValueError(f"Unknown act_type: {act_type}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def activate_head(out, activation="norm_exp", conf_activation="expp1"):
|
| 62 |
+
"""
|
| 63 |
+
Process network output to extract 3D points and confidence values.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
out: Network output tensor (B, C, H, W)
|
| 67 |
+
activation: Activation type for 3D points
|
| 68 |
+
conf_activation: Activation type for confidence values
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
Tuple of (3D points tensor, confidence tensor)
|
| 72 |
+
"""
|
| 73 |
+
# Move channels from last dim to the 4th dimension => (B, H, W, C)
|
| 74 |
+
fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected
|
| 75 |
+
|
| 76 |
+
# Split into xyz (first C-1 channels) and confidence (last channel)
|
| 77 |
+
xyz = fmap[:, :, :, :-1]
|
| 78 |
+
conf = fmap[:, :, :, -1]
|
| 79 |
+
|
| 80 |
+
if activation == "norm_exp":
|
| 81 |
+
d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8)
|
| 82 |
+
xyz_normed = xyz / d
|
| 83 |
+
pts3d = xyz_normed * torch.expm1(d)
|
| 84 |
+
elif activation == "norm":
|
| 85 |
+
pts3d = xyz / xyz.norm(dim=-1, keepdim=True)
|
| 86 |
+
elif activation == "exp":
|
| 87 |
+
pts3d = torch.exp(xyz)
|
| 88 |
+
elif activation == "relu":
|
| 89 |
+
pts3d = F.relu(xyz)
|
| 90 |
+
elif activation == "inv_log":
|
| 91 |
+
pts3d = inverse_log_transform(xyz)
|
| 92 |
+
elif activation == "xy_inv_log":
|
| 93 |
+
xy, z = xyz.split([2, 1], dim=-1)
|
| 94 |
+
z = inverse_log_transform(z)
|
| 95 |
+
pts3d = torch.cat([xy * z, z], dim=-1)
|
| 96 |
+
elif activation == "sigmoid":
|
| 97 |
+
pts3d = torch.sigmoid(xyz)
|
| 98 |
+
elif activation == "linear":
|
| 99 |
+
pts3d = xyz
|
| 100 |
+
else:
|
| 101 |
+
raise ValueError(f"Unknown activation: {activation}")
|
| 102 |
+
|
| 103 |
+
if conf_activation == "expp1":
|
| 104 |
+
conf_out = 1 + conf.exp()
|
| 105 |
+
elif conf_activation == "expp0":
|
| 106 |
+
conf_out = conf.exp()
|
| 107 |
+
elif conf_activation == "sigmoid":
|
| 108 |
+
conf_out = torch.sigmoid(conf)
|
| 109 |
+
else:
|
| 110 |
+
raise ValueError(f"Unknown conf_activation: {conf_activation}")
|
| 111 |
+
|
| 112 |
+
return pts3d, conf_out
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def inverse_log_transform(y):
|
| 116 |
+
"""
|
| 117 |
+
Apply inverse log transform: sign(y) * (exp(|y|) - 1)
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
y: Input tensor
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
Transformed tensor
|
| 124 |
+
"""
|
| 125 |
+
return torch.sign(y) * (torch.expm1(torch.abs(y)))
|
src/model/encoder/vggt/heads/track_head.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from .dpt_head import DPTHead
|
| 9 |
+
from .track_modules.base_track_predictor import BaseTrackerPredictor
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TrackHead(nn.Module):
|
| 13 |
+
"""
|
| 14 |
+
Track head that uses DPT head to process tokens and BaseTrackerPredictor for tracking.
|
| 15 |
+
The tracking is performed iteratively, refining predictions over multiple iterations.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
dim_in,
|
| 21 |
+
patch_size=14,
|
| 22 |
+
features=128,
|
| 23 |
+
iters=4,
|
| 24 |
+
predict_conf=True,
|
| 25 |
+
stride=2,
|
| 26 |
+
corr_levels=7,
|
| 27 |
+
corr_radius=4,
|
| 28 |
+
hidden_size=384,
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Initialize the TrackHead module.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
dim_in (int): Input dimension of tokens from the backbone.
|
| 35 |
+
patch_size (int): Size of image patches used in the vision transformer.
|
| 36 |
+
features (int): Number of feature channels in the feature extractor output.
|
| 37 |
+
iters (int): Number of refinement iterations for tracking predictions.
|
| 38 |
+
predict_conf (bool): Whether to predict confidence scores for tracked points.
|
| 39 |
+
stride (int): Stride value for the tracker predictor.
|
| 40 |
+
corr_levels (int): Number of correlation pyramid levels
|
| 41 |
+
corr_radius (int): Radius for correlation computation, controlling the search area.
|
| 42 |
+
hidden_size (int): Size of hidden layers in the tracker network.
|
| 43 |
+
"""
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
self.patch_size = patch_size
|
| 47 |
+
|
| 48 |
+
# Feature extractor based on DPT architecture
|
| 49 |
+
# Processes tokens into feature maps for tracking
|
| 50 |
+
self.feature_extractor = DPTHead(
|
| 51 |
+
dim_in=dim_in,
|
| 52 |
+
patch_size=patch_size,
|
| 53 |
+
features=features,
|
| 54 |
+
feature_only=True, # Only output features, no activation
|
| 55 |
+
down_ratio=2, # Reduces spatial dimensions by factor of 2
|
| 56 |
+
pos_embed=False,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Tracker module that predicts point trajectories
|
| 60 |
+
# Takes feature maps and predicts coordinates and visibility
|
| 61 |
+
self.tracker = BaseTrackerPredictor(
|
| 62 |
+
latent_dim=features, # Match the output_dim of feature extractor
|
| 63 |
+
predict_conf=predict_conf,
|
| 64 |
+
stride=stride,
|
| 65 |
+
corr_levels=corr_levels,
|
| 66 |
+
corr_radius=corr_radius,
|
| 67 |
+
hidden_size=hidden_size,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
self.iters = iters
|
| 71 |
+
|
| 72 |
+
def forward(self, aggregated_tokens_list, images, patch_start_idx, query_points=None, iters=None):
|
| 73 |
+
"""
|
| 74 |
+
Forward pass of the TrackHead.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
aggregated_tokens_list (list): List of aggregated tokens from the backbone.
|
| 78 |
+
images (torch.Tensor): Input images of shape (B, S, C, H, W) where:
|
| 79 |
+
B = batch size, S = sequence length.
|
| 80 |
+
patch_start_idx (int): Starting index for patch tokens.
|
| 81 |
+
query_points (torch.Tensor, optional): Initial query points to track.
|
| 82 |
+
If None, points are initialized by the tracker.
|
| 83 |
+
iters (int, optional): Number of refinement iterations. If None, uses self.iters.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
tuple:
|
| 87 |
+
- coord_preds (torch.Tensor): Predicted coordinates for tracked points.
|
| 88 |
+
- vis_scores (torch.Tensor): Visibility scores for tracked points.
|
| 89 |
+
- conf_scores (torch.Tensor): Confidence scores for tracked points (if predict_conf=True).
|
| 90 |
+
"""
|
| 91 |
+
B, S, _, H, W = images.shape
|
| 92 |
+
|
| 93 |
+
# Extract features from tokens
|
| 94 |
+
# feature_maps has shape (B, S, C, H//2, W//2) due to down_ratio=2
|
| 95 |
+
feature_maps = self.feature_extractor(aggregated_tokens_list, images, patch_start_idx)
|
| 96 |
+
|
| 97 |
+
# Use default iterations if not specified
|
| 98 |
+
if iters is None:
|
| 99 |
+
iters = self.iters
|
| 100 |
+
|
| 101 |
+
# Perform tracking using the extracted features
|
| 102 |
+
coord_preds, vis_scores, conf_scores = self.tracker(
|
| 103 |
+
query_points=query_points,
|
| 104 |
+
fmaps=feature_maps,
|
| 105 |
+
iters=iters,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return coord_preds, vis_scores, conf_scores
|