Integrate & Improve FlexiCubes
Also updated the default .mtl file settings
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import os
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import nvdiffrast.torch as dr
|
||||
from kiui.cam import orbit_camera
|
||||
|
||||
from ..flexicubes import util
|
||||
|
||||
class FlexiCubesRenderer:
|
||||
def __init__(self, force_cuda_rast):
|
||||
|
||||
if force_cuda_rast or os.name != 'nt':
|
||||
self.glctx = dr.RasterizeCudaContext()
|
||||
else:
|
||||
self.glctx = dr.RasterizeGLContext()
|
||||
|
||||
def get_rotate_camera(self, itr, fovy = np.deg2rad(45), iter_res=[512,512], cam_near_far=[0.1, 1000.0], cam_radius=3.0, device="cuda"):
|
||||
proj_mtx = util.perspective(fovy, iter_res[1] / iter_res[0], cam_near_far[0], cam_near_far[1])
|
||||
|
||||
# Smooth rotation for display.
|
||||
ang = (itr / 10) * np.pi * 2
|
||||
mv = util.translate(0, 0, -cam_radius) @ (util.rotate_x(-0.4) @ util.rotate_y(ang))
|
||||
mvp = proj_mtx @ mv
|
||||
return mv.to(device), mvp.to(device)
|
||||
|
||||
def get_orbit_camera(self, azimuth=0, elevation=0, fovy=45, iter_res=[512,512], cam_near_far=[0.1, 1000.0], cam_radius=3.0, device="cuda"):
|
||||
aspect = iter_res[1] / iter_res[0]
|
||||
fovy = np.deg2rad(fovy)
|
||||
proj_mtx = util.perspective(fovy, aspect, cam_near_far[0], cam_near_far[1])
|
||||
#fovx = 2 * np.arctan(np.tan(fovy / 2) * aspect)
|
||||
#proj_mtx = get_projection_matrix(cam_near_far[0], cam_near_far[1], fovx, -fovy, z_sign=-1.0)
|
||||
|
||||
# Smooth rotation for display.
|
||||
#mv = util.translate(0, 0, -cam_radius) @ (util.rotate_x(-np.de2rad(elevation)) @ util.rotate_y(np.deg2rad(azimuth)))
|
||||
mv = torch.tensor(np.linalg.inv(orbit_camera(-elevation, azimuth, cam_radius)))
|
||||
mvp = proj_mtx @ mv
|
||||
return mv.to(device), mvp.to(device)
|
||||
|
||||
def render_mesh(self, mesh, mv, mvp, iter_res, depth_min=-5.5, depth_max=-0.5, return_types=["mask", "depth", "normal"], white_bg=False):
|
||||
'''
|
||||
The rendering function used to produce the results in the paper.
|
||||
'''
|
||||
v_pos_clip = util.xfm_points(mesh.vertices.unsqueeze(0), mvp) # Rotate it to camera coordinates
|
||||
rast, db = dr.rasterize(
|
||||
dr.RasterizeGLContext(), v_pos_clip, mesh.faces.int(), iter_res)
|
||||
|
||||
alpha_index = rast[..., -1:] > 0
|
||||
inv_alpha_index = rast[..., -1:] <= 0
|
||||
alpha = alpha_index.float()
|
||||
|
||||
out_dict = {}
|
||||
for type in return_types:
|
||||
if type == "mask" :
|
||||
img = dr.antialias(alpha, rast, v_pos_clip, mesh.faces.int())
|
||||
elif type == "depth":
|
||||
v_pos_cam = util.xfm_points(mesh.vertices.unsqueeze(0), mv)
|
||||
img, _ = util.interpolate(v_pos_cam[..., [2]].contiguous(), rast, mesh.faces.int())
|
||||
img_masked = img[alpha_index]
|
||||
img_masked = torch.clamp(img_masked, min=depth_min, max=depth_max)
|
||||
img_masked = (img_masked - depth_min) / (depth_max - depth_min)
|
||||
img[alpha_index] = img_masked
|
||||
img[inv_alpha_index] = 0
|
||||
elif type == "normal" :
|
||||
normal_indices = (torch.arange(0, mesh.nrm.shape[0], dtype=torch.int64, device='cuda')[:, None]).repeat(1, 3)
|
||||
img, _ = util.interpolate(mesh.nrm.unsqueeze(0).contiguous(), rast, normal_indices.int())
|
||||
elif type == "vertex_normal":
|
||||
img, _ = util.interpolate(mesh.v_nrm.unsqueeze(0).contiguous(), rast, mesh.faces.int())
|
||||
img = dr.antialias((img + 1) * 0.5, rast, v_pos_clip, mesh.faces.int())
|
||||
if white_bg:
|
||||
bg = torch.ones_like(img)
|
||||
img = torch.lerp(bg, img, alpha)
|
||||
out_dict[type] = img
|
||||
return out_dict
|
||||
@@ -0,0 +1,212 @@
|
||||
import os
|
||||
import imageio
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
|
||||
import tqdm
|
||||
import comfy.utils
|
||||
|
||||
|
||||
from .flexicubes_renderer import FlexiCubesRenderer
|
||||
from ..shared_utils.camera_utils import OrbitCamera
|
||||
from ..flexicubes.flexicubes import FlexiCubes
|
||||
from ..flexicubes.util import SimpleMesh
|
||||
from ..flexicubes.loss import sdf_reg_loss
|
||||
from ..mesh_processer.mesh import Mesh
|
||||
|
||||
def lr_schedule(iter):
|
||||
return max(0.0, 10**(-(iter)*0.0002)) # Exponential falloff from [1.0, 0.1] over 5k epochs.
|
||||
|
||||
class FlexiCubesTrainer:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
training_iterations,
|
||||
batch_size,
|
||||
learning_rate,
|
||||
voxel_grids_resolution,
|
||||
depth_near=0.5,
|
||||
depth_far=5.5,
|
||||
mask_loss_weight=1.0,
|
||||
depth_loss_weight=100.0,
|
||||
normal_loss_weight=1.0,
|
||||
sdf_regularizer_weight=0.2,
|
||||
remove_floaters_weight=0.5,
|
||||
cube_stabilizer_weight=0.1,
|
||||
force_cuda_rast=False,
|
||||
device='cuda'
|
||||
):
|
||||
self.device = torch.device(device)
|
||||
|
||||
self.renderer = FlexiCubesRenderer(force_cuda_rast)
|
||||
|
||||
# Create and initialize FlexiCubes
|
||||
self.voxel_grid_res = voxel_grids_resolution
|
||||
self.fc = FlexiCubes(self.device)
|
||||
self.x_nx3, self.cube_fx8 = self.fc.construct_voxel_grid(self.voxel_grid_res)
|
||||
self.x_nx3 *= 2 # scale up the grid so that it's larger than the target object
|
||||
|
||||
self.sdf = torch.rand_like(self.x_nx3[:,0]) - 0.1 # randomly init SDF
|
||||
self.sdf = torch.nn.Parameter(self.sdf.clone().detach(), requires_grad=True)
|
||||
# set per-cube learnable weights to zeros
|
||||
self.weight = torch.zeros((self.cube_fx8.shape[0], 21), dtype=torch.float, device=self.device)
|
||||
self.weight = torch.nn.Parameter(self.weight.clone().detach(), requires_grad=True)
|
||||
self.deform = torch.nn.Parameter(torch.zeros_like(self.x_nx3), requires_grad=True)
|
||||
|
||||
# Retrieve all the edges of the voxel grid; these edges will be utilized to
|
||||
# compute the regularization loss in subsequent steps of the process.
|
||||
all_edges = self.cube_fx8[:, self.fc.cube_edges].reshape(-1, 2)
|
||||
self.grid_edges = torch.unique(all_edges, dim=0)
|
||||
|
||||
# Setup optimizer
|
||||
self.optimizer = torch.optim.Adam([self.sdf, self.weight, self.deform], lr=learning_rate)
|
||||
self.scheduler = torch.optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lambda x: lr_schedule(x))
|
||||
|
||||
self.training_iterations = training_iterations
|
||||
self.batch_size = batch_size
|
||||
|
||||
self.depth_near = -depth_near
|
||||
self.depth_far = -depth_far
|
||||
|
||||
self.mask_loss_weight = mask_loss_weight
|
||||
self.depth_loss_weight = depth_loss_weight
|
||||
self.normal_loss_weight = normal_loss_weight
|
||||
self.sdf_regularizer_weight = sdf_regularizer_weight
|
||||
self.remove_floaters_weight = remove_floaters_weight
|
||||
self.cube_stabilizer_weight = cube_stabilizer_weight
|
||||
|
||||
def prepare_training(self, reference_depth_images, reference_masks, reference_orbit_camera_poses, reference_orbit_camera_fovy, reference_normals=None):
|
||||
self.ref_imgs_num = len(reference_depth_images)
|
||||
|
||||
self.all_ref_cam_poses = reference_orbit_camera_poses
|
||||
self.ref_cam_fovy = reference_orbit_camera_fovy
|
||||
|
||||
self.ref_size_H = reference_depth_images[0].shape[0]
|
||||
self.ref_size_W = reference_depth_images[0].shape[1]
|
||||
|
||||
self.cam = OrbitCamera(self.ref_size_W, self.ref_size_H, fovy=reference_orbit_camera_fovy)
|
||||
|
||||
# prepare reference images and masks
|
||||
self.ref_depth_imgs_torch = reference_depth_images[:, :, :, 0].unsqueeze(3).to(self.device) # (N, H, W, C) -> (N, H, W, 1)
|
||||
self.ref_masks_torch = reference_masks.unsqueeze(3).to(self.device)
|
||||
|
||||
if reference_normals is not None:
|
||||
self.ref_normal_imgs_torch = (reference_normals * 2 - 1).to(self.device) # change value from [0, 1] -> [-1, 1]
|
||||
else:
|
||||
self.ref_normal_imgs_torch = None
|
||||
|
||||
# prepare reference camera projection matrix for all camera poses
|
||||
mv_all = []
|
||||
mvp_all = []
|
||||
for pose in self.all_ref_cam_poses:
|
||||
mv, mvp = self.renderer.get_orbit_camera(pose[2], pose[1], cam_radius=pose[0], device=self.device)
|
||||
mv_all.append(mv)
|
||||
mvp_all.append(mvp)
|
||||
self.mv_all = torch.stack(mv_all).to(self.device)
|
||||
self.mvp_all = torch.stack(mvp_all).to(self.device)
|
||||
self.camposes_len = len(self.all_ref_cam_poses)
|
||||
|
||||
def training(self):
|
||||
starter = torch.cuda.Event(enable_timing=True)
|
||||
ender = torch.cuda.Event(enable_timing=True)
|
||||
starter.record()
|
||||
|
||||
comfy_pbar = comfy.utils.ProgressBar(self.training_iterations)
|
||||
|
||||
if self.ref_normal_imgs_torch is not None:
|
||||
return_types = ["mask", "depth", "normal"]
|
||||
else:
|
||||
return_types = ["mask", "depth"]
|
||||
|
||||
for step in tqdm.trange(self.training_iterations):
|
||||
# sample random render & camera pose from multi-views
|
||||
batch_index = np.random.randint(0, self.camposes_len, size=self.batch_size)
|
||||
mv = self.mv_all[batch_index, :, :]
|
||||
mvp = self.mvp_all[batch_index, :, :]
|
||||
|
||||
target_mask = self.ref_masks_torch[batch_index, :, :, :]
|
||||
target_depth = self.ref_depth_imgs_torch[batch_index, :, :, :]
|
||||
|
||||
# extract and render FlexiCubes mesh
|
||||
grid_verts = self.x_nx3 + (2-1e-8) / (self.voxel_grid_res * 2) * torch.tanh(self.deform)
|
||||
vertices, faces, L_dev = self.fc(grid_verts, self.sdf, self.cube_fx8, self.voxel_grid_res, beta_fx12=self.weight[:,:12], alpha_fx8=self.weight[:,12:20],
|
||||
gamma_f=self.weight[:,20], training=True)
|
||||
flexicubes_mesh = SimpleMesh(vertices, faces)
|
||||
if self.ref_normal_imgs_torch is not None:
|
||||
flexicubes_mesh.auto_normals()
|
||||
buffers = self.renderer.render_mesh(flexicubes_mesh, mv, mvp, (self.ref_size_H, self.ref_size_W), self.depth_far, self.depth_near, return_types)
|
||||
|
||||
t_iter = step / self.training_iterations
|
||||
# evaluate reconstruction loss
|
||||
# mask & depth shape: (N, H, W, 1)
|
||||
mask_loss = (buffers['mask'] - target_mask).abs().mean() * self.mask_loss_weight
|
||||
depth_loss = (((((buffers['depth'] - target_depth)* target_mask)**2).sum(-1)+1e-8)).sqrt().mean() * self.depth_loss_weight
|
||||
total_loss = mask_loss + depth_loss
|
||||
if self.ref_normal_imgs_torch is not None:
|
||||
target_normal = self.ref_normal_imgs_torch[batch_index, :, :, :]
|
||||
normal_loss = (((((buffers['normal'] - (target_normal))* target_mask)**2).sum(-1)+1e-8)).sqrt().mean() * self.normal_loss_weight * t_iter
|
||||
total_loss += normal_loss
|
||||
|
||||
sdf_weight = self.sdf_regularizer_weight - (self.sdf_regularizer_weight - self.sdf_regularizer_weight/20)*min(1.0, 4.0 * t_iter)
|
||||
reg_loss = sdf_reg_loss(self.sdf, self.grid_edges).mean() * sdf_weight # Loss to eliminate internal floaters that are not visible
|
||||
reg_loss += L_dev.mean() * self.remove_floaters_weight
|
||||
reg_loss += (self.weight[:,:20]).abs().mean() * self.cube_stabilizer_weight
|
||||
total_loss += reg_loss
|
||||
|
||||
# optimize step
|
||||
total_loss.backward()
|
||||
self.optimizer.step()
|
||||
self.scheduler.step()
|
||||
self.optimizer.zero_grad()
|
||||
|
||||
comfy_pbar.update_absolute(step + 1)
|
||||
|
||||
#self.test_save(step, mv, mvp, grid_verts, total_loss, out_dir="C:\\Users\\reall\\Softwares\\ComfyUI_windows_portable\\ComfyUI\\output\\FlexiCubes_Output\\Test_Normals")
|
||||
|
||||
ender.record()
|
||||
|
||||
def get_mesh(self):
|
||||
grid_verts = self.x_nx3 + (2-1e-8) / (self.voxel_grid_res * 2) * torch.tanh(self.deform)
|
||||
vertices, faces, L_dev = self.fc(grid_verts, self.sdf, self.cube_fx8, self.voxel_grid_res, beta_fx12=self.weight[:,:12], alpha_fx8=self.weight[:,12:20],
|
||||
gamma_f=self.weight[:,20], training=False)
|
||||
|
||||
v = vertices.detach().contiguous().float().to(self.device)
|
||||
f = faces.detach().contiguous().float().to(self.device)
|
||||
mesh = Mesh(v=v, f=f, device=self.device)
|
||||
mesh.auto_normal()
|
||||
mesh.auto_uv()
|
||||
|
||||
# Trimesh seems output better mesh
|
||||
#import trimesh
|
||||
#import os
|
||||
#mesh_np = trimesh.Trimesh(vertices = vertices.detach().cpu().numpy(), faces=faces.detach().cpu().numpy(), process=False)
|
||||
#mesh_np.export(os.path.join("C:\\Users\\reall\\Softwares\\ComfyUI_windows_portable\\ComfyUI\\output\\FlexiCubes_Output", 'output_trimesh.obj'))
|
||||
|
||||
return mesh
|
||||
|
||||
def test_save(self, step, mv, mvp, grid_verts, total_loss, out_dir, save_interval=20, display_res=[1024, 1024]):
|
||||
if (step % save_interval == 0 or step == (self.training_iterations-1)): # save normal image for visualization
|
||||
with torch.no_grad():
|
||||
# extract mesh with training=False
|
||||
vertices, faces, L_dev = self.fc(grid_verts, self.sdf, self.cube_fx8, self.voxel_grid_res, beta_fx12=self.weight[:,:12], alpha_fx8=self.weight[:,12:20],
|
||||
gamma_f=self.weight[:,20], training=False)
|
||||
flexicubes_mesh = SimpleMesh(vertices, faces)
|
||||
flexicubes_mesh.auto_normals() # compute face normals for visualization
|
||||
|
||||
mv, mvp = self.renderer.get_rotate_camera(step//save_interval, iter_res=display_res, device=self.device)
|
||||
mv = mv.unsqueeze(0)
|
||||
mvp = mvp.unsqueeze(0)
|
||||
val_buffers = self.renderer.render_mesh(flexicubes_mesh, mv, mvp, display_res, return_types=["normal"], white_bg=True)
|
||||
val_image = ((val_buffers["normal"][0].detach().cpu().numpy()+1)/2*255).astype(np.uint8)
|
||||
#val_image = (val_buffers["depth"][0].detach().cpu().numpy()*255).astype(np.uint8)
|
||||
#val_repeat = np.repeat(val_image, 4, axis=2)
|
||||
#val_repeat[:, :, 3] = 255
|
||||
|
||||
#gt_image = (gt_image[0].detach().cpu().numpy()*255).astype(np.uint8)
|
||||
#gt_repeat = np.repeat(gt_image, 4, axis=2)
|
||||
#gt_repeat[:, :, 3] = 255
|
||||
|
||||
imageio.imwrite(os.path.join(out_dir, '{:04d}.png'.format(step)), val_image)
|
||||
#imageio.imwrite(os.path.join(out_dir, '{:04d}.png'.format(step)), np.concatenate([val_repeat, gt_repeat], 1))
|
||||
print(f"Optimization Step [{step}/{self.training_iterations}], Loss: {total_loss.item():.4f}")
|
||||
@@ -1,397 +0,0 @@
|
||||
import torch
|
||||
import numpy as np
|
||||
from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation
|
||||
from torch import nn
|
||||
import os
|
||||
from utils.system_utils import mkdir_p
|
||||
from plyfile import PlyData, PlyElement
|
||||
from utils.sh_utils import RGB2SH
|
||||
from simple_knn._C import distCUDA2
|
||||
from utils.graphics_utils import BasicPointCloud
|
||||
from utils.general_utils import strip_symmetric, build_scaling_rotation
|
||||
|
||||
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, divide_ratio : float):
|
||||
self.active_sh_degree = 0
|
||||
self.max_sh_degree = sh_degree
|
||||
self._xyz = 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.max_radii2D = torch.empty(0)
|
||||
self.xyz_gradient_accum = torch.empty(0)
|
||||
self.denom = torch.empty(0)
|
||||
self.optimizer = None
|
||||
self.percent_dense = 0
|
||||
self.spatial_lr_scale = 0
|
||||
self.setup_functions()
|
||||
self.divide_ratio = divide_ratio
|
||||
|
||||
def capture(self):
|
||||
return (
|
||||
self.active_sh_degree,
|
||||
self._xyz,
|
||||
self._features_dc,
|
||||
self._features_rest,
|
||||
self._scaling,
|
||||
self._rotation,
|
||||
self._opacity,
|
||||
self.max_radii2D,
|
||||
self.xyz_gradient_accum,
|
||||
self.denom,
|
||||
self.optimizer.state_dict(),
|
||||
self.spatial_lr_scale,
|
||||
)
|
||||
|
||||
def restore(self, model_args, training_args):
|
||||
(self.active_sh_degree,
|
||||
self._xyz,
|
||||
self._features_dc,
|
||||
self._features_rest,
|
||||
self._scaling,
|
||||
self._rotation,
|
||||
self._opacity,
|
||||
self.max_radii2D,
|
||||
xyz_gradient_accum,
|
||||
denom,
|
||||
opt_dict,
|
||||
self.spatial_lr_scale) = model_args
|
||||
self.training_setup(training_args)
|
||||
self.xyz_gradient_accum = xyz_gradient_accum
|
||||
self.denom = denom
|
||||
self.optimizer.load_state_dict(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)
|
||||
|
||||
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])
|
||||
|
||||
dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
|
||||
scales = torch.log(torch.sqrt(dist2))[...,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"))
|
||||
|
||||
self._xyz = nn.Parameter(fused_point_cloud.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")
|
||||
|
||||
def training_setup(self, training_args):
|
||||
self.percent_dense = training_args.percent_dense
|
||||
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
|
||||
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
|
||||
|
||||
l = [
|
||||
{'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
|
||||
{'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"}
|
||||
]
|
||||
|
||||
self.optimizer = torch.optim.Adam(l, 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)
|
||||
|
||||
def update_learning_rate(self, iteration):
|
||||
''' Learning rate scheduling per step '''
|
||||
for param_group in self.optimizer.param_groups:
|
||||
if param_group["name"] == "xyz":
|
||||
lr = self.xyz_scheduler_args(iteration)
|
||||
param_group['lr'] = lr
|
||||
return lr
|
||||
|
||||
def construct_list_of_attributes(self):
|
||||
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
|
||||
|
||||
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))
|
||||
return l
|
||||
|
||||
def save_ply(self, path):
|
||||
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()
|
||||
|
||||
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
|
||||
|
||||
elements = np.empty(xyz.shape[0], dtype=dtype_full)
|
||||
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])
|
||||
|
||||
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])
|
||||
|
||||
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.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._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.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]
|
||||
|
||||
self.denom = self.denom[valid_points_mask]
|
||||
self.max_radii2D = self.max_radii2D[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_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):
|
||||
d = {"xyz": new_xyz,
|
||||
"f_dc": new_features_dc,
|
||||
"f_rest": new_features_rest,
|
||||
"opacity": new_opacities,
|
||||
"scaling" : new_scaling,
|
||||
"rotation" : new_rotation}
|
||||
|
||||
optimizable_tensors = self.cat_tensors_to_optimizer(d)
|
||||
self._xyz = optimizable_tensors["xyz"]
|
||||
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.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
|
||||
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
|
||||
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
|
||||
|
||||
def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):
|
||||
n_init_points = self.get_xyz.shape[0]
|
||||
|
||||
padded_grad = torch.zeros((n_init_points), device="cuda")
|
||||
padded_grad[:grads.shape[0]] = grads.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)
|
||||
|
||||
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) / (self.divide_ratio*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)
|
||||
|
||||
self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)
|
||||
|
||||
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):
|
||||
|
||||
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)
|
||||
|
||||
new_xyz = self._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]
|
||||
|
||||
self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)
|
||||
|
||||
def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):
|
||||
grads = self.xyz_gradient_accum / self.denom
|
||||
grads[grads.isnan()] = 0.0
|
||||
|
||||
self.densify_and_clone(grads, max_grad, extent)
|
||||
self.densify_and_split(grads, max_grad, extent)
|
||||
|
||||
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)
|
||||
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
def add_densification_stats(self, viewspace_point_tensor, update_filter):
|
||||
self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)
|
||||
self.denom[update_filter] += 1
|
||||
Reference in New Issue
Block a user