| 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 | SceneScript Point Cloud Encoder |
| 9 | |
| 10 | Reference: https://github.com/facebookresearch/scenescript/blob/main/src/networks/encoder.py |
| 11 | |
| 12 | @inproceedings{avetisyan2024scenescript, |
| 13 | title = {SceneScript: Reconstructing Scenes With An Autoregressive Structured Language Model}, |
| 14 | author = {Avetisyan, Armen and Xie, Christopher and Howard-Jenkins, Henry and Yang, Tsun-Yi and Aroudj, Samir and Patra, Suvam and Zhang, Fuyang and Frost, Duncan and Holland, Luke and Orme, Campbell and Engel, Jakob and Miller, Edward and Newcombe, Richard and Balntas, Vasileios}, |
| 15 | booktitle = {European Conference on Computer Vision (ECCV)}, |
| 16 | year = {2024}, |
| 17 | } |
| 18 | """ |
| 19 | |
| 20 | import torch |
| 21 | import torchsparse |
| 22 | import torchsparse.nn as spnn |
| 23 | from einops import repeat |
| 24 | |
| 25 | from torch import nn |
| 26 | from torch.nn import functional as F |
| 27 | |
| 28 | |
| 29 | def make_conv3d_sparse( |
| 30 | channels_in, |
| 31 | channels_out, |
| 32 | kernel_size=3, |
| 33 | num_groups=8, |
| 34 | activation=spnn.ReLU, |
| 35 | ): |
| 36 | num_groups = min(num_groups, channels_out) |
| 37 | block = nn.Sequential( |
| 38 | spnn.Conv3d(channels_in, channels_out, kernel_size=kernel_size, stride=1), |
| 39 | spnn.GroupNorm(num_groups, channels_out), |
| 40 | activation(inplace=True), |
| 41 | ) |
| 42 | return block |
| 43 | |
| 44 | |
| 45 | def make_conv3d_downscale_sparse( |
| 46 | channels_in, |
| 47 | channels_out, |
| 48 | num_groups=8, |
| 49 | activation=spnn.ReLU, |
| 50 | ): |
| 51 | num_groups = min(num_groups, channels_out) |
| 52 | block = nn.Sequential( |
| 53 | spnn.Conv3d(channels_in, channels_out, kernel_size=2, stride=2), |
| 54 | spnn.GroupNorm(num_groups, channels_out), |
| 55 | activation(inplace=True), |
| 56 | ) |
| 57 | return block |
| 58 | |
| 59 | |
| 60 | class ResBlockSparse(nn.Module): |
| 61 | def __init__( |
| 62 | self, |
| 63 | channels, |
| 64 | num_groups=8, |
| 65 | activation=spnn.ReLU, |
| 66 | ): |
| 67 | super().__init__() |
| 68 | |
| 69 | self.block0 = make_conv3d_sparse( |
| 70 | channels, channels, num_groups=num_groups, activation=activation |
| 71 | ) |
| 72 | self.block1 = make_conv3d_sparse( |
| 73 | channels, channels, num_groups=num_groups, activation=activation |
| 74 | ) |
| 75 | |
| 76 | def forward(self, x): |
| 77 | out = self.block0(x) |
| 78 | out = self.block1(out) |
| 79 | return x + out |
| 80 | |
| 81 | |
| 82 | def index_batched_sparse_tensor(sparse_tensor, index): |
| 83 | """Index into a batched torchsparse.SparseTensor. |
| 84 | |
| 85 | Args: |
| 86 | sparse_tensor: a torchsparse.SparseTensor that is the output of |
| 87 | torchsparse.utils.collate.sparse_collate(). |
| 88 | index: int. |
| 89 | |
| 90 | Returns: |
| 91 | torchsparse.SparseTensor with no batch dimension. |
| 92 | """ |
| 93 | batch_mask = sparse_tensor.C[:, 0] == index |
| 94 | coords = sparse_tensor.C[batch_mask, 1:] # Get rid of batch dim |
| 95 | feats = sparse_tensor.F[batch_mask] |
| 96 | return torchsparse.SparseTensor( |
| 97 | coords=coords, |
| 98 | feats=feats, |
| 99 | stride=sparse_tensor.s, |
| 100 | ) |
| 101 | |
| 102 | |
| 103 | def sparse_uncollate(sparse_tensor): |
| 104 | """Un-Collate a batched torchsparse.SparseTensor. |
| 105 | |
| 106 | Args: |
| 107 | sparse_tensor: a torchsparse.SparseTensor that is the output of |
| 108 | torchsparse.utils.collate.sparse_collate(). |
| 109 | |
| 110 | Returns: |
| 111 | List[torchsparse.SparseTensor]. |
| 112 | """ |
| 113 | batch_size = sparse_tensor.C[:, 0].max() + 1 |
| 114 | |
| 115 | sparse_tensor_list = [] |
| 116 | for b in range(batch_size): |
| 117 | sparse_tensor_list.append(index_batched_sparse_tensor(sparse_tensor, b)) |
| 118 | return sparse_tensor_list |
| 119 | |
| 120 | |
| 121 | def vox_to_sequence(sparse_tensor): |
| 122 | """Compute sequence from sparse point cloud. |
| 123 | |
| 124 | Args: |
| 125 | sparse_tensor: torchsparse.SparseTensor. |
| 126 | |
| 127 | Returns: |
| 128 | Dict with the following keys: |
| 129 | seq: [B, maxlen, C] torch.FloatTensor. |
| 130 | coords: [B, maxlen, 3] torch.IntTensor. To be used with embeddings for Transformers. |
| 131 | mask: [B, maxlen] torch.BoolTensor. To be used with Transformers. |
| 132 | """ |
| 133 | sparse_tensor_list = sparse_uncollate(sparse_tensor) |
| 134 | batch_size = len(sparse_tensor_list) |
| 135 | channels = sparse_tensor_list[0].F.shape[-1] |
| 136 | maxlen = max([x.C.shape[0] for x in sparse_tensor_list]) |
| 137 | |
| 138 | seq = torch.zeros( |
| 139 | (batch_size, maxlen, channels), |
| 140 | dtype=sparse_tensor.F.dtype, |
| 141 | device=sparse_tensor.F.device, |
| 142 | ) |
| 143 | coords = torch.zeros( |
| 144 | (batch_size, maxlen, 3), |
| 145 | dtype=sparse_tensor.C.dtype, |
| 146 | device=sparse_tensor.C.device, |
| 147 | ) |
| 148 | mask = torch.ones( |
| 149 | (batch_size, maxlen), |
| 150 | dtype=torch.bool, |
| 151 | device=sparse_tensor.F.device, |
| 152 | ) |
| 153 | for i in range(batch_size): |
| 154 | sparse_tensor = sparse_tensor_list[i] |
| 155 | |
| 156 | # Get coords (divided by stride, so its in {0, 1, ...}) |
| 157 | coords_i = sparse_tensor.C # [N_points_i, 3] |
| 158 | coords_num = coords_i.shape[0] |
| 159 | assert coords_num <= maxlen, f"coords_num: {coords_num} is too high..." |
| 160 | |
| 161 | # Get features |
| 162 | feats = sparse_tensor.F # [N_points_i, C] |
| 163 | |
| 164 | # Pad and save |
| 165 | pad = maxlen - coords_num |
| 166 | |
| 167 | feats = F.pad(feats.T, (0, pad), value=0).T # [maxlen, C] |
| 168 | seq[i] = feats |
| 169 | |
| 170 | coords_i = F.pad(coords_i.T, (0, pad), value=0).T # [maxlen, 3] |
| 171 | coords[i] = coords_i |
| 172 | |
| 173 | mask[i, :coords_num] = False |
| 174 | |
| 175 | return { |
| 176 | "seq": seq, |
| 177 | "coords": coords, |
| 178 | "mask": mask, |
| 179 | } |
| 180 | |
| 181 | |
| 182 | def fourier_encode_vector(vec, num_bands=10, sample_rate=60): |
| 183 | """Fourier encode a vector. |
| 184 | |
| 185 | Args: |
| 186 | vec: [B, N, D] torch.FloatTensor. |
| 187 | num_bands: int. |
| 188 | sample_rate: int. |
| 189 | |
| 190 | Returns: |
| 191 | [B, N, (2 * num_bands + 1) * D] torch.FloatTensor. |
| 192 | """ |
| 193 | b, n, d = vec.shape |
| 194 | samples = torch.linspace(1, sample_rate / 2, num_bands).to(vec.device) * torch.pi |
| 195 | sines = torch.sin(samples[None, None, :, None] * vec[:, :, None, :]) |
| 196 | cosines = torch.cos(samples[None, None, :, None] * vec[:, :, None, :]) |
| 197 | |
| 198 | encoding = torch.stack([sines, cosines], dim=3).reshape(b, n, 2 * num_bands, d) |
| 199 | encoding = torch.cat([vec[:, :, None, :], encoding], dim=2) |
| 200 | return encoding.flatten(2) |
| 201 | |
| 202 | |
| 203 | class ResNet3DSparse(nn.Module): |
| 204 | def __init__(self, dim_in, dim_out, layers): |
| 205 | super().__init__() |
| 206 | |
| 207 | self.stem = nn.Sequential( |
| 208 | make_conv3d_sparse(dim_in, layers[0], kernel_size=7), |
| 209 | ResBlockSparse(layers[0]), |
| 210 | ) |
| 211 | |
| 212 | # Number of down-convs is len(layers) - 1 |
| 213 | blocks = [] |
| 214 | for i in range(len(layers) - 1): |
| 215 | blocks.append( |
| 216 | nn.Sequential( |
| 217 | make_conv3d_downscale_sparse(layers[i], layers[i + 1]), |
| 218 | ResBlockSparse(layers[i + 1]), |
| 219 | ResBlockSparse(layers[i + 1]), |
| 220 | ) |
| 221 | ) |
| 222 | self.blocks = nn.Sequential(*blocks) |
| 223 | |
| 224 | self.bottleneck = nn.Sequential( |
| 225 | nn.Linear(layers[-1], 2 * layers[-1]), |
| 226 | nn.GroupNorm(8, 2 * layers[-1]), # 8 is default num_groups for GroupNorm |
| 227 | nn.ReLU(inplace=True), |
| 228 | nn.Linear(2 * layers[-1], dim_out), |
| 229 | ) |
| 230 | |
| 231 | def forward(self, x): |
| 232 | out = self.stem(x) |
| 233 | out = self.blocks(out) |
| 234 | out.F = self.bottleneck(out.F) # bottleneck applied to features only |
| 235 | return out |
| 236 | |
| 237 | |
| 238 | class PointCloudEncoder(nn.Module): |
| 239 | def __init__( |
| 240 | self, |
| 241 | input_channels, |
| 242 | d_model, |
| 243 | conv_layers, |
| 244 | num_bins, |
| 245 | ): |
| 246 | """Point Cloud Encoder. |
| 247 | |
| 248 | Args: |
| 249 | input_channels: int. |
| 250 | d_model: int. |
| 251 | conv_layers: List[int]. |
| 252 | num_bins: int. |
| 253 | """ |
| 254 | |
| 255 | super().__init__() |
| 256 | |
| 257 | self.sparse_resnet = ResNet3DSparse( |
| 258 | dim_in=input_channels, |
| 259 | dim_out=d_model, |
| 260 | layers=conv_layers, |
| 261 | ) |
| 262 | downconvs = len(conv_layers) - 1 |
| 263 | res_reduction = 2**downconvs # voxel resolution reduction |
| 264 | self.reduced_grid_size = int(num_bins / res_reduction) |
| 265 | self.input_proj = nn.Linear(d_model + 63, d_model) # 63 for fourier encoding |
| 266 | |
| 267 | # the following is a legacy parameter |
| 268 | self.extra_embedding = nn.Parameter(torch.empty(d_model).normal_(std=0.02)) |
| 269 | |
| 270 | def forward(self, point_cloud: torchsparse.SparseTensor): |
| 271 | """Forward function. |
| 272 | |
| 273 | Args: |
| 274 | point_cloud: torchsparse.SparseTensor. |
| 275 | |
| 276 | Returns: a Dict with the following keys: |
| 277 | context: [B, maxlen, d_model] torch.FloatTensor. |
| 278 | context_mask: [B, maxlen] torch.BoolTensor. True means ignore. |
| 279 | """ |
| 280 | outputs = self.sparse_resnet(point_cloud) |
| 281 | outputs = vox_to_sequence(outputs) |
| 282 | |
| 283 | context = outputs["seq"] |
| 284 | context_mask = outputs["mask"] |
| 285 | |
| 286 | coords = outputs["coords"] |
| 287 | coords_normalised = coords / (self.reduced_grid_size - 1) |
| 288 | encoded_coords = fourier_encode_vector(coords_normalised) |
| 289 | |
| 290 | context = torch.cat([context, encoded_coords], dim=-1) |
| 291 | context = self.input_proj(context) |
| 292 | |
| 293 | # legacy parameter |
| 294 | context = context + repeat(self.extra_embedding, "d -> 1 1 d") |
| 295 | |
| 296 | return { |
| 297 | "context": context, |
| 298 | "context_mask": context_mask, |
| 299 | } |