Spaces:
Running
Running
File size: 42,958 Bytes
684943d |
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 |
#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact [email protected]
#
import os
import numpy as np
import torch
from plyfile import PlyData, PlyElement
from pytorch3d.transforms import quaternion_to_matrix
from simple_knn._C import distCUDA2
from torch import nn
from field_construction.scene.per_point_adam import PerPointAdam
from field_construction.utils.general_utils import (build_rotation,
build_scaling,
build_scaling_rotation,
get_expon_lr_func,
inverse_sigmoid,
strip_symmetric)
from field_construction.utils.graphics_utils import BasicPointCloud
from field_construction.utils.pose_utils import get_tensor_from_camera
from field_construction.utils.sh_utils import RGB2SH
from field_construction.utils.system_utils import mkdir_p
def dilate(bin_img, ksize=5):
pad = (ksize - 1) // 2
bin_img = torch.nn.functional.pad(bin_img, pad=[pad, pad, pad, pad], mode='reflect')
out = torch.nn.functional.max_pool2d(bin_img, kernel_size=ksize, stride=1, padding=0)
return out
def erode(bin_img, ksize=5):
out = 1 - dilate(1 - bin_img, ksize)
return out
class GaussianModel:
def setup_functions(self):
def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):
L = build_scaling_rotation(scaling_modifier * scaling, rotation)
actual_covariance = L @ L.transpose(1, 2)
symm = strip_symmetric(actual_covariance)
return symm
self.scaling_activation = torch.exp
self.scaling_inverse_activation = torch.log
self.covariance_activation = build_covariance_from_scaling_rotation
self.opacity_activation = torch.sigmoid
self.inverse_opacity_activation = inverse_sigmoid
self.rotation_activation = torch.nn.functional.normalize
def __init__(self, sh_degree : int):
self.active_sh_degree = 0
self.max_sh_degree = sh_degree
self._xyz = torch.empty(0)
self._knn_f = torch.empty(0)
self._features_dc = torch.empty(0)
self._features_rest = torch.empty(0)
self._scaling = torch.empty(0)
self._rotation = torch.empty(0)
self._opacity = torch.empty(0)
self._language_feature = torch.empty(0)
self._instance_feature=torch.empty(0)
self.max_radii2D = torch.empty(0)
self.max_weight = torch.empty(0)
self.xyz_gradient_accum = torch.empty(0)
self.xyz_gradient_accum_abs = torch.empty(0)
self.denom = torch.empty(0)
self.denom_abs = torch.empty(0)
self.optimizer = None
self.cam_optimizer = None
self.percent_dense = 0
self.spatial_lr_scale = 0
self.knn_dists = None
self.knn_idx = None
self.setup_functions()
self.use_app = False
def capture(self, include_feature=False):
if include_feature:
return (
self.active_sh_degree,
self._xyz,
self._knn_f,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self._language_feature,
self._instance_feature,
self.max_radii2D,
self.max_weight,
self.xyz_gradient_accum,
self.xyz_gradient_accum_abs,
self.denom,
self.denom_abs,
self.optimizer.state_dict(),
self.cam_optimizer.state_dict(),
self.spatial_lr_scale,
self.P
)
else:
return (
self.active_sh_degree,
self._xyz,
self._knn_f,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
self.max_weight,
self.xyz_gradient_accum,
self.xyz_gradient_accum_abs,
self.denom,
self.denom_abs,
self.optimizer.state_dict(),
self.cam_optimizer.state_dict(),
self.spatial_lr_scale,
self.P
)
def restore(self, model_args, training_args, mode='train'):
# Ckpt with training feature (20 arguments)
if len(model_args) == 20:
(self.active_sh_degree,
self._xyz,
self._knn_f,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self._language_feature, # Added training feature: language feature
self._instance_feature, # Added training feature: instance feature
self.max_radii2D,
self.max_weight,
xyz_gradient_accum,
xyz_gradient_accum_abs,
denom,
denom_abs,
opt_dict,
cam_opt_dict,
self.spatial_lr_scale,
self.P
) = model_args
# Ckpt without training feature (18 arguments)
elif len(model_args) == 18:
(self.active_sh_degree,
self._xyz,
self._knn_f,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
self.max_weight,
xyz_gradient_accum,
xyz_gradient_accum_abs,
denom,
denom_abs,
opt_dict,
cam_opt_dict,
self.spatial_lr_scale,
self.P
) = model_args
if mode == 'train':
if isinstance(self.optimizer, PerPointAdam):
self.training_setup_pp(training_args)
else:
self.training_setup(training_args)
self.xyz_gradient_accum = xyz_gradient_accum
self.xyz_gradient_accum_abs = xyz_gradient_accum_abs
self.denom = denom
self.denom_abs = denom_abs
self.optimizer.load_state_dict(opt_dict)
self.cam_optimizer.load_state_dict(cam_opt_dict)
@property
def get_scaling(self):
return self.scaling_activation(self._scaling)
@property
def get_rotation(self):
return self.rotation_activation(self._rotation)
@property
def get_xyz(self):
return self._xyz
@property
def get_features(self):
features_dc = self._features_dc
features_rest = self._features_rest
return torch.cat((features_dc, features_rest), dim=1)
@property
def get_opacity(self):
return self.opacity_activation(self._opacity)
@property
def get_language_feature(self):
return self._language_feature
@property
def get_instance_feature(self):
return self._instance_feature
def get_smallest_axis(self, return_idx=False):
rotation_matrices = self.get_rotation_matrix()
smallest_axis_idx = self.get_scaling.min(dim=-1)[1][..., None, None].expand(-1, 3, -1)
smallest_axis = rotation_matrices.gather(2, smallest_axis_idx)
if return_idx:
return smallest_axis.squeeze(dim=2), smallest_axis_idx[..., 0, 0]
return smallest_axis.squeeze(dim=2)
def get_normal(self, view_cam):
normal_global = self.get_smallest_axis()
gaussian_to_cam_global = view_cam.camera_center - self._xyz
neg_mask = (normal_global * gaussian_to_cam_global).sum(-1) < 0.0
normal_global[neg_mask] = -normal_global[neg_mask]
return normal_global
def init_RT_seq(self, cam_list):
poses =[]
index_mapping = {}
for cam_idx, cam in enumerate(cam_list[1.0]):
p = get_tensor_from_camera(cam.world_view_transform.transpose(0, 1)) # R T -> quat t
poses.append(p)
index_mapping[cam.uid] = cam_idx
poses = torch.stack(poses)
self.index_mapping = index_mapping
self.P = poses.cuda().requires_grad_(True)
def get_RT(self, idx):
pose = self.P[idx]
return pose
def get_RT_test(self, idx):
pose = self.test_P[idx]
return pose
def get_rotation_matrix(self):
return quaternion_to_matrix(self.get_rotation)
def get_covariance(self, scaling_modifier = 1):
return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)
def oneupSHdegree(self):
if self.active_sh_degree < self.max_sh_degree:
self.active_sh_degree += 1
def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):
self.spatial_lr_scale = spatial_lr_scale
fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()
fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())
features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()
features[:, :3, 0 ] = fused_color
features[:, 3:, 1:] = 0.0
print("Number of points at initialisation : ", fused_point_cloud.shape[0])
dist = torch.sqrt(torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001))
# print(f"new scale {torch.quantile(dist, 0.1)}")
scales = torch.log(dist)[...,None].repeat(1, 3)
rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")
rots[:, 0] = 1
opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))
knn_f = torch.randn((fused_point_cloud.shape[0], 6)).float().cuda()
self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))
self._knn_f = nn.Parameter(knn_f.requires_grad_(True))
self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))
self._scaling = nn.Parameter(scales.requires_grad_(True))
self._rotation = nn.Parameter(rots.requires_grad_(True))
self._opacity = nn.Parameter(opacities.requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
self.max_weight = torch.zeros((self.get_xyz.shape[0]), device="cuda")
language_feature = torch.zeros((fused_point_cloud.shape[0], 3), device="cuda")
self._language_feature = nn.Parameter(language_feature.requires_grad_(True)).requires_grad_(True) # dont train feature at first
# NOTE for instance distinguish
instance_feature = torch.zeros((fused_point_cloud.shape[0], 3), device="cuda")
self._instance_feature = nn.Parameter(instance_feature.requires_grad_(False)).requires_grad_(False) # just train feature at last
def training_setup(self, training_args, device):
self.percent_dense = training_args.percent_dense
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.xyz_gradient_accum_abs = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.denom_abs = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.abs_split_radii2D_threshold = training_args.abs_split_radii2D_threshold
self.max_abs_split_points = training_args.max_abs_split_points
self.max_all_points = training_args.max_all_points
l = [
{'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
{'params': [self._knn_f], 'lr': 0.01, "name": "knn_f"},
{'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
{'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
{'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
{'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
{'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
{'params': [self._language_feature], 'lr': training_args.language_feature_lr, "name": "language_feature"}, # semantic
{'params': [self._instance_feature], 'lr': training_args.language_feature_lr, "name": "instance_feature"}, # instance
]
l_cam = [{'params': [self.P],'lr': training_args.rotation_lr*0.1, "name": "pose"},]
# l += l_cam
self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
self.cam_optimizer = torch.optim.Adam(l_cam, lr=0.0, eps=1e-15)
self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
lr_final=training_args.position_lr_final*self.spatial_lr_scale,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.position_lr_max_steps)
self.cam_scheduler_args = get_expon_lr_func(
lr_init=training_args.rotation_lr*0.1,
lr_final=training_args.rotation_lr*0.001,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
# per-point optimizer
def training_setup_pp(self, training_args, confidence_lr=None, device="cuda"):
self.percent_dense = training_args.percent_dense
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.xyz_gradient_accum_abs = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.denom_abs = torch.zeros((self.get_xyz.shape[0], 1), device=device)
self.abs_split_radii2D_threshold = training_args.abs_split_radii2D_threshold
self.max_abs_split_points = training_args.max_abs_split_points
self.max_all_points = training_args.max_all_points
self.per_point_lr = confidence_lr
l = [
{'params': [self._xyz], 'per_point_lr': self.per_point_lr, 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
{'params': [self._knn_f], 'lr': 0.01, "name": "knn_f"},
{'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
{'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
{'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
{'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
{'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
{'params': [self._language_feature], 'lr': training_args.language_feature_lr, "name": "language_feature"}, # semantic
{'params': [self._instance_feature], 'lr': training_args.language_feature_lr, "name": "instance_feature"}, # instance
]
l_cam = [{'params': [self.P],'lr': training_args.rotation_lr*0.1, "name": "pose"},]
# l += l_cam
self.optimizer = PerPointAdam(l, lr=0, betas=(0.9, 0.999), eps=1e-15, weight_decay=0.0)
self.cam_optimizer = torch.optim.Adam(l_cam, lr=0.0, eps=1e-15)
self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
lr_final=training_args.position_lr_final*self.spatial_lr_scale,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.position_lr_max_steps)
self.cam_scheduler_args = get_expon_lr_func(
lr_init=training_args.rotation_lr*0.1,
lr_final=training_args.rotation_lr*0.001,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
def clip_grad(self, norm=1.0):
for group in self.optimizer.param_groups:
torch.nn.utils.clip_grad_norm_(group["params"][0], norm)
def update_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.cam_optimizer.param_groups:
if param_group["name"] == "pose":
lr = self.cam_scheduler_args(iteration)
param_group['lr'] = lr
for param_group in self.optimizer.param_groups:
if param_group["name"] == "xyz":
lr = self.xyz_scheduler_args(iteration)
param_group['lr'] = lr
def construct_list_of_attributes(self, include_feature=False):
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
# All channels except the 3 DC
for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
l.append('f_dc_{}'.format(i))
for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
l.append('f_rest_{}'.format(i))
l.append('opacity')
for i in range(self._scaling.shape[1]):
l.append('scale_{}'.format(i))
for i in range(self._rotation.shape[1]):
l.append('rot_{}'.format(i))
if include_feature:
for i in range(self._language_feature.shape[1]):
l.append('language_feature_{}'.format(i))
for i in range(self._instance_feature.shape[1]):
l.append('instance_feature_{}'.format(i))
return l
def save_ply(self, path, mask=None, include_feature=False):
mkdir_p(os.path.dirname(path))
xyz = self._xyz.detach().cpu().numpy()
normals = np.zeros_like(xyz)
f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self._opacity.detach().cpu().numpy()
scale = self._scaling.detach().cpu().numpy()
rotation = self._rotation.detach().cpu().numpy()
language_feature = self._language_feature.detach().cpu().numpy()
instance_feature = self._instance_feature.detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes(include_feature)]
elements = np.empty(xyz.shape[0], dtype=dtype_full)
if include_feature:
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation, language_feature, instance_feature), axis=1)
else:
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
elements[:] = list(map(tuple, attributes))
el = PlyElement.describe(elements, 'vertex')
PlyData([el]).write(path)
def reset_opacity(self):
opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))
optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity")
self._opacity = optimizable_tensors["opacity"]
def load_ply(self, path):
plydata = PlyData.read(path)
xyz = np.stack((np.asarray(plydata.elements[0]["x"]),
np.asarray(plydata.elements[0]["y"]),
np.asarray(plydata.elements[0]["z"])), axis=1)
opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis]
features_dc = np.zeros((xyz.shape[0], 3, 1))
features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"])
features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"])
features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"])
extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")]
extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))
assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3
features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))
for idx, attr_name in enumerate(extra_f_names):
features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])
# Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)
features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))
scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")]
scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))
scales = np.zeros((xyz.shape[0], len(scale_names)))
for idx, attr_name in enumerate(scale_names):
scales[:, idx] = np.asarray(plydata.elements[0][attr_name])
rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")]
rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))
rots = np.zeros((xyz.shape[0], len(rot_names)))
for idx, attr_name in enumerate(rot_names):
rots[:, idx] = np.asarray(plydata.elements[0][attr_name])
language_feature_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("language_feature")]
language_feature_names = sorted(language_feature_names, key = lambda x: int(x.split('_')[-1]))
language_feature = np.zeros((xyz.shape[0], len(language_feature_names)))
for idx, attr_name in enumerate(language_feature_names):
language_feature[:, idx] = np.asarray(plydata.elements[0][attr_name])
# NOTE instance
instance_feature_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("instance_feature")]
instance_feature_names = sorted(instance_feature_names, key = lambda x: int(x.split('_')[-1]))
instance_feature = np.zeros((xyz.shape[0], len(instance_feature_names)))
for idx, attr_name in enumerate(instance_feature_names):
instance_feature[:, idx] = np.asarray(plydata.elements[0][attr_name])
self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True))
self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True))
self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True))
self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True))
self._language_feature = nn.Parameter(torch.tensor(language_feature, dtype=torch.float, device="cuda").requires_grad_(False))
self._instance_feature = nn.Parameter(torch.tensor(instance_feature, dtype=torch.float, device="cuda").requires_grad_(False))
self.active_sh_degree = self.max_sh_degree
def replace_tensor_to_optimizer(self, tensor, name):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
if group["name"] == name:
stored_state = self.optimizer.state.get(group['params'][0], None)
stored_state["exp_avg"] = torch.zeros_like(tensor)
stored_state["exp_avg_sq"] = torch.zeros_like(tensor)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(tensor.requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def _prune_optimizer(self, mask):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
stored_state = self.optimizer.state.get(group['params'][0], None)
if stored_state is not None:
stored_state["exp_avg"] = stored_state["exp_avg"][mask]
stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask]
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True)))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def prune_points(self, mask):
valid_points_mask = ~mask
optimizable_tensors = self._prune_optimizer(valid_points_mask)
self._xyz = optimizable_tensors["xyz"]
self._knn_f = optimizable_tensors["knn_f"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self._language_feature = optimizable_tensors["language_feature"]
self._instance_feature = optimizable_tensors["instance_feature"]
self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]
self.xyz_gradient_accum_abs = self.xyz_gradient_accum_abs[valid_points_mask]
self.denom = self.denom[valid_points_mask]
self.denom_abs = self.denom_abs[valid_points_mask]
self.max_radii2D = self.max_radii2D[valid_points_mask]
self.max_weight = self.max_weight[valid_points_mask]
def cat_tensors_to_optimizer(self, tensors_dict):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
assert len(group["params"]) == 1
extension_tensor = tensors_dict[group["name"]]
stored_state = self.optimizer.state.get(group['params'][0], None)
if stored_state is not None:
stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0)
stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def densification_postfix(self, new_xyz, new_knn_f, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, new_language_feature, new_instance_feature):
d = {"xyz": new_xyz,
"knn_f": new_knn_f,
"f_dc": new_features_dc,
"f_rest": new_features_rest,
"opacity": new_opacities,
"scaling" : new_scaling,
"rotation" : new_rotation,
"language_feature": new_language_feature,
"instance_feature": new_instance_feature,
}
optimizable_tensors = self.cat_tensors_to_optimizer(d)
self._xyz = optimizable_tensors["xyz"]
self._knn_f = optimizable_tensors["knn_f"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self._language_feature = optimizable_tensors["language_feature"]
self._instance_feature = optimizable_tensors["instance_feature"]
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.xyz_gradient_accum_abs = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom_abs = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
self.max_weight = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def densify_and_split(self, grads, grad_threshold, grads_abs, grad_abs_threshold, scene_extent, max_radii2D, N=2):
n_init_points = self.get_xyz.shape[0]
# Extract points that satisfy the gradient condition
padded_grad = torch.zeros((n_init_points), device="cuda")
padded_grad[:grads.shape[0]] = grads.squeeze()
padded_grads_abs = torch.zeros((n_init_points), device="cuda")
padded_grads_abs[:grads_abs.shape[0]] = grads_abs.squeeze()
padded_max_radii2D = torch.zeros((n_init_points), device="cuda")
padded_max_radii2D[:max_radii2D.shape[0]] = max_radii2D.squeeze()
selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)
selected_pts_mask = torch.logical_and(selected_pts_mask,
torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)
if selected_pts_mask.sum() + n_init_points > self.max_all_points:
limited_num = self.max_all_points - n_init_points
padded_grad[~selected_pts_mask] = 0
ratio = limited_num / float(n_init_points)
threshold = torch.quantile(padded_grad, (1.0-ratio))
selected_pts_mask = torch.where(padded_grad > threshold, True, False)
# print(f"split {selected_pts_mask.sum()}, raddi2D {padded_max_radii2D.max()} ,{padded_max_radii2D.median()}")
else:
padded_grads_abs[selected_pts_mask] = 0
mask = (torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent) & (padded_max_radii2D > self.abs_split_radii2D_threshold)
padded_grads_abs[~mask] = 0
selected_pts_mask_abs = torch.where(padded_grads_abs >= grad_abs_threshold, True, False)
limited_num = min(self.max_all_points - n_init_points - selected_pts_mask.sum(), self.max_abs_split_points)
if selected_pts_mask_abs.sum() > limited_num:
ratio = limited_num / float(n_init_points)
threshold = torch.quantile(padded_grads_abs, (1.0-ratio))
selected_pts_mask_abs = torch.where(padded_grads_abs > threshold, True, False)
selected_pts_mask = torch.logical_or(selected_pts_mask, selected_pts_mask_abs)
# print(f"split {selected_pts_mask.sum()}, abs {selected_pts_mask_abs.sum()}, raddi2D {padded_max_radii2D.max()} ,{padded_max_radii2D.median()}")
stds = self.get_scaling[selected_pts_mask].repeat(N,1)
means =torch.zeros((stds.size(0), 3),device="cuda")
samples = torch.normal(mean=means, std=stds)
rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1)
new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask].repeat(N, 1)
new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))
new_rotation = self._rotation[selected_pts_mask].repeat(N,1)
new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)
new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)
new_opacity = self._opacity[selected_pts_mask].repeat(N,1)
new_knn_f = self._knn_f[selected_pts_mask].repeat(N,1)
new_language_feature = self._language_feature[selected_pts_mask].repeat(N,1)
new_instance_feature = self._instance_feature[selected_pts_mask].repeat(N,1)
self.densification_postfix(new_xyz, new_knn_f, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation, new_language_feature, new_instance_feature)
prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device="cuda", dtype=bool)))
self.prune_points(prune_filter)
def densify_and_clone(self, grads, grad_threshold, scene_extent):
n_init_points = self.get_xyz.shape[0]
# Extract points that satisfy the gradient condition
selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)
selected_pts_mask = torch.logical_and(selected_pts_mask,
torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)
if selected_pts_mask.sum() + n_init_points > self.max_all_points:
limited_num = self.max_all_points - n_init_points
grads_tmp = grads.squeeze().clone()
grads_tmp[~selected_pts_mask] = 0
ratio = min(limited_num / float(n_init_points), 1)
threshold = torch.quantile(grads_tmp, (1.0-ratio))
selected_pts_mask = torch.where(grads_tmp > threshold, True, False)
if selected_pts_mask.sum() > 0:
# print(f"clone {selected_pts_mask.sum()}")
new_xyz = self._xyz[selected_pts_mask]
stds = self.get_scaling[selected_pts_mask]
means =torch.zeros((stds.size(0), 3),device="cuda")
samples = torch.normal(mean=means, std=stds)
rots = build_rotation(self._rotation[selected_pts_mask])
new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask]
new_features_dc = self._features_dc[selected_pts_mask]
new_features_rest = self._features_rest[selected_pts_mask]
new_opacities = self._opacity[selected_pts_mask]
new_scaling = self._scaling[selected_pts_mask]
new_rotation = self._rotation[selected_pts_mask]
new_knn_f = self._knn_f[selected_pts_mask]
new_language_feature = self._language_feature[selected_pts_mask]
new_instance_feature = self._instance_feature[selected_pts_mask]
self.densification_postfix(new_xyz, new_knn_f, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, new_language_feature, new_instance_feature)
def densify_and_prune(self, max_grad, abs_max_grad, min_opacity, extent, max_screen_size):
grads = self.xyz_gradient_accum / self.denom
grads_abs = self.xyz_gradient_accum_abs / self.denom_abs
grads[grads.isnan()] = 0.0
grads_abs[grads_abs.isnan()] = 0.0
max_radii2D = self.max_radii2D.clone()
self.densify_and_clone(grads, max_grad, extent)
self.densify_and_split(grads, max_grad, grads_abs, abs_max_grad, extent, max_radii2D)
prune_mask = (self.get_opacity < min_opacity).squeeze()
if max_screen_size:
big_points_vs = self.max_radii2D > max_screen_size
big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent
prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)
self.prune_points(prune_mask)
# print(f"all points {self._xyz.shape[0]}")
torch.cuda.empty_cache()
def add_densification_stats(self, viewspace_point_tensor, viewspace_point_tensor_abs, update_filter):
self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)
self.xyz_gradient_accum_abs[update_filter] += torch.norm(viewspace_point_tensor_abs.grad[update_filter,:2], dim=-1, keepdim=True)
self.denom[update_filter] += 1
self.denom_abs[update_filter] += 1
def get_points_depth_in_depth_map(self, fov_camera, depth, points_in_camera_space, scale=1):
st = max(int(scale/2)-1,0)
depth_view = depth[None,:,st::scale,st::scale]
W, H = int(fov_camera.image_width/scale), int(fov_camera.image_height/scale)
depth_view = depth_view[:H, :W]
pts_projections = torch.stack(
[points_in_camera_space[:,0] * fov_camera.Fx / points_in_camera_space[:,2] + fov_camera.Cx,
points_in_camera_space[:,1] * fov_camera.Fy / points_in_camera_space[:,2] + fov_camera.Cy], -1).float()/scale
mask = (pts_projections[:, 0] > 0) & (pts_projections[:, 0] < W) &\
(pts_projections[:, 1] > 0) & (pts_projections[:, 1] < H) & (points_in_camera_space[:,2] > 0.1)
pts_projections[..., 0] /= ((W - 1) / 2)
pts_projections[..., 1] /= ((H - 1) / 2)
pts_projections -= 1
pts_projections = pts_projections.view(1, -1, 1, 2)
map_z = torch.nn.functional.grid_sample(input=depth_view,
grid=pts_projections,
mode='bilinear',
padding_mode='border',
align_corners=True
)[0, :, :, 0]
return map_z, mask
def get_points_from_depth(self, fov_camera, depth, scale=1):
st = int(max(int(scale/2)-1,0))
depth_view = depth.squeeze()[st::scale,st::scale]
rays_d = fov_camera.get_rays(scale=scale)
depth_view = depth_view[:rays_d.shape[0], :rays_d.shape[1]]
pts = (rays_d * depth_view[..., None]).reshape(-1,3)
R = torch.tensor(fov_camera.R).float().cuda()
T = torch.tensor(fov_camera.T).float().cuda()
pts = (pts-T)@R.transpose(-1,-2)
return pts
def change_reqiures_grad(self, change, iteration, quiet=True):
if change == "geometry":
self._xyz.requires_grad_(True)
self._knn_f.requires_grad_(True)
self._features_dc.requires_grad_(True)
self._features_rest.requires_grad_(True)
self._scaling.requires_grad_(True)
self._rotation.requires_grad_(True)
self._opacity.requires_grad_(True)
self.P.requires_grad_(True)
self._language_feature.requires_grad_(False)
self._instance_feature.requires_grad_(False)
if not quiet:
print(f'\n[ITER {iteration}] Training gaussian params')
elif change == 'semantic':
self._xyz.requires_grad_(True)
self._knn_f.requires_grad_(True)
self._features_dc.requires_grad_(True)
self._features_rest.requires_grad_(True)
self._scaling.requires_grad_(True)
self._rotation.requires_grad_(True)
self._opacity.requires_grad_(True)
self.P.requires_grad_(True)
self._language_feature.requires_grad_(True)
self._instance_feature.requires_grad_(False)
if not quiet:
print(f'\n[ITER {iteration}] Training gaussian params and language feature')
elif change == 'semantic_only':
self._xyz.requires_grad_(False)
self._knn_f.requires_grad_(False)
self._features_dc.requires_grad_(False)
self._features_rest.requires_grad_(False)
self._scaling.requires_grad_(False)
self._rotation.requires_grad_(False)
self._opacity.requires_grad_(False)
self.P.requires_grad_(False)
self._language_feature.requires_grad_(True)
self._instance_feature.requires_grad_(False)
if not quiet:
print(f'\n[ITER {iteration}] Training language feature')
elif change == 'instance':
self._xyz.requires_grad_(False)
self._knn_f.requires_grad_(False)
self._features_dc.requires_grad_(False)
self._features_rest.requires_grad_(False)
self._scaling.requires_grad_(False)
self._rotation.requires_grad_(False)
self._opacity.requires_grad_(False)
self.P.requires_grad_(False)
self._language_feature.requires_grad_(False)
self._instance_feature.requires_grad_(True)
if not quiet:
print(f'\n[ITER {iteration}] Training instance feature')
elif change == "pose_only":
self._xyz.requires_grad_(False)
self._knn_f.requires_grad_(False)
self._features_dc.requires_grad_(False)
self._features_rest.requires_grad_(False)
self._scaling.requires_grad_(False)
self._rotation.requires_grad_(False)
self._opacity.requires_grad_(False)
self.P.requires_grad_(True)
self._language_feature.requires_grad_(False)
self._instance_feature.requires_grad_(False)
if not quiet:
print(f'\n[ITER {iteration}] Training instance feature')
elif change == 'finetune':
self._xyz.requires_grad_(False)
self._knn_f.requires_grad_(False)
self._features_dc.requires_grad_(True)
self._features_rest.requires_grad_(True)
self._scaling.requires_grad_(False)
self._rotation.requires_grad_(False)
self._opacity.requires_grad_(False)
self.P.requires_grad_(False)
self._language_feature.requires_grad_(False)
self._instance_feature.requires_grad_(False)
if not quiet:
print(f'\n[ITER {iteration}] finetune')
else:
raise ValueError('Unknown type!')
|