Spaces:
Running on Zero
Running on Zero
File size: 7,122 Bytes
7547a6b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | import torch
from einops import repeat
from dataclasses import fields, is_dataclass
from functools import wraps
# CUDA graphs cannot capture torch.linalg.inv. The online step graph switches this on.
_graph_safe_inverse = False
def graph_safe_inverse(enabled: bool) -> bool:
"""Switch batch_unproject to tensor inverses a CUDA graph can capture. Returns the previous value."""
global _graph_safe_inverse
previous = _graph_safe_inverse
_graph_safe_inverse = enabled
return previous
def _invert_3x3(matrix: torch.Tensor) -> torch.Tensor:
a, b, c = matrix[..., 0, 0], matrix[..., 0, 1], matrix[..., 0, 2]
d, e, f = matrix[..., 1, 0], matrix[..., 1, 1], matrix[..., 1, 2]
g, h, i = matrix[..., 2, 0], matrix[..., 2, 1], matrix[..., 2, 2]
A = e * i - f * h
B = f * g - d * i
C = d * h - e * g
D = c * h - b * i
E = a * i - c * g
F = b * g - a * h
G = b * f - c * e
H = c * d - a * f
I = a * e - b * d
det = a * A + b * B + c * C
return torch.stack(
(
torch.stack((A, D, G), dim=-1),
torch.stack((B, E, H), dim=-1),
torch.stack((C, F, I), dim=-1),
),
dim=-2,
) / det[..., None, None]
def _invert_rigid(matrix: torch.Tensor) -> torch.Tensor:
rotation = matrix[..., :3, :3]
translation = matrix[..., :3, 3:]
rotation_t = rotation.transpose(-1, -2)
out = matrix.new_zeros(matrix.shape)
out[..., :3, :3] = rotation_t
out[..., :3, 3:] = -rotation_t.matmul(translation)
out[..., 3, 3] = 1
return out
def convert_tensor(x, allow_cast: bool):
if not isinstance(x, torch.Tensor):
return x
if x.dtype not in [torch.float16, torch.bfloat16]:
return x
if allow_cast:
return x.to(dtype=torch.float32)
else:
raise TypeError(f"Tensor of dtype {x.dtype} is not allowed. Expected float32.")
def convert_tensor_struct(data, allow_cast: bool):
if isinstance(data, torch.Tensor):
return convert_tensor(data, allow_cast)
elif isinstance(data, list):
return [convert_tensor_struct(item, allow_cast) for item in data]
elif isinstance(data, tuple):
return tuple(convert_tensor_struct(item, allow_cast) for item in data)
elif isinstance(data, dict):
return {key: convert_tensor_struct(value, allow_cast) for key, value in data.items()}
elif is_dataclass(data):
return type(data)(**{field.name: convert_tensor_struct(getattr(data, field.name), allow_cast) for field in fields(data)})
else:
return data
def ensure_float32(allow_cast: bool = True):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
new_args = tuple(convert_tensor_struct(arg, allow_cast) for arg in args)
new_kwargs = {key: convert_tensor_struct(value, allow_cast) for key, value in kwargs.items()}
with torch.autocast(device_type='cuda', enabled=False):
return convert_tensor_struct(func(*new_args, **new_kwargs), True)
return wrapper
return decorator
def cast_float32():
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
new_args = tuple(convert_tensor_struct(arg, True) for arg in args)
new_kwargs = {key: convert_tensor_struct(value, True) for key, value in kwargs.items()}
return convert_tensor_struct(func(*new_args, **new_kwargs), True)
return wrapper
return decorator
@ensure_float32(allow_cast=False)
def batch_unproject(depth: torch.Tensor, intrinsic: torch.Tensor, extrinsic: torch.Tensor) -> torch.Tensor:
if depth.ndim == 4:
pcds = batch_unproject(
depth.view(-1, *depth.shape[2:]),
intrinsic.view(-1, *intrinsic.shape[2:]),
extrinsic.view(-1, *extrinsic.shape[2:]),
)
return pcds.reshape(depth.shape[:2] + pcds.shape[1:])
assert depth.ndim == 3, "depth must be a 3D array"
t, h, w = depth.shape
assert intrinsic.shape == (t, 3, 3), f"intrinsic must be a 3D array of shape (t, 3, 3), got {intrinsic.shape}"
assert extrinsic.shape == (t, 4, 4), f"extrinsic must be a 3D array of shape (t, 4, 4), got {extrinsic.shape}"
# Generate 3D point cloud in world coordinates
v, u = torch.meshgrid(torch.arange(h, device=depth.device), torch.arange(w, device=depth.device), indexing='ij')
uv_homogeneous = torch.stack((u, v, torch.ones_like(u)), dim=-1).float()
K_inv = _invert_3x3(intrinsic) if _graph_safe_inverse else torch.linalg.inv(intrinsic)
camera_coords = torch.einsum("nij, xyj -> nxyi", K_inv, uv_homogeneous)
camera_coords = camera_coords * depth[..., None]
camera_coords = torch.cat((camera_coords, torch.ones_like(camera_coords[..., :1])), dim=-1)
inv_extrinsics = _invert_rigid(extrinsic) if _graph_safe_inverse else torch.linalg.inv(extrinsic)
world_coordinates = torch.einsum("nij, nxyj -> nxyi", inv_extrinsics, camera_coords)
return world_coordinates[..., :3].permute(0, 3, 1, 2)
@ensure_float32(allow_cast=False)
def batch_project(
pts3d: torch.Tensor,
intrinsics: torch.Tensor,
extrinsics: torch.Tensor,
) -> torch.Tensor:
pts3d_homogeneous = torch.cat((pts3d, torch.ones_like(pts3d[..., :1])), dim=-1) # (n, 4)
pts_camera_homogeneous = torch.einsum("...ij, ...j -> ...i", extrinsics, pts3d_homogeneous) # (n, 4)
pts_camera = pts_camera_homogeneous[..., :3] / pts_camera_homogeneous[..., 3:] # (n, 3)
pts_image_homogeneous = torch.einsum("...ij, ...j -> ...i", intrinsics, pts_camera) # (n, 3)
pts_image = pts_image_homogeneous[..., :2] / pts_image_homogeneous[..., 2:] # (n, 2)
return pts_image
def project_queries(queries_3d: torch.Tensor, intrinsics: torch.Tensor, extrinsics: torch.Tensor) -> torch.Tensor:
B, N, _ = queries_3d.shape
T = intrinsics.shape[1]
assert extrinsics.shape == (B, T, 4, 4), f"extrinsics should have shape (B, T, 4, 4), got {extrinsics.shape}"
assert intrinsics.shape == (B, T, 3, 3), f"intrinsics should have shape (B, T, 3, 3), got {intrinsics.shape}"
assert queries_3d.shape == (B, N, 4), f"queries_3d should have shape (B, N, 4), got {queries_3d.shape}"
query_times = queries_3d[..., 0].to(torch.int64) # (B, N)
batch_indices = repeat(torch.arange(B, device=queries_3d.device), "b -> b n", n=N)
intrinsics = intrinsics[batch_indices, query_times] # (B, N, 3, 3)
extrinsics = extrinsics[batch_indices, query_times] # (B, N, 4, 4)
queries_2d = batch_project(queries_3d[..., 1:].reshape(B * N, 3), intrinsics.reshape(B * N, 3, 3), extrinsics.reshape(B * N, 4, 4)).reshape(B, N, 2)
return torch.cat((query_times[..., None], queries_2d), dim=-1)
@ensure_float32(allow_cast=False)
def apply_homo_transform(coords: torch.Tensor, transform: torch.Tensor):
coords_homo = torch.cat([coords, torch.ones_like(coords[..., :1])], dim=-1)
coords_transformed_homo = torch.einsum("...ij,...j->...i", transform, coords_homo)
coords_transformed = coords_transformed_homo[..., :-1] / coords_transformed_homo[..., -1:]
return coords_transformed
|