[ICCV 2023] Make-It-3D: High-Fidelity 3D Creation from A Single Image with Diffusion Prior
update coarse stage training code
junshutang97c71b171cb8
diff --git a/README.md b/README.mdnew file mode 100644index 0000000..301ae81--- /dev/null+++ b/README.md@@ -0,0 +1,73 @@+# Make-It-3D: High-Fidelity 3D Creation from A Single Image with Diffusion Prior++### [Project page](https://make-it-3d.github.io/) | [Paper](https://arxiv.org/abs/2303.14184)+<!-- <br> -->+[Junshu Tang](https://junshutang.github.io/), [Tengfei Wang](https://tengfei-wang.github.io/), [Bo Zhang](https://bo-zhang.me/), [Ting Zhang](https://www.microsoft.com/en-us/research/people/tinzhan/), [Ran Yi](https://yiranran.github.io/), [Lizhuang Ma](https://dmcv.sjtu.edu.cn/), and [Dong Chen](https://www.microsoft.com/en-us/research/people/doch/).+<!-- <br> -->++## Abstract+>In this work, we investigate the problem of creating high-fidelity 3D content from only a single image. This is inherently challenging: it essentially involves estimating the underlying 3D geometry while simultaneously hallucinating unseen textures. To address this challenge, we leverage prior knowledge from a well-trained 2D diffusion model to act as 3D-aware supervision for 3D creation. Our approach, Make-It-3D, employs a two-stage optimization pipeline: the first stage optimizes a neural radiance field by incorporating constraints from the reference image at the frontal view and diffusion prior at novel views; the second stage transforms the coarse model into textured point clouds and further elevates the realism with diffusion prior while leveraging the high-quality textures from the reference image. Extensive experiments demonstrate that our method outperforms prior works by a large margin, resulting in faithful reconstructions and impressive visual quality. Our method presents the first attempt to achieve high-quality 3D creation from a single image for general objects and enables various applications such as text-to-3D creation and texture editing.++++++## Installation+Install with pip:+```+ pip install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio===0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html+ pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch+ pip install git+https://github.com/openai/CLIP.git+ pip install git+https://github.com/huggingface/diffusers.git+ pip install git+https://github.com/huggingface/huggingface_hub.git+ pip install git+https://github.com/facebookresearch/pytorch3d.git+```+Other dependencies:+```+ pip install -r requirements.txt+ pip install ./raymarching+```+Training requirements+- [DPT](https://github.com/isl-org/DPT). We use an off-the-shelf single-view depth estimator DPT to predict the depth for the reference image.+ ```+ git clone https://github.com/isl-org/DPT.git+ mkdir dpt_weights+ ```+ Download the pretrained model [dpt_hybrid](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt), and put it in `dpt_weights`.+- [BLIP2](https://arxiv.org/abs/2301.12597). We use BLIP2 to generate a caption. You can also modify the conditioned text using `--text "{TEXT}"`.+- [Stable Diffusion](https://huggingface.co/models?other=stable-diffusion). We use diffusion prior is from a pretrained 2D pretrained Stable Diffusion 2.0 model. To start with, you may need a huggingface [token](https://huggingface.co/settings/tokens) to access the model, or use `huggingface-cli login` command.+## Coarse Stage Training+We use progressive training strategy to generate a full 360° 3D geometry. Run the command and modify the workspace name `NAME` and the path of the reference image `IMGPATH`.+We first optimize the scene under frontal camera views.+```+ python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 135 225 --iters 2000+```+Then we spread the camera view samples to full 360°.+```+ python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 0 360 --albedo_iters 3000 --iters 5000 --final+```+## Refine Stage Training++Coming soon...++## Important Note+Hallucinating 3D geometry and generating novel views from a single image of general genre is a challenging task. While our method demonstrates strong capability on creating 3D from most images with a centered single object, it may still encounter difficulties in reconstructing solid geometry on complex cases. **If you encounter any bugs, please feel free to contact us.**++## Todo+- [x] Release coarse stage training code+- [ ] Release the test benchmark for all results in the paper+- [ ] Release all training code+- [ ] Release more applications+++## Citation+If you find this code helpful for your research, please cite:+```+@article{tang2023make,+ title={Make-It-3D: High-Fidelity 3D Creation from A Single Image with Diffusion Prior},+ author={Tang, Junshu and Wang, Tengfei and Zhang, Bo and Zhang, Ting and Yi, Ran and Ma, Lizhuang and Chen, Dong},+ journal={arXiv preprint arXiv:2303.14184},+ year={2023}+}+```+diff --git a/activation.py b/activation.pynew file mode 100644index 0000000..c8edfd3--- /dev/null+++ b/activation.py@@ -0,0 +1,18 @@+import torch+from torch.autograd import Function+from torch.cuda.amp import custom_bwd, custom_fwd++class _trunc_exp(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float)+ def forward(ctx, x):+ ctx.save_for_backward(x)+ return torch.exp(x)++ @staticmethod+ @custom_bwd+ def backward(ctx, g):+ x = ctx.saved_tensors[0]+ return g * torch.exp(x.clamp(max=15))++trunc_exp = _trunc_exp.apply\ No newline at end of filediff --git a/demo/corgi.png b/demo/corgi.pngnew file mode 100644index 0000000..16d782aBinary files /dev/null and b/demo/corgi.png differdiff --git a/demo/teddy-2.png b/demo/teddy-2.pngnew file mode 100644index 0000000..d1a9f2fBinary files /dev/null and b/demo/teddy-2.png differdiff --git a/demo/teddy.png b/demo/teddy.pngnew file mode 100644index 0000000..7bb3a96Binary files /dev/null and b/demo/teddy.png differdiff --git a/encoding.py b/encoding.pynew file mode 100644index 0000000..a922b5a--- /dev/null+++ b/encoding.py@@ -0,0 +1,75 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++class FreqEncoder_torch(nn.Module):+ def __init__(self, input_dim, max_freq_log2, N_freqs,+ log_sampling=True, include_input=True,+ periodic_fns=(torch.sin, torch.cos)):++ super().__init__()++ self.input_dim = input_dim+ self.include_input = include_input+ self.periodic_fns = periodic_fns++ self.output_dim = 0+ if self.include_input:+ self.output_dim += self.input_dim++ self.output_dim += self.input_dim * N_freqs * len(self.periodic_fns)++ if log_sampling:+ self.freq_bands = 2 ** torch.linspace(0, max_freq_log2, N_freqs)+ else:+ self.freq_bands = torch.linspace(2 ** 0, 2 ** max_freq_log2, N_freqs)++ self.freq_bands = self.freq_bands.numpy().tolist()++ def forward(self, input, **kwargs):++ out = []+ if self.include_input:+ out.append(input)++ for i in range(len(self.freq_bands)):+ freq = self.freq_bands[i]+ for p_fn in self.periodic_fns:+ out.append(p_fn(input * freq))++ out = torch.cat(out, dim=-1)++ return out++def get_encoder(encoding, input_dim=3,+ multires=6,+ degree=4,+ num_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=2048, align_corners=False, interpolation='linear',+ **kwargs):++ if encoding == 'None':+ return lambda x, **kwargs: x, input_dim++ elif encoding == 'frequency_torch':+ encoder = FreqEncoder_torch(input_dim=input_dim, max_freq_log2=multires-1, N_freqs=multires, log_sampling=True)++ elif encoding == 'frequency': # CUDA implementation, faster than torch.+ from freqencoder import FreqEncoder+ encoder = FreqEncoder(input_dim=input_dim, degree=multires)++ elif encoding == 'sphere_harmonics':+ from shencoder import SHEncoder+ encoder = SHEncoder(input_dim=input_dim, degree=degree)++ elif encoding == 'hashgrid':+ from gridencoder import GridEncoder+ encoder = GridEncoder(input_dim=input_dim, num_levels=num_levels, level_dim=level_dim, base_resolution=base_resolution, log2_hashmap_size=log2_hashmap_size, desired_resolution=desired_resolution, gridtype='hash', align_corners=align_corners, interpolation=interpolation)++ elif encoding == 'tiledgrid':+ from gridencoder import GridEncoder+ encoder = GridEncoder(input_dim=input_dim, num_levels=num_levels, level_dim=level_dim, base_resolution=base_resolution, log2_hashmap_size=log2_hashmap_size, desired_resolution=desired_resolution, gridtype='tiled', align_corners=align_corners)++ else:+ raise NotImplementedError('Unknown encoding mode, choose from [None, frequency, sphere_harmonics, hashgrid, tiledgrid]')++ return encoder, encoder.output_dim\ No newline at end of filediff --git a/main.py b/main.pynew file mode 100644index 0000000..e375cc1--- /dev/null+++ b/main.py@@ -0,0 +1,246 @@+import torch+import argparse++from nerf.provider import NeRFDataset+from nerf.utils import *+from DPT.dpt.models import DPTDepthModel+import torchvision.transforms as T+from scipy.ndimage import median_filter+import DPT.util.io+# BLIP+from transformers import Blip2Processor, Blip2ForConditionalGeneration+from PIL import Image++# torch.autograd.set_detect_anomaly(True)++if __name__ == '__main__':++ parser = argparse.ArgumentParser()+ parser.add_argument('--text', default=None, help="text prompt")+ parser.add_argument('--negative', default='', type=str, help="negative text prompt")+ parser.add_argument('--test', action='store_true', help="test mode")+ parser.add_argument('--final', action='store_true', help="final train mode")+ parser.add_argument('--save_mesh', action='store_true', help="export an obj mesh with texture")+ parser.add_argument('--eval_interval', type=int, default=10, help="evaluate on the valid set every interval epochs")+ parser.add_argument('--workspace', type=str, default='workspace')+ parser.add_argument('--guidance', type=str, default='stable-diffusion', help='choose from [stable-diffusion, clip]')+ parser.add_argument('--seed', type=int, default=0)+ # parser.add_argument('--depth_model', type=str, default='dpt_hybrid', help='choose from [dpt_large, dpt_hybrid]')+ parser.add_argument('--guidance_scale', type=float, default=10)+ parser.add_argument('--need_back', action='store_true', help="use back text prompt")+ parser.add_argument('--suppress_face', action='store_true', help="also use negative dir text prompt.")+ parser.add_argument('--ref_path', default=None, type=str, help="use image as referance, only support alpha image")+++ ### training options+ parser.add_argument('--iters', type=int, default=10000, help="training iters")+ parser.add_argument('--lr', type=float, default=1e-3, help="max learning rate")+ parser.add_argument('--min_lr', type=float, default=1e-4, help="minimal learning rate")+ parser.add_argument('--ckpt', type=str, default='latest')+ parser.add_argument('--cuda_ray', action='store_true', help="use CUDA raymarching instead of pytorch")+ parser.add_argument('--max_steps', type=int, default=512, help="max num steps sampled per ray (only valid when using --cuda_ray)")+ parser.add_argument('--num_steps', type=int, default=64, help="num steps sampled per ray (only valid when not using --cuda_ray)")+ parser.add_argument('--upsample_steps', type=int, default=32, help="num steps up-sampled per ray (only valid when not using --cuda_ray)")+ parser.add_argument('--update_extra_interval', type=int, default=16, help="iter interval to update extra status (only valid when using --cuda_ray)")+ parser.add_argument('--max_ray_batch', type=int, default=4096, help="batch size of rays at inference to avoid OOM (only valid when not using --cuda_ray)")+ parser.add_argument('--albedo_iters', type=int, default=1000, help="training iters that only use albedo shading")+ parser.add_argument('--uniform_sphere_rate', type=float, default=0.5, help="likelihood of sampling camera location uniformly on the sphere surface area")+ parser.add_argument('--diff_iters', type=int, default=400, help="training iters that only use albedo shading")+ parser.add_argument('--step_range', type=float, nargs='*', default=[0.2, 0.6])++ # model options+ parser.add_argument('--bg_radius', type=float, default=-1, help="if positive, use a background model at sphere(bg_radius)")+ parser.add_argument('--density_thresh', type=float, default=10, help="threshold for density grid to be occupied")+ parser.add_argument('--blob_density', type=float, default=5, help="max (center) density for the gaussian density blob")+ parser.add_argument('--blob_radius', type=float, default=0.1, help="control the radius for the gaussian density blob")+ # network backbone+ parser.add_argument('--fp16', action='store_true', help="use amp mixed precision training")+ parser.add_argument('--backbone', type=str, default='tcnn', choices=['grid', 'tcnn', 'sdf', 'vanilla', 'normal'], help="nerf backbone")+ parser.add_argument('--optim', type=str, default='adan', choices=['adan', 'adam', 'adamw'], help="optimizer")+ parser.add_argument('--sd_version', type=str, default='2.0', choices=['1.5', '2.0'], help="stable diffusion version")+ parser.add_argument('--hf_key', type=str, default=None, help="hugging face Stable diffusion model key")+ # rendering resolution in training, decrease this if CUDA OOM.+ parser.add_argument('--w', type=int, default=128, help="render width for NeRF in training")+ parser.add_argument('--h', type=int, default=128, help="render height for NeRF in training")++ ### dataset options+ parser.add_argument('--bound', type=float, default=1, help="assume the scene is bounded in box(-bound, bound)")+ parser.add_argument('--dt_gamma', type=float, default=0, help="dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)")+ parser.add_argument('--min_near', type=float, default=0.1, help="minimum near distance for camera")+ parser.add_argument('--radius_range', type=float, nargs='*', default=[0.8, 1.2], help="training camera radius range")+ parser.add_argument('--fov', type=float, default=20, help="training camera fovy range")+ parser.add_argument('--fovy_range', type=float, nargs='*', default=[15, 25], help="training camera fovy range")+ parser.add_argument('--theta_range', type=float, nargs='*', default=[70, 110], help="training camera phi range")+ parser.add_argument('--phi_range', type=float, nargs='*', default=[0, 360], help="training camera phi range")++ parser.add_argument('--lambda_entropy', type=float, default=1, help="loss scale for alpha entropy")+ parser.add_argument('--lambda_opacity', type=float, default=1e-3, help="loss scale for alpha value")+ parser.add_argument('--lambda_orient', type=float, default=1e-2, help="loss scale for orientation")+ parser.add_argument('--lambda_smooth', type=float, default=1, help="loss scale for surface smoothness")+ parser.add_argument('--lambda_img', type=float, default=1e3, help="loss scale for ref loss")+ parser.add_argument('--lambda_depth', type=float, default=1, help="loss scale for depth loss")+ parser.add_argument('--lambda_clip', type=float, default=1, help="loss scale for clip loss")++ parser.add_argument('--W', type=int, default=800, help="GUI width")+ parser.add_argument('--H', type=int, default=800, help="GUI height")+ parser.add_argument('--radius', type=float, default=3, help="default GUI camera radius from center")+ parser.add_argument('--light_theta', type=float, default=60, help="default GUI light direction in [0, 180], corresponding to elevation [90, -90]")+ parser.add_argument('--light_phi', type=float, default=0, help="default GUI light direction in [0, 360), azimuth")+ parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel")+ parser.add_argument('--max_depth', type=float, default=10.0, help="farthest depth")++ opt = parser.parse_args()+ opt.cuda_ray = True+ optDict = opt.__dict__+ opt.workspace = os.path.join('results', opt.workspace)+ if opt.workspace is not None:+ os.makedirs(opt.workspace, exist_ok=True)++ if opt.backbone == 'vanilla':+ from nerf.network import NeRFNetwork+ elif opt.backbone == 'tcnn':+ from nerf.network_tcnn import NeRFNetwork+ else:+ raise NotImplementedError(f'--backbone {opt.backbone} is not implemented!')++ print(opt)+ seed_everything(opt.seed)++ # load depth network+ net_w = net_h = 384+ depth_model = DPTDepthModel(+ path="dpt_weights/dpt_hybrid-midas-501f0c75.pt",+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )+ depth_transform = T.Compose(+ [+ T.Resize((384, 384)),+ T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),+ ]+ )++ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')+ depth_model.to(device)++ if opt.optim == 'adan':+ from optimizer import Adan+ # Adan usually requires a larger LR+ optimizer = lambda model: Adan(model.get_params(5 * opt.lr), eps=1e-8, weight_decay=2e-5, max_grad_norm=5.0, foreach=False)+ else: # adam+ optimizer = lambda model: torch.optim.Adam(model.get_params(opt.lr), betas=(0.9, 0.99), eps=1e-15)++ if opt.backbone == 'vanilla':+ warm_up_with_cosine_lr = lambda iter: iter / opt.warm_iters if iter <= opt.warm_iters \+ else max(0.5 * ( math.cos((iter - opt.warm_iters) /(opt.iters - opt.warm_iters) * math.pi) + 1),+ opt.min_lr / opt.lr)++ scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, warm_up_with_cosine_lr)+ else:+ scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, lambda iter: 1) # fixed+ # scheduler = lambda optimizer: optim.lr_scheduler.LambdaLR(optimizer, lambda iter: 0.1 ** min(iter / opt.iters, 1))++ if opt.guidance == 'stable-diffusion':+ from nerf.sd import StableDiffusion+ guidance = StableDiffusion(device, opt.sd_version, opt.hf_key, step_range=opt.step_range)+ elif opt.guidance == 'clip':+ from nerf.clip import CLIP+ guidance = CLIP(device)+ else:+ raise NotImplementedError(f'--guidance {opt.guidance} is not implemented.')++ ref_imgs = cv2.imread(opt.ref_path, cv2.IMREAD_UNCHANGED) # [H, W, 3] o [H, W, 4]+ image_pil = Image.open(opt.ref_path).convert("RGB")++ # generated caption+ if opt.text == None:+ print("load blip2 for image caption...")+ processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")+ blip_model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16).to("cuda")+ inputs = processor(image_pil, return_tensors="pt").to("cuda", torch.float16)+ out = blip_model.generate(**inputs)+ caption = processor.batch_decode(out, skip_special_tokens=True)[0].strip()+ caption = caption.replace("there is ", "")+ caption = caption.replace("close up", "photo")+ for d in ["black background", "white background"]:+ if d in caption:+ caption = caption.replace(d, "ground")+ print("Caption: ", caption)+ opt.text = caption++ with open(os.path.join(opt.workspace, 'setting.txt'), 'w') as f:+ f.writelines('------------------ start ------------------' + '\n')+ for eachArg, value in optDict.items():+ f.writelines(eachArg + ' : ' + str(value) + '\n')+ f.writelines('------------------- end -------------------')+++ # only support alpha photo input.+ imgs = cv2.cvtColor(ref_imgs, cv2.COLOR_BGRA2RGBA)+ imgs = cv2.resize(imgs, (512, 512), interpolation=cv2.INTER_AREA)+ ref_imgs = (torch.from_numpy(imgs)/255.).unsqueeze(0).permute(0, 3, 1, 2).to(device)+ ori_imgs = ref_imgs[:, :3, :, :] * ref_imgs[:, 3:, :, :] + (1 - ref_imgs[:, 3:, :, :])++ mask = imgs[:, :, 3:]+ # mask[mask < 0.5 * 255] = 0+ # mask[mask >= 0.5 * 255] = 1+ kernel = np.ones(((5,5)), np.uint8) ##11+ mask = cv2.erode(mask,kernel,iterations=1)+ mask = (mask == 0)+ mask = (torch.from_numpy(mask)).unsqueeze(0).unsqueeze(0).to(device)+ depth_mask = mask++ # depth estimation+ with torch.no_grad():+ depth_prediction = depth_model.forward(depth_transform(ori_imgs))+ depth_prediction = torch.nn.functional.interpolate(+ depth_prediction.unsqueeze(1),+ size=512,+ mode="bicubic",+ align_corners=True,+ ) # [1, 1, 512, 512] [80~150]+ DPT.util.io.write_depth_name(os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_depth'), depth_prediction.squeeze().cpu().numpy(), bits=2)+ disparity = imageio.imread(os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_depth.png')) / 65535.+ disparity = median_filter(disparity, size=5)+ depth = 1. / np.maximum(disparity, 1e-2)++ depth = DPT.util.io.resize_img_cv(depth, ds_factor=1)++ depth_prediction = torch.tensor(depth, device=device)+ depth_mask = torch.tensor(depth_mask, device=device)+ # normalize estimated depth+ depth_prediction = depth_prediction * (~depth_mask) + torch.ones_like(depth_prediction) * (depth_mask)+ depth_prediction = ((depth_prediction - 1.0) / (depth_prediction.max() - 1.0)) * 0.9 + 0.1+ # save_image(ori_imgs, os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_ref.png'))++++ model = NeRFNetwork(opt)+ trainer = Trainer('df', opt, model, depth_model, guidance,+ ref_imgs=ref_imgs, ref_depth=depth_prediction,+ ref_mask=depth_mask, ori_imgs=ori_imgs,+ device=device, workspace=opt.workspace, optimizer=optimizer, ema_decay=None, fp16=opt.fp16, lr_scheduler=scheduler, use_checkpoint=opt.ckpt, eval_interval=opt.eval_interval, scheduler_update_every_step=True)+++ if opt.test:+ test_loader = NeRFDataset(opt, device=device, type='test', H=opt.H, W=opt.W, size=33).dataloader()+ trainer.test(test_loader, write_video=True)++ if opt.save_mesh:+ trainer.save_mesh(resolution=256)++ else:++ train_loader = NeRFDataset(opt, device=device, type='train', H=opt.h, W=opt.w, size=100).dataloader()+ valid_loader = NeRFDataset(opt, device=device, type='val', H=opt.H, W=opt.W, size=5).dataloader()+ max_epoch = np.ceil(opt.iters / 100).astype(np.int32)+ trainer.train(train_loader, valid_loader, max_epoch)++ # also test+ if opt.final:+ test_loader = NeRFDataset(opt, device=device, type='test', H=opt.H, W=opt.W, size=64).dataloader()+ trainer.test(test_loader, write_video=True)++ if opt.save_mesh:+ trainer.save_mesh(resolution=256)diff --git a/nerf/__pycache__/gui.cpython-37.pyc b/nerf/__pycache__/gui.cpython-37.pycnew file mode 100644index 0000000..f061068Binary files /dev/null and b/nerf/__pycache__/gui.cpython-37.pyc differdiff --git a/nerf/__pycache__/network_tcnn.cpython-37.pyc b/nerf/__pycache__/network_tcnn.cpython-37.pycnew file mode 100644index 0000000..eb4fa5cBinary files /dev/null and b/nerf/__pycache__/network_tcnn.cpython-37.pyc differdiff --git a/nerf/__pycache__/provider.cpython-37.pyc b/nerf/__pycache__/provider.cpython-37.pycnew file mode 100644index 0000000..9061b27Binary files /dev/null and b/nerf/__pycache__/provider.cpython-37.pyc differdiff --git a/nerf/__pycache__/renderer.cpython-37.pyc b/nerf/__pycache__/renderer.cpython-37.pycnew file mode 100644index 0000000..f4fc944Binary files /dev/null and b/nerf/__pycache__/renderer.cpython-37.pyc differdiff --git a/nerf/__pycache__/sd.cpython-37.pyc b/nerf/__pycache__/sd.cpython-37.pycnew file mode 100644index 0000000..5fb8400Binary files /dev/null and b/nerf/__pycache__/sd.cpython-37.pyc differdiff --git a/nerf/__pycache__/unet.cpython-37.pyc b/nerf/__pycache__/unet.cpython-37.pycnew file mode 100644index 0000000..baed916Binary files /dev/null and b/nerf/__pycache__/unet.cpython-37.pyc differdiff --git a/nerf/__pycache__/utils.cpython-37.pyc b/nerf/__pycache__/utils.cpython-37.pycnew file mode 100644index 0000000..7bf1434Binary files /dev/null and b/nerf/__pycache__/utils.cpython-37.pyc differdiff --git a/nerf/clip.py b/nerf/clip.pynew file mode 100644index 0000000..f33258a--- /dev/null+++ b/nerf/clip.py@@ -0,0 +1,47 @@+import torch+import torch.nn as nn++import torchvision.transforms as T+import torchvision.transforms.functional as TF++import clip++class CLIP(nn.Module):+ def __init__(self, device):+ super().__init__()++ self.device = device++ self.clip_model, self.clip_preprocess = clip.load("ViT-B/16", device=self.device, jit=False)++ # image augmentation+ self.aug = T.Compose([+ T.Resize((224, 224)),+ T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),+ ])++ # self.gaussian_blur = T.GaussianBlur(15, sigma=(0.1, 10))+++ def get_text_embeds(self, prompt, negative_prompt):++ # NOTE: negative_prompt is ignored for CLIP.++ text = clip.tokenize(prompt).to(self.device)+ text_z = self.clip_model.encode_text(text)+ text_z = text_z / text_z.norm(dim=-1, keepdim=True)++ return text_z+++ def train_step(self, text_z, pred_rgb):++ pred_rgb = self.aug(pred_rgb)++ image_z = self.clip_model.encode_image(pred_rgb)+ image_z = image_z / image_z.norm(dim=-1, keepdim=True) # normalize features++ loss = - (image_z * text_z).sum(-1).mean()++ return loss+diff --git a/nerf/network.py b/nerf/network.pynew file mode 100644index 0000000..e6ed647--- /dev/null+++ b/nerf/network.py@@ -0,0 +1,242 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++from activation import trunc_exp+from .renderer import NeRFRenderer++import numpy as np+from encoding import get_encoder++from .utils import safe_normalize++# TODO: not sure about the details...+class ResBlock(nn.Module):+ def __init__(self, dim_in, dim_out, bias=True):+ super().__init__()+ self.dim_in = dim_in+ self.dim_out = dim_out++ self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias)+ self.norm = nn.LayerNorm(self.dim_out)+ self.activation = nn.SiLU(inplace=True)++ if self.dim_in != self.dim_out:+ self.skip = nn.Linear(self.dim_in, self.dim_out, bias=False)+ else:+ self.skip = None++ def forward(self, x):+ # x: [B, C]+ identity = x++ out = self.dense(x)+ out = self.norm(out)++ if self.skip is not None:+ identity = self.skip(identity)++ out += identity+ out = self.activation(out)++ return out++class BasicBlock(nn.Module):+ def __init__(self, dim_in, dim_out, bias=True):+ super().__init__()+ self.dim_in = dim_in+ self.dim_out = dim_out++ self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias)+ self.activation = nn.ReLU(inplace=True)++ def forward(self, x):+ # x: [B, C]++ out = self.dense(x)+ out = self.activation(out)++ return out++class MLP(nn.Module):+ def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True, block=BasicBlock):+ super().__init__()+ self.dim_in = dim_in+ self.dim_out = dim_out+ self.dim_hidden = dim_hidden+ self.num_layers = num_layers++ net = []+ for l in range(num_layers):+ if l == 0:+ net.append(BasicBlock(self.dim_in, self.dim_hidden, bias=bias))+ elif l != num_layers - 1:+ net.append(block(self.dim_hidden, self.dim_hidden, bias=bias))+ else:+ net.append(nn.Linear(self.dim_hidden, self.dim_out, bias=bias))++ self.net = nn.ModuleList(net)+++ def forward(self, x):++ for l in range(self.num_layers):+ x = self.net[l](x)++ return x+++class NeRFNetwork(NeRFRenderer):+ def __init__(self,+ opt,+ num_layers=4, # 5 in paper+ hidden_dim=96, # 128 in paper+ num_layers_bg=2, # 3 in paper+ hidden_dim_bg=64, # 64 in paper+ encoding='frequency_torch', # pure pytorch+ ):++ super().__init__(opt)++ self.num_layers = num_layers+ self.hidden_dim = hidden_dim+ self.encoder, self.in_dim = get_encoder(encoding, input_dim=3, multires=6)+ self.sigma_net = MLP(self.in_dim, 4, hidden_dim, num_layers, bias=True, block=ResBlock)++ # background network+ if self.bg_radius > 0:+ self.num_layers_bg = num_layers_bg+ self.hidden_dim_bg = hidden_dim_bg+ self.encoder_bg, self.in_dim_bg = get_encoder(encoding, input_dim=3, multires=4)+ self.bg_net = MLP(self.in_dim_bg, 3, hidden_dim_bg, num_layers_bg, bias=True)++ else:+ self.bg_net = None++ def gaussian(self, x):+ # x: [B, N, 3]++ d = (x ** 2).sum(-1)+ g = self.opt.blob_density * torch.exp(- d / (self.opt.blob_radius ** 2))++ return g++ def common_forward(self, x):+ # x: [N, 3], in [-bound, bound]++ # sigma+ h = self.encoder(x, bound=self.bound)++ h = self.sigma_net(h)++ sigma = trunc_exp(h[..., 0] + self.gaussian(x))+ albedo = torch.sigmoid(h[..., 1:])++ return sigma, albedo++ # ref: https://github.com/zhaofuq/Instant-NSR/blob/main/nerf/network_sdf.py#L192+ def finite_difference_normal(self, x, epsilon=1e-2):+ # x: [N, 3]+ dx_pos, _ = self.common_forward((x + torch.tensor([[epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dx_neg, _ = self.common_forward((x + torch.tensor([[-epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dy_pos, _ = self.common_forward((x + torch.tensor([[0.00, epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dy_neg, _ = self.common_forward((x + torch.tensor([[0.00, -epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dz_pos, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, epsilon]], device=x.device)).clamp(-self.bound, self.bound))+ dz_neg, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, -epsilon]], device=x.device)).clamp(-self.bound, self.bound))++ normal = torch.stack([+ 0.5 * (dx_pos - dx_neg) / epsilon,+ 0.5 * (dy_pos - dy_neg) / epsilon,+ 0.5 * (dz_pos - dz_neg) / epsilon+ ], dim=-1)++ return -normal++ def normal(self, x):++ with torch.enable_grad():+ x.requires_grad_(True)+ sigma, albedo = self.common_forward(x)+ # query gradient+ normal = - torch.autograd.grad(torch.sum(sigma), x, create_graph=True)[0] # [N, 3]++ # normal = self.finite_difference_normal(x)+ normal = safe_normalize(normal)+ # normal = torch.nan_to_num(normal)++ return normal++ def forward(self, x, d, l=None, ratio=1, shading='albedo'):+ # x: [N, 3], in [-bound, bound]+ # d: [N, 3], view direction, nomalized in [-1, 1]+ # l: [3], plane light direction, nomalized in [-1, 1]+ # ratio: scalar, ambient ratio, 1 == no shading (albedo only), 0 == only shading (textureless)++ if shading == 'albedo':+ # no need to query normal+ sigma, color = self.common_forward(x)+ normal = None++ else:+ # query normal++ # sigma, albedo = self.common_forward(x)+ # normal = self.normal(x)++ with torch.enable_grad():+ x.requires_grad_(True)+ sigma, albedo = self.common_forward(x)+ # query gradient+ normal = - torch.autograd.grad(torch.sum(sigma), x, create_graph=True)[0] # [N, 3]+ normal = safe_normalize(normal)+ # normal = torch.nan_to_num(normal)+ # normal = normal.detach()++ # lambertian shading+ lambertian = ratio + (1 - ratio) * (normal @ l).clamp(min=0) # [N,]++ if shading == 'textureless':+ color = lambertian.unsqueeze(-1).repeat(1, 3)+ elif shading == 'normal':+ color = (normal + 1) / 2+ else: # 'lambertian'+ color = albedo * lambertian.unsqueeze(-1)++ return sigma, color, normal+++ def density(self, x):+ # x: [N, 3], in [-bound, bound]++ sigma, albedo = self.common_forward(x)++ return {+ 'sigma': sigma,+ 'albedo': albedo,+ }+++ def background(self, d):++ h = self.encoder_bg(d) # [N, C]++ h = self.bg_net(h)++ # sigmoid activation for rgb+ rgbs = torch.sigmoid(h)++ return rgbs++ # optimizer utils+ def get_params(self, lr):++ params = [+ # {'params': self.encoder.parameters(), 'lr': lr * 10},+ {'params': self.sigma_net.parameters(), 'lr': lr},+ ]++ if self.bg_radius > 0:+ # params.append({'params': self.encoder_bg.parameters(), 'lr': lr * 10})+ params.append({'params': self.bg_net.parameters(), 'lr': lr})++ return params\ No newline at end of filediff --git a/nerf/network_tcnn.py b/nerf/network_tcnn.pynew file mode 100644index 0000000..7d8039b--- /dev/null+++ b/nerf/network_tcnn.py@@ -0,0 +1,206 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++from activation import trunc_exp+from .renderer import NeRFRenderer+from encoding import get_encoder++import numpy as np+import tinycudann as tcnn+from .utils import safe_normalize++class MLP(nn.Module):+ def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True):+ super().__init__()+ self.dim_in = dim_in+ self.dim_out = dim_out+ self.dim_hidden = dim_hidden+ self.num_layers = num_layers++ net = []+ for l in range(num_layers):+ net.append(nn.Linear(self.dim_in if l == 0 else self.dim_hidden, self.dim_out if l == num_layers - 1 else self.dim_hidden, bias=bias))++ self.net = nn.ModuleList(net)++ def forward(self, x):+ for l in range(self.num_layers):+ x = self.net[l](x)+ if l != self.num_layers - 1:+ x = F.relu(x, inplace=True)+ return x+++++class NeRFNetwork(NeRFRenderer):+ def __init__(self,+ opt,+ bg_color=None,+ num_layers=3,+ hidden_dim=64,+ num_layers_bg=2,+ hidden_dim_bg=64,+ ):++ super().__init__(opt)++ self.num_layers = num_layers+ self.hidden_dim = hidden_dim+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')+ per_level_scale = np.exp2(np.log2(2048 * self.bound / 16) / (16 - 1))++ self.encoder = tcnn.Encoding(+ n_input_dims=3,+ encoding_config={+ "otype": "HashGrid",+ "n_levels": 16,+ "n_features_per_level": 2,+ "log2_hashmap_size": 19,+ "base_resolution": 16,+ "per_level_scale": per_level_scale,+ },+ dtype=torch.float32+ )++ self.sigma_net = MLP(32, 4, hidden_dim, num_layers, bias=True)+ if bg_color is not None:+ bg64 = torch.nn.functional.interpolate(+ bg_color,+ size=64,+ mode="bicubic",+ align_corners=True,+ ) # [1, 1, 512, 512] [80~150]+ bg64 = bg64.permute(0, 2, 3, 1).view(-1, 3)+ self.bg_color = torch.tensor(bg64, requires_grad=False, device=self.device)+ else:+ self.bg_color = torch.rand((4096, 3), requires_grad=False, device=self.device)+ # background network+ if self.bg_radius > 0:+ self.num_layers_bg = num_layers_bg+ self.hidden_dim_bg = hidden_dim_bg++ self.encoder_bg, self.in_dim_bg = get_encoder('frequency', input_dim=3)++ self.bg_net = MLP(self.in_dim_bg, 3, hidden_dim_bg, num_layers_bg, bias=True)+ else:+ self.bg_net = None++ def set_device(self, device):+ self.encoder.to(device)+ self.sigma_net.to(device)++ def gaussian(self, x):+ # x: [B, N, 3]++ d = (x ** 2).sum(-1)+ g = self.opt.blob_density * torch.exp(-d / (2 * self.opt.blob_radius ** 2))++ return g++ def common_forward(self, x):+ # x: [N, 3], in [-bound, bound]++ # sigma+ h = (x + self.bound) / (2 * self.bound) # to [0, 1]+ h = self.encoder(h)+ h = self.sigma_net(h)+ sigma = trunc_exp(h[..., 0] + self.gaussian(x))+ albedo = torch.sigmoid(h[..., 1:])++ return sigma, albedo++ # ref: https://github.com/zhaofuq/Instant-NSR/blob/main/nerf/network_sdf.py#L192+ def finite_difference_normal(self, x, epsilon=1e-2):+ # x: [N, 3]+ dx_pos, _ = self.common_forward((x + torch.tensor([[epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dx_neg, _ = self.common_forward((x + torch.tensor([[-epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dy_pos, _ = self.common_forward((x + torch.tensor([[0.00, epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dy_neg, _ = self.common_forward((x + torch.tensor([[0.00, -epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound))+ dz_pos, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, epsilon]], device=x.device)).clamp(-self.bound, self.bound))+ dz_neg, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, -epsilon]], device=x.device)).clamp(-self.bound, self.bound))++ normal = torch.stack([+ 0.5 * (dx_pos - dx_neg) / epsilon,+ 0.5 * (dy_pos - dy_neg) / epsilon,+ 0.5 * (dz_pos - dz_neg) / epsilon+ ], dim=-1)++ return -normal++ def normal(self, x):++ normal = self.finite_difference_normal(x)+ normal = safe_normalize(normal)+ normal = torch.nan_to_num(normal)++ return normal++ def forward(self, x, d, l=None, ratio=1, shading='albedo'):+ # x: [N, 3], in [-bound, bound]+ # d: [N, 3], view direction, nomalized in [-1, 1]+ # l: [3], plane light direction, nomalized in [-1, 1]+ # ratio: scalar, ambient ratio, 1 == no shading (albedo only)++ if shading == 'albedo':+ # no need to query normal+ sigma, albedo = self.common_forward(x)+ normal = self.normal(x)+ color = albedo++ else:+ # query normal+ # has_grad = torch.is_grad_enabled()++ sigma, albedo = self.common_forward(x)+ normal = self.normal(x)+ # lambertian shading+ if normal.shape[0] < 1e6:+ lambertian = ratio + (1 - ratio) * (normal @ l).clamp(min=0.1) # [N,]+ if shading == 'textureless':+ color = lambertian.unsqueeze(-1).repeat(1, 3)+ elif shading == 'normal':+ color = (normal + 1) / 2+ else: # 'lambertian'+ color = albedo * lambertian.unsqueeze(-1)+ else:+ color = albedo++ return sigma, color, normal+++ def density(self, x):+ # x: [N, 3], in [-bound, bound]+ sigma, albedo = self.common_forward(x)++ return {+ 'sigma': sigma,+ 'albedo': albedo,+ }++ def background(self, d):+ # x: [N, 2], in [-1, 1]++ h = self.encoder_bg(d) # [N, C]++ h = self.bg_net(h)++ # sigmoid activation for rgb+ rgbs = torch.sigmoid(h)++ return rgbs++ # optimizer utils+ def get_params(self, lr):+ params = [+ {'params': self.encoder.parameters(), 'lr': lr * 10},+ {'params': self.sigma_net.parameters(), 'lr': lr},+ # {'params': [self.bg_color], 'lr': lr}+ ]++ if self.bg_radius > 0:+ params.append({'params': self.encoder_bg.parameters(), 'lr': lr * 10})+ params.append({'params': self.bg_net.parameters(), 'lr': lr})++ return params\ No newline at end of filediff --git a/nerf/provider.py b/nerf/provider.pynew file mode 100644index 0000000..ad7c459--- /dev/null+++ b/nerf/provider.py@@ -0,0 +1,319 @@+import os+import cv2+import glob+import json+import tqdm+import random+import numpy as np+from scipy.spatial.transform import Slerp, Rotation+import math+import trimesh++import torch+import torch.nn.functional as F+from torch.utils.data import DataLoader++from .utils import get_rays, safe_normalize++DIR_COLORS = np.array([+ [255, 0, 0, 255], # front+ [0, 255, 0, 255], # side+ [0, 0, 255, 255], # back+ [255, 255, 0, 255], # side+ [255, 0, 255, 255], # overhead+ [0, 255, 255, 255], # bottom+], dtype=np.uint8)++def visualize_poses(poses, dirs, size=0.1):+ # poses: [B, 4, 4], dirs: [B]++ axes = trimesh.creation.axis(axis_length=4)+ sphere = trimesh.creation.icosphere(radius=1)+ objects = [axes, sphere]++ for pose, dir in zip(poses, dirs):+ # a camera is visualized with 8 line segments.+ pos = pose[:3, 3]+ a = pos + size * pose[:3, 0] + size * pose[:3, 1] + size * pose[:3, 2]+ b = pos - size * pose[:3, 0] + size * pose[:3, 1] + size * pose[:3, 2]+ c = pos - size * pose[:3, 0] - size * pose[:3, 1] + size * pose[:3, 2]+ d = pos + size * pose[:3, 0] - size * pose[:3, 1] + size * pose[:3, 2]++ segs = np.array([[pos, a], [pos, b], [pos, c], [pos, d], [a, b], [b, c], [c, d], [d, a]])+ segs = trimesh.load_path(segs)++ # different color for different dirs+ segs.colors = DIR_COLORS[[dir]].repeat(len(segs.entities), 0)++ objects.append(segs)++ trimesh.Scene(objects).show()++def get_view_direction(thetas, phis, overhead, front):+ # phis [B,]; thetas: [B,]+ # front = 0 [0, front)+ # side (left) = 1 [front, 180)+ # back = 2 [180, 180+front)+ # side (right) = 3 [180+front, 360)+ # top = 4 [0, overhead]+ # bottom = 5 [180-overhead, 180]+ res = torch.zeros(thetas.shape[0], dtype=torch.long)+ # first determine by phis+ res[(phis < front)] = 0+ res[(phis >= front) & (phis < np.pi)] = 1+ res[(phis >= np.pi) & (phis < (np.pi + front))] = 2+ res[(phis >= (np.pi + front))] = 3+ # override by thetas+ res[thetas <= overhead] = 4+ res[thetas >= (np.pi - overhead)] = 5+ return res+++def rand_poses(size, device, radius_range=[1, 1.5], theta_range=[0, 120], phi_range=[0, 360], return_dirs=False, angle_overhead=30, angle_front=60, jitter=False, uniform_sphere_rate=0.5):+ ''' generate random poses from an orbit camera+ Args:+ size: batch size of generated poses.+ device: where to allocate the output.+ radius: camera radius+ theta_range: [min, max], should be in [0, pi]+ phi_range: [min, max], should be in [0, 2 * pi]+ Return:+ poses: [size, 4, 4]+ '''++ theta_range = np.deg2rad(theta_range)+ phi_range = np.deg2rad(phi_range)+ angle_overhead = np.deg2rad(angle_overhead)+ angle_front = np.deg2rad(angle_front)++ radius = torch.rand(size, device=device) * (radius_range[1] - radius_range[0]) + radius_range[0]++ if random.random() < uniform_sphere_rate:+ unit_centers = F.normalize(+ torch.stack([+ (torch.rand(size, device=device) - 0.5) * 2.0,+ torch.rand(size, device=device),+ (torch.rand(size, device=device) - 0.5) * 2.0,+ ], dim=-1), p=2, dim=1+ )+ thetas = torch.acos(unit_centers[:,1])+ phis = torch.atan2(unit_centers[:,0], unit_centers[:,2])+ phis[phis < 0] += 2 * np.pi+ centers = unit_centers * radius.unsqueeze(-1)+ else:+ thetas = torch.rand(size, device=device) * (theta_range[1] - theta_range[0]) + theta_range[0]+ phis = torch.rand(size, device=device) * (phi_range[1] - phi_range[0]) + phi_range[0]++ centers = torch.stack([+ radius * torch.sin(thetas) * torch.sin(phis),+ radius * torch.cos(thetas),+ radius * torch.sin(thetas) * torch.cos(phis),+ ], dim=-1) # [B, 3]++ targets = 0++ # jitters+ if jitter:+ centers = centers + (torch.rand_like(centers) * 0.2 - 0.1)+ targets = targets + torch.randn_like(centers) * 0.2++ # lookat+ forward_vector = safe_normalize(targets - centers)+ up_vector = torch.FloatTensor([0, -1, 0]).to(device).unsqueeze(0).repeat(size, 1)+ right_vector = safe_normalize(torch.cross(forward_vector, up_vector, dim=-1))++ if jitter:+ up_noise = torch.randn_like(up_vector) * 0.02+ else:+ up_noise = 0++ up_vector = safe_normalize(torch.cross(right_vector, forward_vector, dim=-1) + up_noise)++ poses = torch.eye(4, dtype=torch.float, device=device).unsqueeze(0).repeat(size, 1, 1)+ poses[:, :3, :3] = torch.stack((right_vector, up_vector, forward_vector), dim=-1)+ poses[:, :3, 3] = centers++ if return_dirs:+ dirs = get_view_direction(thetas, phis, angle_overhead, angle_front)+ else:+ dirs = None++ return poses, dirs++def fix_poses(size, index, device, radius_range=[1, 1.5], theta_range=[0, 100], phi_range=[0, 360]):+ ''' generate random poses from an orbit camera+ Args:+ size: batch size of generated poses.+ device: where to allocate the output.+ radius: camera radius+ theta_range: [min, max], should be in [0, pi]+ phi_range: [min, max], should be in [0, 2 * pi]+ Return:+ poses: [size, 4, 4]+ '''++ theta_range = np.deg2rad(theta_range)+ phi_range = np.deg2rad(phi_range)++ # rand = random.random()+ if index % 4 == 0:+ radius = torch.ones(size, device=device)+ thetas = torch.ones(size, device=device) * (theta_range[1] - theta_range[0]) / 2 + theta_range[0]+ phis = torch.ones(size, device=device) * (phi_range[1] - phi_range[0]) / 2 + phi_range[0]+ # phis = torch.ones(size, device=device) * phi_range[0]+ is_front = True+ is_large = False++ else:+ radius = torch.rand(size, device=device) * (radius_range[1] - radius_range[0]) + radius_range[0]+ if phi_range[1] <= np.deg2rad(240.0) and phi_range[0] >= np.deg2rad(120.0):+ phis = torch.rand(size, device=device) * (phi_range[1] - phi_range[0]) + phi_range[0]+ else:+ rand = random.random()+ if rand > 0.85:+ phis = torch.rand(size, device=device) * (phi_range[1] - np.deg2rad(315.0)) + np.deg2rad(315.0)+ elif rand > 0.7:+ phis = torch.rand(size, device=device) * (np.deg2rad(45.0) - phi_range[0]) + phi_range[0]+ elif rand > 0.5:+ phis = torch.rand(size, device=device) * (np.deg2rad(315.0) - np.deg2rad(240.0)) + np.deg2rad(240.0)+ elif rand > 0.3:+ phis = torch.rand(size, device=device) * (np.deg2rad(120.0) - np.deg2rad(45.0)) + np.deg2rad(45.0)+ else:+ phis = torch.rand(size, device=device) * (np.deg2rad(240.0) - np.deg2rad(120.0)) + np.deg2rad(120.0)++ is_front = False++ rand_theta = torch.rand(size, device=device)+ thetas = rand_theta * (theta_range[1] - theta_range[0]) + theta_range[0]++ if (phis >= np.deg2rad(0) and phis <= np.deg2rad(45)) or (phis >= np.deg2rad(315) and phis <= np.deg2rad(360)):+ is_large = True+ else:+ is_large = False++ centers = torch.stack([+ radius * torch.sin(thetas) * torch.sin(phis),+ radius * torch.cos(thetas),+ radius * torch.sin(thetas) * torch.cos(phis),+ ], dim=-1) # [B, 3]++ targets = 0++ # lookat+ forward_vector = safe_normalize(targets - centers)+ up_vector = torch.FloatTensor([0, -1, 0]).to(device).unsqueeze(0).repeat(size, 1)+ right_vector = safe_normalize(torch.cross(forward_vector, up_vector, dim=-1))++ up_noise = 0+ up_vector = safe_normalize(torch.cross(right_vector, forward_vector, dim=-1) + up_noise)++ poses = torch.eye(4, dtype=torch.float, device=device).unsqueeze(0).repeat(size, 1, 1)+ poses[:, :3, :3] = torch.stack((right_vector, up_vector, forward_vector), dim=-1)+ poses[:, :3, 3] = centers++ return thetas, phis, poses, is_front, is_large+++def circle_poses(device, radius=1.0, theta=60, phi=0):++ theta = np.deg2rad(theta)+ phi = np.deg2rad(phi)++ thetas = torch.FloatTensor([theta]).to(device)+ phis = torch.FloatTensor([phi]).to(device)++ centers = torch.stack([+ radius * torch.sin(thetas) * torch.sin(phis),+ radius * torch.cos(thetas),+ radius * torch.sin(thetas) * torch.cos(phis),+ ], dim=-1) # [B, 3]++ # lookat+ forward_vector = - safe_normalize(centers)+ up_vector = torch.FloatTensor([0, -1, 0]).to(device).unsqueeze(0)+ right_vector = safe_normalize(torch.cross(forward_vector, up_vector, dim=-1))+ up_vector = safe_normalize(torch.cross(right_vector, forward_vector, dim=-1))++ poses = torch.eye(4, dtype=torch.float, device=device).unsqueeze(0)+ poses[:, :3, :3] = torch.stack((right_vector, up_vector, forward_vector), dim=-1)+ poses[:, :3, 3] = centers++ return thetas, phis, poses+++class NeRFDataset:+ def __init__(self, opt, device, type='train', H=256, W=256, size=100):+ super().__init__()++ self.opt = opt+ self.device = device+ self.type = type # train, val, test++ self.H = H+ self.W = W+ self.radius_range = opt.radius_range+ self.fov = opt.fov+ self.size = size++ self.training = self.type in ['train', 'all']+ self.testing = self.type in ['test']+ self.cx = self.H / 2+ self.cy = self.W / 2++ def collate(self, index):++ B = len(index) # always 1++ if self.training:+ # random pose on the fly+ thetas, phis, poses, is_front, is_large = fix_poses(B, index[0], self.device, radius_range=self.radius_range, theta_range=self.opt.theta_range, phi_range=self.opt.phi_range)+ if is_front:+ fov = self.fov+ else:+ fov = random.random() * (self.opt.fovy_range[1] - self.opt.fovy_range[0]) + self.opt.fovy_range[0]++ # elif self.testing:+ # theta = [80.0, 90.0, 100.0]+ # length = self.size // 3+ # i = int(index[0] // length)+ # if i % 2 == 0:+ # phi = ((index[0]%length)/(length -1)) * (self.opt.phi_range[1]-self.opt.phi_range[0]) + self.opt.phi_range[0]+ # else:+ # phi = ((index[0]%length)/(length -1)) * (self.opt.phi_range[0]-self.opt.phi_range[1]) + self.opt.phi_range[1]+ # theta = theta[i]++ # thetas, phis, poses = circle_poses(self.device, radius=1.0, theta=theta, phi=phi)+ # is_front = False+ # is_large = False+ # fov = self.fov+ else:+ phi = (index[0] / self.size) * (self.opt.phi_range[1]-self.opt.phi_range[0]) + self.opt.phi_range[0]+ thetas, phis, poses = circle_poses(self.device, radius=1.0, theta=90, phi=phi)+ is_front = False+ is_large = False+ fov = self.fov++ focal = self.H / (2 * np.tan(np.deg2rad(fov) / 2))+ intrinsics = np.array([focal, focal, self.cx, self.cy])+ # sample a low-resolution but full image for CLIP+ rays = get_rays(poses, intrinsics, self.H, self.W, -1)++ data = {+ 'H': self.H,+ 'W': self.W,+ 'rays_o': rays['rays_o'],+ 'rays_d': rays['rays_d'],+ 'depth_scale': rays['depth_scale'],+ 'is_front': is_front,+ 'is_large': is_large,+ 'poses': poses,+ 'thetas': thetas,+ 'phis': phis,+ }++ return data+++ def dataloader(self):+ loader = DataLoader(list(range(self.size)), batch_size=1, collate_fn=self.collate, shuffle=self.training, num_workers=0)+ return loader\ No newline at end of filediff --git a/nerf/renderer.py b/nerf/renderer.pynew file mode 100644index 0000000..3c33fa9--- /dev/null+++ b/nerf/renderer.py@@ -0,0 +1,678 @@+import os+import math+import cv2+import trimesh+import open3d as o3d+import numpy as np++import torch+import torch.nn as nn+import torch.nn.functional as F++import mcubes+import raymarching+from .utils import custom_meshgrid, safe_normalize++def sample_pdf(bins, weights, n_samples, det=False):+ # This implementation is from NeRF+ # bins: [B, T], old_z_vals+ # weights: [B, T - 1], bin weights.+ # return: [B, n_samples], new_z_vals++ # Get pdf+ weights = weights + 1e-5 # prevent nans+ pdf = weights / torch.sum(weights, -1, keepdim=True)+ cdf = torch.cumsum(pdf, -1)+ cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], -1)+ # Take uniform samples+ if det:+ u = torch.linspace(0. + 0.5 / n_samples, 1. - 0.5 / n_samples, steps=n_samples).to(weights.device)+ u = u.expand(list(cdf.shape[:-1]) + [n_samples])+ else:+ u = torch.rand(list(cdf.shape[:-1]) + [n_samples]).to(weights.device)++ # Invert CDF+ u = u.contiguous()+ inds = torch.searchsorted(cdf, u, right=True)+ below = torch.max(torch.zeros_like(inds - 1), inds - 1)+ above = torch.min((cdf.shape[-1] - 1) * torch.ones_like(inds), inds)+ inds_g = torch.stack([below, above], -1) # (B, n_samples, 2)++ matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]]+ cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g)+ bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g)++ denom = (cdf_g[..., 1] - cdf_g[..., 0])+ denom = torch.where(denom < 1e-5, torch.ones_like(denom), denom)+ t = (u - cdf_g[..., 0]) / denom+ samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0])++ return samples+[email protected](enabled=False)+def near_far_from_bound(rays_o, rays_d, bound, type='cube', min_near=0.05):+ # rays: [B, N, 3], [B, N, 3]+ # bound: int, radius for ball or half-edge-length for cube+ # return near [B, N, 1], far [B, N, 1]++ radius = rays_o.norm(dim=-1, keepdim=True)++ if type == 'sphere':+ near = radius - bound # [B, N, 1]+ far = radius + bound++ elif type == 'cube':+ tmin = (-bound - rays_o) / (rays_d + 1e-15) # [B, N, 3]+ tmax = (bound - rays_o) / (rays_d + 1e-15)+ near = torch.where(tmin < tmax, tmin, tmax).max(dim=-1, keepdim=True)[0]+ far = torch.where(tmin > tmax, tmin, tmax).min(dim=-1, keepdim=True)[0]+ # if far < near, means no intersection, set both near and far to inf (1e9 here)+ mask = far < near+ near[mask] = 1e9+ far[mask] = 1e9+ # restrict near to a minimal value+ near = torch.clamp(near, min=min_near)++ return near, far+++def plot_pointcloud(pc, color=None):+ # pc: [N, 3]+ # color: [N, 3/4]+ print('[visualize points]', pc.shape, pc.dtype, pc.min(0), pc.max(0))+ pc = trimesh.PointCloud(pc, color)+ # axis+ axes = trimesh.creation.axis(axis_length=4)+ # sphere+ sphere = trimesh.creation.icosphere(radius=1)+ trimesh.Scene([pc, axes, sphere]).show()++def save_pointcloud(save_dir, points, rgb=None):+ pcd = o3d.geometry.PointCloud()+ pcd.points = o3d.utility.Vector3dVector(points)+ if rgb is not None:+ pcd.colors = o3d.utility.Vector3dVector(rgb)+ o3d.io.write_point_cloud(save_dir, pcd, write_ascii=True)++++class NeRFRenderer(nn.Module):+ def __init__(self, opt):+ super().__init__()++ self.opt = opt+ self.bound = opt.bound+ self.cascade = 1 + math.ceil(math.log2(opt.bound))+ self.grid_size = 128+ self.cuda_ray = opt.cuda_ray+ self.min_near = opt.min_near+ self.density_thresh = opt.density_thresh+ self.bg_radius = opt.bg_radius++ # prepare aabb with a 6D tensor (xmin, ymin, zmin, xmax, ymax, zmax)+ # NOTE: aabb (can be rectangular) is only used to generate points, we still rely on bound (always cubic) to calculate density grid and hashing.+ aabb_train = torch.FloatTensor([-opt.bound, -opt.bound, -opt.bound, opt.bound, opt.bound, opt.bound])+ aabb_infer = aabb_train.clone()+ self.register_buffer('aabb_train', aabb_train)+ self.register_buffer('aabb_infer', aabb_infer)++ # extra state for cuda raymarching+ if self.cuda_ray:+ # density grid+ density_grid = torch.zeros([self.cascade, self.grid_size ** 3]) # [CAS, H * H * H]+ density_bitfield = torch.zeros(self.cascade * self.grid_size ** 3 // 8, dtype=torch.uint8) # [CAS * H * H * H // 8]+ self.register_buffer('density_grid', density_grid)+ self.register_buffer('density_bitfield', density_bitfield)+ self.mean_density = 0+ self.iter_density = 0+ # step counter+ step_counter = torch.zeros(16, 2, dtype=torch.int32) # 16 is hardcoded for averaging...+ self.register_buffer('step_counter', step_counter)+ self.mean_count = 0+ self.local_step = 0+++ def forward(self, x, d):+ raise NotImplementedError()++ def density(self, x):+ raise NotImplementedError()++ def color(self, x, d, mask=None, **kwargs):+ raise NotImplementedError()++ def reset_extra_state(self):+ if not self.cuda_ray:+ return+ # density grid+ self.density_grid.zero_()+ self.mean_density = 0+ self.iter_density = 0+ # step counter+ self.step_counter.zero_()+ self.mean_count = 0+ self.local_step = 0++ @torch.no_grad()+ def export_mesh(self, path, resolution=None, S=128):++ if resolution is None:+ resolution = self.grid_size++ if self.cuda_ray:+ density_thresh = min(self.mean_density, self.density_thresh)+ else:+ density_thresh = self.density_thresh++ sigmas = np.zeros([resolution, resolution, resolution], dtype=np.float32)++ # query+ X = torch.linspace(-1, 1, resolution).split(S)+ Y = torch.linspace(-1, 1, resolution).split(S)+ Z = torch.linspace(-1, 1, resolution).split(S)++ for xi, xs in enumerate(X):+ for yi, ys in enumerate(Y):+ for zi, zs in enumerate(Z):+ xx, yy, zz = custom_meshgrid(xs, ys, zs)+ pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) # [S, 3]+ val = self.density(pts.to(self.aabb_train.device))+ sigmas[xi * S: xi * S + len(xs), yi * S: yi * S + len(ys), zi * S: zi * S + len(zs)] = val['sigma'].reshape(len(xs), len(ys), len(zs)).detach().cpu().numpy() # [S, 1] --> [x, y, z]++ vertices, triangles = mcubes.marching_cubes(sigmas, density_thresh)++ vertices = vertices / (resolution - 1.0) * 2 - 1+ vertices = vertices.astype(np.float32)+ triangles = triangles.astype(np.int32)++ v = torch.from_numpy(vertices).to(self.aabb_train.device)+ f = torch.from_numpy(triangles).int().to(self.aabb_train.device)+++ # texture?+ def _export(v, f, h0=2048, w0=2048, ssaa=1, name=''):+ # v, f: torch Tensor+ device = v.device+ v_np = v.cpu().numpy() # [N, 3]+ f_np = f.cpu().numpy() # [M, 3]++ print(f'[INFO] running xatlas to unwrap UVs for mesh: v={v_np.shape} f={f_np.shape}')++ # unwrap uvs+ import xatlas+ import nvdiffrast.torch as dr+ from sklearn.neighbors import NearestNeighbors+ from scipy.ndimage import binary_dilation, binary_erosion++ glctx = dr.RasterizeCudaContext()++ atlas = xatlas.Atlas()+ atlas.add_mesh(v_np, f_np)+ chart_options = xatlas.ChartOptions()+ chart_options.max_iterations = 0 # disable merge_chart for faster unwrap...+ atlas.generate(chart_options=chart_options)+ vmapping, ft_np, vt_np = atlas[0] # [N], [M, 3], [N, 2]++ # vmapping, ft_np, vt_np = xatlas.parametrize(v_np, f_np) # [N], [M, 3], [N, 2]++ vt = torch.from_numpy(vt_np.astype(np.float32)).float().to(device)+ ft = torch.from_numpy(ft_np.astype(np.int64)).int().to(device)++ # render uv maps+ uv = vt * 2.0 - 1.0 # uvs to range [-1, 1]+ uv = torch.cat((uv, torch.zeros_like(uv[..., :1]), torch.ones_like(uv[..., :1])), dim=-1) # [N, 4]++ if ssaa > 1:+ h = int(h0 * ssaa)+ w = int(w0 * ssaa)+ else:+ h, w = h0, w0++ rast, _ = dr.rasterize(glctx, uv.unsqueeze(0), ft, (h, w)) # [1, h, w, 4]+ xyzs, _ = dr.interpolate(v.unsqueeze(0), rast, f) # [1, h, w, 3]+ mask, _ = dr.interpolate(torch.ones_like(v[:, :1]).unsqueeze(0), rast, f) # [1, h, w, 1]++ # masked query+ xyzs = xyzs.view(-1, 3)+ mask = (mask > 0).view(-1)++ sigmas = torch.zeros(h * w, device=device, dtype=torch.float32)+ feats = torch.zeros(h * w, 3, device=device, dtype=torch.float32)++ if mask.any():+ xyzs = xyzs[mask] # [M, 3]++ # batched inference to avoid OOM+ all_sigmas = []+ all_feats = []+ head = 0+ while head < xyzs.shape[0]:+ tail = min(head + 640000, xyzs.shape[0])+ results_ = self.density(xyzs[head:tail])+ all_sigmas.append(results_['sigma'].float())+ all_feats.append(results_['albedo'].float())+ head += 640000++ sigmas[mask] = torch.cat(all_sigmas, dim=0)+ feats[mask] = torch.cat(all_feats, dim=0)++ sigmas = sigmas.view(h, w, 1)+ feats = feats.view(h, w, -1)+ mask = mask.view(h, w)++ ### alpha mask+ # quantize [0.0, 1.0] to [0, 255]+ feats = feats.cpu().numpy()+ feats = (feats * 255).astype(np.uint8)++ # alphas = alphas.cpu().numpy()+ # alphas = (alphas * 255).astype(np.uint8)++ ### NN search as an antialiasing ...+ mask = mask.cpu().numpy()++ inpaint_region = binary_dilation(mask, iterations=3)+ inpaint_region[mask] = 0++ search_region = mask.copy()+ not_search_region = binary_erosion(search_region, iterations=2)+ search_region[not_search_region] = 0++ search_coords = np.stack(np.nonzero(search_region), axis=-1)+ inpaint_coords = np.stack(np.nonzero(inpaint_region), axis=-1)++ knn = NearestNeighbors(n_neighbors=1, algorithm='kd_tree').fit(search_coords)+ _, indices = knn.kneighbors(inpaint_coords)++ feats[tuple(inpaint_coords.T)] = feats[tuple(search_coords[indices[:, 0]].T)]++ # do ssaa after the NN search, in numpy+ feats = cv2.cvtColor(feats, cv2.COLOR_RGB2BGR)++ if ssaa > 1:+ # alphas = cv2.resize(alphas, (w0, h0), interpolation=cv2.INTER_NEAREST)+ feats = cv2.resize(feats, (w0, h0), interpolation=cv2.INTER_LINEAR)++ # cv2.imwrite(os.path.join(path, f'alpha.png'), alphas)+ cv2.imwrite(os.path.join(path, f'{name}albedo.png'), feats)++ # save obj (v, vt, f /)+ obj_file = os.path.join(path, f'{name}mesh.obj')+ mtl_file = os.path.join(path, f'{name}mesh.mtl')++ print(f'[INFO] writing obj mesh to {obj_file}')+ with open(obj_file, "w") as fp:+ fp.write(f'mtllib {name}mesh.mtl \n')++ print(f'[INFO] writing vertices {v_np.shape}')+ for v in v_np:+ fp.write(f'v {v[0]} {v[1]} {v[2]} \n')++ print(f'[INFO] writing vertices texture coords {vt_np.shape}')+ for v in vt_np:+ fp.write(f'vt {v[0]} {1 - v[1]} \n')++ print(f'[INFO] writing faces {f_np.shape}')+ fp.write(f'usemtl mat0 \n')+ for i in range(len(f_np)):+ fp.write(f"f {f_np[i, 0] + 1}/{ft_np[i, 0] + 1} {f_np[i, 1] + 1}/{ft_np[i, 1] + 1} {f_np[i, 2] + 1}/{ft_np[i, 2] + 1} \n")++ with open(mtl_file, "w") as fp:+ fp.write(f'newmtl mat0 \n')+ fp.write(f'Ka 1.000000 1.000000 1.000000 \n')+ fp.write(f'Kd 1.000000 1.000000 1.000000 \n')+ fp.write(f'Ks 0.000000 0.000000 0.000000 \n')+ fp.write(f'Tr 1.000000 \n')+ fp.write(f'illum 1 \n')+ fp.write(f'Ns 0.000000 \n')+ fp.write(f'map_Kd {name}albedo.png \n')++ _export(v, f)++ def run(self, rays_o, rays_d, ref_bg=None, num_steps=128, upsample_steps=128, light_d=None, ambient_ratio=1.0, shading='albedo', bg_color=None, perturb=False, **kwargs):+ # rays_o, rays_d: [B, N, 3], assumes B == 1+ # bg_color: [BN, 3] in range [0, 1]+ # return: image: [B, N, 3], depth: [B, N]++ prefix = rays_o.shape[:-1]+ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)++ N = rays_o.shape[0] # N = B * N, in fact+ device = rays_o.device++ results = {}++ # choose aabb+ aabb = self.aabb_train if self.training else self.aabb_infer++ # sample steps+ nears, fars = near_far_from_bound(rays_o, rays_d, self.bound, type='sphere', min_near=self.min_near)++ # random sample light_d if not provided+ if light_d is None:+ # gaussian noise around the ray origin, so the light always face the view dir (avoid dark face)+ light_d = (rays_o[0] + torch.randn(3, device=device, dtype=torch.float))+ light_d = safe_normalize(light_d)++ z_vals = torch.linspace(0.0, 1.0, num_steps, device=device).unsqueeze(0) # [1, T]+ z_vals = z_vals.expand((N, num_steps)) # [N, T]+ z_vals = nears + (fars - nears) * z_vals # [N, T], in [nears, fars]++ # perturb z_vals+ sample_dist = (fars - nears) / num_steps+ if perturb:+ z_vals = z_vals + (torch.rand(z_vals.shape, device=device) - 0.5) * sample_dist++ # generate xyzs+ xyzs = rays_o.unsqueeze(-2) + rays_d.unsqueeze(-2) * z_vals.unsqueeze(-1) # [N, 1, 3] * [N, T, 1] -> [N, T, 3]+ xyzs = torch.min(torch.max(xyzs, aabb[:3]), aabb[3:]) # a manual clip.++ #plot_pointcloud(xyzs.reshape(-1, 3).detach().cpu().numpy())++ # query SDF and RGB+ density_outputs = self.density(xyzs.reshape(-1, 3))++ #sigmas = density_outputs['sigma'].view(N, num_steps) # [N, T]+ for k, v in density_outputs.items():+ density_outputs[k] = v.view(N, num_steps, -1)++ # upsample z_vals (nerf-like)+ if upsample_steps > 0:+ with torch.no_grad():++ deltas = z_vals[..., 1:] - z_vals[..., :-1] # [N, T-1]+ deltas = torch.cat([deltas, sample_dist * torch.ones_like(deltas[..., :1])], dim=-1)++ alphas = 1 - torch.exp(-deltas * density_outputs['sigma'].squeeze(-1)) # [N, T]+ alphas_shifted = torch.cat([torch.ones_like(alphas[..., :1]), 1 - alphas + 1e-15], dim=-1) # [N, T+1]+ weights = alphas * torch.cumprod(alphas_shifted, dim=-1)[..., :-1] # [N, T]++ # sample new z_vals+ z_vals_mid = (z_vals[..., :-1] + 0.5 * deltas[..., :-1]) # [N, T-1]+ new_z_vals = sample_pdf(z_vals_mid, weights[:, 1:-1], upsample_steps, det=not self.training).detach() # [N, t]++ new_xyzs = rays_o.unsqueeze(-2) + rays_d.unsqueeze(-2) * new_z_vals.unsqueeze(-1) # [N, 1, 3] * [N, t, 1] -> [N, t, 3]+ new_xyzs = torch.min(torch.max(new_xyzs, aabb[:3]), aabb[3:]) # a manual clip.++ # only forward new points to save computation+ new_density_outputs = self.density(new_xyzs.reshape(-1, 3))+ #new_sigmas = new_density_outputs['sigma'].view(N, upsample_steps) # [N, t]+ for k, v in new_density_outputs.items():+ new_density_outputs[k] = v.view(N, upsample_steps, -1)++ # re-order+ z_vals = torch.cat([z_vals, new_z_vals], dim=1) # [N, T+t]+ z_vals, z_index = torch.sort(z_vals, dim=1)++ xyzs = torch.cat([xyzs, new_xyzs], dim=1) # [N, T+t, 3]+ xyzs = torch.gather(xyzs, dim=1, index=z_index.unsqueeze(-1).expand_as(xyzs))++ for k in density_outputs:+ tmp_output = torch.cat([density_outputs[k], new_density_outputs[k]], dim=1)+ density_outputs[k] = torch.gather(tmp_output, dim=1, index=z_index.unsqueeze(-1).expand_as(tmp_output))++ deltas = z_vals[..., 1:] - z_vals[..., :-1] # [N, T+t-1]+ deltas = torch.cat([deltas, sample_dist * torch.ones_like(deltas[..., :1])], dim=-1)+ alphas = 1 - torch.exp(-deltas * density_outputs['sigma'].squeeze(-1)) # [N, T+t]+ alphas_shifted = torch.cat([torch.ones_like(alphas[..., :1]), 1 - alphas + 1e-15], dim=-1) # [N, T+t+1]+ weights = alphas * torch.cumprod(alphas_shifted, dim=-1)[..., :-1] # [N, T+t]++ dirs = rays_d.view(-1, 1, 3).expand_as(xyzs)+ for k, v in density_outputs.items():+ density_outputs[k] = v.view(-1, v.shape[-1])++ sigmas, rgbs, normals = self(xyzs.reshape(-1, 3), dirs.reshape(-1, 3), light_d, ratio=ambient_ratio, shading=shading)+ rgbs = rgbs.view(N, -1, 3) # [N, T+t, 3]++ if normals is not None:++ # calculate normal+ normal_map = normals.reshape(N, -1, 3) # [N, T, 3]+ normal_map = torch.sum(normal_map * weights[:, :, None], dim=1)++ # orientation loss+ normals = normals.view(N, -1, 3)+ loss_orient = weights.detach() * (normals * dirs).sum(-1).clamp(min=0) ** 2+ results['loss_orient'] = loss_orient.sum(-1).mean()++ # surface normal smoothness+ if self.opt.lambda_smooth > 0:+ normals_perturb = self.normal(xyzs.reshape(-1, 3) + torch.randn_like(xyzs).reshape(-1, 3) * 1e-2).view(N, -1, 3)+ loss_smooth = (normals - normals_perturb).abs()+ results['loss_smooth'] = loss_smooth.mean()++ # calculate weight_sum (mask)+ weights_sum = weights.sum(dim=-1) # [N]++ # calculate depth+ depth = torch.sum(weights * z_vals, dim=-1)++ # calculate color+ image = torch.sum(weights.unsqueeze(-1) * rgbs, dim=-2) # [N, 3], in [0, 1]++ # mix background color+ if self.bg_radius > 0:+ bg_color = self.background(rays_d.reshape(-1, 3)) # [N, 3]+ elif bg_color is None:+ bg_color = 1++ fg_image = image+ bg_image = bg_color.view(*prefix, 3)+ fg_image = fg_image.view(*prefix, 3)++ image = image + (1 - weights_sum).unsqueeze(-1) * bg_color++ image = image.view(*prefix, 3)+ depth = depth.view(*prefix, 1)++ mask = (nears < fars).reshape(*prefix)++ results['image'] = image+ results['depth'] = depth+ results['weights_sum'] = weights_sum+ results['mask'] = mask+ results['normal'] = normal_map+ if self.bg_radius > 0:+ results['bg'] = bg_image++ return results++ def run_cuda(self, rays_o, rays_d, depth_scale=None, bg_color=None, dt_gamma=0, light_d=None, ambient_ratio=1.0, shading='albedo', perturb=False, force_all_rays=False, max_steps=1024, T_thresh=1e-4, **kwargs):+ # rays_o, rays_d: [B, N, 3], assumes B == 1+ # return: image: [B, N, 3], depth: [B, N]+ B = rays_o.shape[0]+ prefix = rays_o.shape[:-1]+ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)++ N = rays_o.shape[0] # N = B * N, in fact+ device = rays_o.device++ # pre-calculate near far+ nears, fars = raymarching.near_far_from_aabb(rays_o, rays_d, self.aabb_train if self.training else self.aabb_infer)++ # random sample light_d if not provided+ if light_d is None:+ # gaussian noise around the ray origin, so the light always face the view dir (avoid dark face)+ light_d = (rays_o[0] + torch.randn(3, device=device, dtype=torch.float))+ light_d = safe_normalize(light_d)++ results = {}++ if self.training:+ # setup counter+ counter = self.step_counter[self.local_step % 16]+ counter.zero_() # set to 0+ self.local_step += 1+ xyzs, dirs, deltas, rays = raymarching.march_rays_train(rays_o, rays_d, self.bound, self.density_bitfield, self.cascade, self.grid_size, nears, fars, counter, self.mean_count, perturb, 128, force_all_rays, dt_gamma, max_steps)+ sigmas, rgbs, normals = self(xyzs, dirs, light_d, ratio=ambient_ratio, shading=shading)+ weights_sum, depth, image = raymarching.composite_rays_train(sigmas, rgbs, deltas, rays, T_thresh)+ # exit()+ # normals related regularizations+ if normals is not None:+ # orientation loss (not very exact in cuda ray mode)+ weights = 1 - torch.exp(-sigmas)++ loss_orient = weights.detach() * (normals * dirs).sum(-1).clamp(min=0) ** 2+ results['loss_orient'] = loss_orient.mean()++ # surface normal smoothness+ if self.opt.lambda_smooth > 0:+ normals_perturb = self.normal(xyzs + torch.randn_like(xyzs) * 1e-2)+ loss_smooth = (normals - normals_perturb).abs()+ results['loss_smooth'] = loss_smooth.mean()++ else:+ # allocate outputs+ dtype = torch.float32++ weights_sum = torch.zeros(N, dtype=dtype, device=device)+ depth = torch.zeros(N, dtype=dtype, device=device)+ image = torch.zeros(N, 3, dtype=dtype, device=device)+ normal = torch.zeros(N, 3, dtype=dtype, device=device)+ n_alive = N+ rays_alive = torch.arange(n_alive, dtype=torch.int32, device=device) # [N]+ rays_t = nears.clone() # [N]+ step = 0+ while step < max_steps: # hard coded max step+ # count alive rays+ n_alive = rays_alive.shape[0]+ # exit loop+ if n_alive <= 0:+ break+ # decide compact_steps+ n_step = max(min(N // n_alive, 8), 1)+ xyzs, dirs, deltas = raymarching.march_rays(n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, self.bound, self.density_bitfield, self.cascade, self.grid_size, nears, fars, 128, perturb if step == 0 else False, dt_gamma, max_steps)+ sigmas, rgbs, normals = self(xyzs, dirs, light_d, ratio=ambient_ratio, shading=shading)+ normals = (normals + 1) / 2+ raymarching.composite_rays(n_alive, n_step, rays_alive, rays_t, sigmas, rgbs, normals, deltas, weights_sum, depth, image, normal, T_thresh)+ rays_alive = rays_alive[rays_alive >= 0]+ step += n_step++ # mix background color+ if bg_color is None:+ bg_color = 1++ image = image + (1 - weights_sum).unsqueeze(-1) * bg_color+ image = image.view(*prefix, 3)++ if not self.training:+ normal = normal + (1 - weights_sum).unsqueeze(-1) * bg_color+ normal = normal.view(*prefix, 3)+++ bg_depth = self.opt.max_depth+ depth = depth + (1 - weights_sum) * bg_depth+ if depth_scale is not None:+ depth = depth.view(*prefix, 1) * depth_scale.view(*prefix, 1)+ else:+ depth = depth.view(*prefix, 1)++ weights_sum = weights_sum.reshape(*prefix)++ mask = (nears < fars).reshape(*prefix)++ results['image'] = image+ results['depth'] = depth+ results['weights_sum'] = weights_sum+ results['mask'] = mask+ if not self.training:+ results['normal'] = normal++ return results+++ @torch.no_grad()+ def update_extra_state(self, decay=0.95, S=128):+ # call before each epoch to update extra states.++ if not self.cuda_ray:+ return++ ### update density grid+ tmp_grid = - torch.ones_like(self.density_grid)++ X = torch.arange(self.grid_size, dtype=torch.int32, device=self.aabb_train.device).split(S)+ Y = torch.arange(self.grid_size, dtype=torch.int32, device=self.aabb_train.device).split(S)+ Z = torch.arange(self.grid_size, dtype=torch.int32, device=self.aabb_train.device).split(S)++ for xs in X:+ for ys in Y:+ for zs in Z:++ # construct points+ xx, yy, zz = custom_meshgrid(xs, ys, zs)+ coords = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) # [N, 3], in [0, 128)+ indices = raymarching.morton3D(coords).long() # [N]+ xyzs = 2 * coords.float() / (self.grid_size - 1) - 1 # [N, 3] in [-1, 1]++ # cascading+ for cas in range(self.cascade):+ bound = min(2 ** cas, self.bound)+ half_grid_size = bound / self.grid_size+ # scale to current cascade's resolution+ cas_xyzs = xyzs * (bound - half_grid_size)+ # add noise in [-hgs, hgs]+ cas_xyzs += (torch.rand_like(cas_xyzs) * 2 - 1) * half_grid_size+ # query density+ sigmas = self.density(cas_xyzs)['sigma'].reshape(-1).detach()+ # assign+ tmp_grid[cas, indices] = sigmas++ # ema update+ valid_mask = self.density_grid >= 0+ self.density_grid[valid_mask] = torch.maximum(self.density_grid[valid_mask] * decay, tmp_grid[valid_mask])+ self.mean_density = torch.mean(self.density_grid[valid_mask]).item()+ self.iter_density += 1++ # convert to bitfield+ density_thresh = min(self.mean_density, self.density_thresh)+ self.density_bitfield = raymarching.packbits(self.density_grid, density_thresh, self.density_bitfield)++ ### update step counter+ total_step = min(16, self.local_step)+ if total_step > 0:+ self.mean_count = int(self.step_counter[:total_step, 0].sum().item() / total_step)+ self.local_step = 0++ # print(f'[density grid] min={self.density_grid.min().item():.4f}, max={self.density_grid.max().item():.4f}, mean={self.mean_density:.4f}, occ_rate={(self.density_grid > density_thresh).sum() / (128**3 * self.cascade):.3f} | [step counter] mean={self.mean_count}')+++ def render(self, rays_o, rays_d, depth_scale=None, staged=False, max_ray_batch=4096, **kwargs):+ # rays_o, rays_d: [B, N, 3], assumes B == 1+ # return: pred_rgb: [B, N, 3]++ if self.cuda_ray:+ _run = self.run_cuda+ else:+ _run = self.run++ B, N = rays_o.shape[:2]+ device = rays_o.device++ # never stage when cuda_ray+ if staged and not self.cuda_ray:+ depth = torch.empty((B, N, 1), device=device)+ image = torch.empty((B, N, 3), device=device)+ weights_sum = torch.empty((B, N), device=device)++ for b in range(B):+ head = 0+ while head < N:+ tail = min(head + max_ray_batch, N)+ results_ = _run(rays_o[b:b+1, head:tail], rays_d[b:b+1, head:tail], **kwargs)+ depth[b:b+1, head:tail] = results_['depth']+ weights_sum[b:b+1, head:tail] = results_['weights_sum']+ image[b:b+1, head:tail] = results_['image']+ head += max_ray_batch++ results = {}+ results['depth'] = depth+ results['image'] = image+ results['weights_sum'] = weights_sum++ else:+ results = _run(rays_o, rays_d, depth_scale, **kwargs)++ return results\ No newline at end of filediff --git a/nerf/sd.py b/nerf/sd.pynew file mode 100644index 0000000..542bec0--- /dev/null+++ b/nerf/sd.py@@ -0,0 +1,272 @@+from transformers import CLIPTextModel, CLIPTokenizer, logging, CLIPVisionModel, CLIPFeatureExtractor+from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler, DDIMScheduler++# suppress partial model loading warning+logging.set_verbosity_error()++import torch+import torch.nn as nn+import torch.nn.functional as F+from torchvision.utils import save_image+import torchvision.transforms as T+import time+import os+import clip+def seed_everything(seed):+ torch.manual_seed(seed)+ torch.cuda.manual_seed(seed)+ #torch.backends.cudnn.deterministic = True+ #torch.backends.cudnn.benchmark = True++class StableDiffusion(nn.Module):+ def __init__(self, device, sd_version='2.0', hf_key=None, step_range=[0.2, 0.6]):+ super().__init__()++ self.device = device+ self.sd_version = sd_version++ print(f'[INFO] loading stable diffusion...')++ if hf_key is not None:+ print(f'[INFO] using hugging face custom model key: {hf_key}')+ model_key = hf_key+ elif self.sd_version == '2.0':+ model_key = "stabilityai/stable-diffusion-2-base"+ elif self.sd_version == '1.5':+ model_key = "runwayml/stable-diffusion-v1-5"+ else:+ raise ValueError(f'Stable-diffusion version {self.sd_version} not supported.')++ # Create model+ self.vae = AutoencoderKL.from_pretrained(model_key, subfolder="vae").to(self.device)+ self.tokenizer = CLIPTokenizer.from_pretrained(model_key, subfolder="tokenizer")+ self.text_encoder = CLIPTextModel.from_pretrained(model_key, subfolder="text_encoder").to(self.device)+ self.image_encoder = CLIPVisionModel.from_pretrained("openai/clip-vit-large-patch14").to(self.device)+ self.text_clip_encoder = CLIPVisionModel.from_pretrained("openai/clip-vit-large-patch14").to(self.device)++ self.processor = CLIPFeatureExtractor.from_pretrained("openai/clip-vit-large-patch14")++ self.aug = T.Compose([+ T.Resize((224, 224)),+ T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),+ ])+ self.unet = UNet2DConditionModel.from_pretrained(model_key, subfolder="unet").to(self.device)++ self.scheduler = DDIMScheduler.from_pretrained(model_key, subfolder="scheduler")+ # self.scheduler = PNDMScheduler.from_pretrained(model_key, subfolder="scheduler")++ self.num_train_timesteps = self.scheduler.config.num_train_timesteps+ self.num_inference_steps = 50+ self.min_step = int(self.num_train_timesteps * float(step_range[0]))+ self.max_step = int(self.num_train_timesteps * float(step_range[1]))+ self.alphas = self.scheduler.alphas_cumprod.to(self.device) # for convenience+ self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod.to(self.device)+ self.ref_imgs = None++ print(f'[INFO] loaded stable diffusion!')++ def get_text_embeds(self, prompt, negative_prompt):+ # prompt, negative_prompt: [str]++ # Tokenize text and get embeddings+ text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')++ with torch.no_grad():+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]++ # Do the same for unconditional embeddings+ uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length, return_tensors='pt')++ with torch.no_grad():+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]++ # Cat for final embeddings+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])+ return text_embeddings++ def get_img_embeds(self, prompt_img):+ # Tokenize text and get embeddings+ prompt_img = prompt_img.squeeze(0)+ img_input = self.processor(images=prompt_img.detach().cpu().numpy(), return_tensors='pt')++ with torch.no_grad():+ img_embeddings = self.image_encoder(img_input.pixel_values.to(self.device))[0]++ return img_embeddings++ def img_clip_loss(self, clip_model, rgb1, rgb2):+ image_z_1 = clip_model.encode_image(self.aug(rgb1))+ image_z_2 = clip_model.encode_image(self.aug(rgb2))+ image_z_1 = image_z_1 / image_z_1.norm(dim=-1, keepdim=True) # normalize features+ image_z_2 = image_z_2 / image_z_2.norm(dim=-1, keepdim=True) # normalize features++ loss = - (image_z_1 * image_z_2).sum(-1).mean()+ return loss++ def img_text_clip_loss(self, clip_model, rgb, prompt):+ image_z_1 = clip_model.encode_image(self.aug(rgb))+ image_z_1 = image_z_1 / image_z_1.norm(dim=-1, keepdim=True) # normalize features++ text = clip.tokenize(prompt).to(self.device)+ text_z = clip_model.encode_text(text)+ text_z = text_z / text_z.norm(dim=-1, keepdim=True)+ loss = - (image_z_1 * text_z).sum(-1).mean()+ return loss+++ def train_step(self, text_embeddings, pred_rgb, ref_rgb=None, noise=None, islarge=False, ref_text=None, clip_model=None, guidance_scale=10):++ # interp to 512x512 to be fed into vae.+ loss = 0+ imgs = None++ # _t = time.time()+ pred_rgb_512 = F.interpolate(pred_rgb, (512, 512), mode='bilinear', align_corners=False)+ # torch.cuda.synchronize(); print(f'[TIME] guiding: interp {time.time() - _t:.4f}s')++ # timestep ~ U(0.02, 0.98) to avoid very high/low noise level+ t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device)+ w_ = 1.0++ # encode image into latents with vae, requires grad!+ # _t = time.time()+ latents = self.encode_imgs(pred_rgb_512)+ # torch.cuda.synchronize(); print(f'[TIME] guiding: vae enc {time.time() - _t:.4f}s')++ # predict the noise residual with unet, NO grad!+ # _t = time.time()+ with torch.no_grad():+ # add noise+ noise = torch.randn_like(latents)+ latents_noisy = self.scheduler.add_noise(latents, noise, t)+ # pred noise+ latent_model_input = torch.cat([latents_noisy] * 2)+ latent_model_input = latent_model_input.detach().requires_grad_()++ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample+ # torch.cuda.synchronize(); print(f'[TIME] guiding: unet {time.time() - _t:.4f}s')++ # perform guidance+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)+ noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond)++ if not islarge and (t / self.num_train_timesteps) <= 0.4:+ self.scheduler.set_timesteps(self.num_train_timesteps)+ de_latents = self.scheduler.step(noise_pred, t, latents_noisy)['prev_sample']+ # de_latents = de_latents.detach().requires_grad_()+ imgs = self.decode_latents(de_latents)+ loss = 10 * self.img_clip_loss(clip_model, imgs, ref_rgb) + \+ 10 * self.img_text_clip_loss(clip_model, imgs, ref_text)++ # grad = torch.autograd.grad(loss_clip, de_latents, retain_graph=True)[0]+ # print(f"loss clip: {loss}")+ else:+ # w(t), sigma_t^2+ w = (1 - self.alphas[t])+ grad = w * (noise_pred - noise) * w_+ imgs = None++ # clip grad for stable training?+ grad = torch.nan_to_num(grad)+ latents.backward(gradient=grad, retain_graph=True)+ loss = 0++ return loss, imgs # dummy loss value++ def produce_latents(self, text_embeddings, height=512, width=512, num_inference_steps=50, guidance_scale=7.5, latents=None):++ if latents is None:+ latents = torch.randn((text_embeddings.shape[0] // 2, self.unet.in_channels, height // 8, width // 8), device=self.device)++ self.scheduler.set_timesteps(num_inference_steps)++ with torch.autocast('cuda'):+ for i, t in enumerate(self.scheduler.timesteps):+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.+ latent_model_input = torch.cat([latents] * 2)++ # predict the noise residual+ with torch.no_grad():+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings)['sample']++ # perform guidance+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)+ noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond)++ # compute the previous noisy sample x_t -> x_t-1+ latents = self.scheduler.step(noise_pred, t, latents)['prev_sample']++ return latents++ def decode_latents(self, latents):++ latents = 1 / 0.18215 * latents++ # with torch.no_grad():+ imgs = self.vae.decode(latents).sample++ imgs = (imgs / 2 + 0.5).clamp(0, 1)++ return imgs++ def encode_imgs(self, imgs):+ # imgs: [B, 3, H, W]++ imgs = 2 * imgs - 1++ posterior = self.vae.encode(imgs).latent_dist+ latents = posterior.sample() * 0.18215++ return latents++ def prompt_to_img(self, prompts, negative_prompts='', height=512, width=512, num_inference_steps=50, guidance_scale=7.5, latents=None):++ if isinstance(prompts, str):+ prompts = [prompts]++ if isinstance(negative_prompts, str):+ negative_prompts = [negative_prompts]++ # Prompts -> text embeds+ text_embeds = self.get_text_embeds(prompts, negative_prompts) # [2, 77, 768]++ # Text embeds -> img latents+ latents = self.produce_latents(text_embeds, height=height, width=width, latents=latents, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale) # [1, 4, 64, 64]++ # Img latents -> imgs+ imgs = self.decode_latents(latents) # [1, 3, 512, 512]+ return imgs+++if __name__ == '__main__':++ import argparse+ import matplotlib.pyplot as plt++ parser = argparse.ArgumentParser()+ parser.add_argument('prompt', type=str)+ parser.add_argument('--negative', default='', type=str)+ parser.add_argument('--workspace', default='', type=str)+ parser.add_argument('--sd_version', type=str, default='2.0', choices=['1.5', '2.0'], help="stable diffusion version")+ parser.add_argument('-H', type=int, default=512)+ parser.add_argument('-W', type=int, default=512)+ parser.add_argument('--seeds', type=int, default=0)+ # parser.add_argument('--seeds', nargs='+', default=[0, 1, 2])+ parser.add_argument('--steps', type=int, default=50)+ opt = parser.parse_args()++ opt.workspace = os.path.join('test_bench', opt.workspace)+ if opt.workspace is not None:+ os.makedirs(opt.workspace, exist_ok=True)+ device = torch.device('cuda')++ sd = StableDiffusion(device, opt.sd_version)++ for seed in range(opt.seeds):+ seed_everything(seed)+ imgs = sd.prompt_to_img(opt.prompt, opt.negative, opt.H, opt.W, opt.steps, guidance_scale=7.5)+ save_image(imgs, os.path.join(opt.workspace, opt.prompt.replace(" ", "_") + f'_{seed}.png'))++++diff --git a/nerf/utils.py b/nerf/utils.pynew file mode 100644index 0000000..61ef22b--- /dev/null+++ b/nerf/utils.py@@ -0,0 +1,978 @@+import os+import glob+import tqdm+import math+import imageio+import random+import warnings+import tensorboardX++import numpy as np+import pandas as pd++import time+from datetime import datetime++import cv2+import matplotlib.pyplot as plt++import torch+import torch.nn as nn+import torch.optim as optim+import torch.nn.functional as F+import torch.distributed as dist+from torch.utils.data import Dataset, DataLoader+from torchvision.utils import save_image++import trimesh+import mcubes+from rich.console import Console+from torch_ema import ExponentialMovingAverage++import clip+import torchvision.transforms as T+from torchmetrics import PearsonCorrCoef++from packaging import version as pver++def custom_meshgrid(*args):+ # ref: https://pytorch.org/docs/stable/generated/torch.meshgrid.html?highlight=meshgrid#torch.meshgrid+ if pver.parse(torch.__version__) < pver.parse('1.10'):+ return torch.meshgrid(*args)+ else:+ return torch.meshgrid(*args, indexing='ij')++def safe_normalize(x, eps=1e-20):+ return x / torch.sqrt(torch.clamp(torch.sum(x * x, -1, keepdim=True), min=eps, max=1e32))+[email protected](enabled=False)+def get_rays(poses, intrinsics, H, W, N=-1, error_map=None):+ ''' get rays+ Args:+ poses: [B, 4, 4], cam2world+ intrinsics: [4]+ H, W, N: int+ error_map: [B, 128 * 128], sample probability based on training error+ Returns:+ rays_o, rays_d: [B, N, 3]+ inds: [B, N]+ '''++ device = poses.device+ B = poses.shape[0]+ fx, fy, cx, cy = intrinsics++ i, j = custom_meshgrid(torch.linspace(0, W-1, W, device=device), torch.linspace(0, H-1, H, device=device))+ i = i.t().reshape([1, H*W]).expand([B, H*W]) + 0.5+ j = j.t().reshape([1, H*W]).expand([B, H*W]) + 0.5++ results = {}++ if N > 0:+ N = min(N, H*W)++ if error_map is None:+ inds = torch.randint(0, H*W, size=[N], device=device) # may duplicate+ inds = inds.expand([B, N])+ else:++ # weighted sample on a low-reso grid+ inds_coarse = torch.multinomial(error_map.to(device), N, replacement=False) # [B, N], but in [0, 128*128)++ # map to the original resolution with random perturb.+ inds_x, inds_y = inds_coarse // 128, inds_coarse % 128 # `//` will throw a warning in torch 1.10... anyway.+ sx, sy = H / 128, W / 128+ inds_x = (inds_x * sx + torch.rand(B, N, device=device) * sx).long().clamp(max=H - 1)+ inds_y = (inds_y * sy + torch.rand(B, N, device=device) * sy).long().clamp(max=W - 1)+ inds = inds_x * W + inds_y++ results['inds_coarse'] = inds_coarse # need this when updating error_map++ i = torch.gather(i, -1, inds)+ j = torch.gather(j, -1, inds)++ results['inds'] = inds++ else:+ inds = torch.arange(H*W, device=device).expand([B, H*W])++ zs = torch.ones_like(i)+ xs = (i - cx) / fx * zs+ ys = (j - cy) / fy * zs+ directions = torch.stack((xs, ys, zs), dim=-1)+ scale = 1 / directions.pow(2).sum(-1).pow(0.5)++ directions = safe_normalize(directions)+ rays_d = directions @ poses[:, :3, :3].transpose(-1, -2) # (B, N, 3)+ rays_o = poses[..., :3, 3] # [B, 3]+ rays_o = rays_o[..., None, :].expand_as(rays_d) # [B, N, 3]++ results['rays_o'] = rays_o+ results['rays_d'] = rays_d+ results['depth_scale'] = scale++ return results+++def seed_everything(seed):+ random.seed(seed)+ os.environ['PYTHONHASHSEED'] = str(seed)+ np.random.seed(seed)+ torch.manual_seed(seed)+ torch.cuda.manual_seed(seed)+ #torch.backends.cudnn.deterministic = True+ #torch.backends.cudnn.benchmark = True+++def torch_vis_2d(x, renormalize=False):+ # x: [3, H, W] or [1, H, W] or [H, W]+ import matplotlib.pyplot as plt+ import numpy as np+ import torch++ if isinstance(x, torch.Tensor):+ if len(x.shape) == 3:+ x = x.permute(1,2,0).squeeze()+ x = x.detach().cpu().numpy()++ print(f'[torch_vis_2d] {x.shape}, {x.dtype}, {x.min()} ~ {x.max()}')++ x = x.astype(np.float32)++ # renormalize+ if renormalize:+ x = (x - x.min(axis=0, keepdims=True)) / (x.max(axis=0, keepdims=True) - x.min(axis=0, keepdims=True) + 1e-8)++ plt.imshow(x)+ plt.show()++def linear_to_srgb(x):+ return torch.where(x < 0.0031308, 12.92 * x, 1.055 * x ** 0.41666 - 0.055)+++def srgb_to_linear(x):+ return torch.where(x < 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)++def extract_fields(bound_min, bound_max, resolution, query_func):+ N = 256+ X = torch.linspace(bound_min[0], bound_max[0], resolution).split(N)+ Y = torch.linspace(bound_min[1], bound_max[1], resolution).split(N)+ Z = torch.linspace(bound_min[2], bound_max[2], resolution).split(N)++ u = np.zeros([resolution, resolution, resolution], dtype=np.float32)+ #with torch.no_grad():+ for xi, xs in enumerate(X):+ for yi, ys in enumerate(Y):+ for zi, zs in enumerate(Z):+ xx, yy, zz = torch.meshgrid(xs, ys, zs) # for torch < 1.10, should remove indexing='ij'+ pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1) # [1, N, 3]+ val = query_func(pts).reshape(len(xs), len(ys), len(zs)) # [1, N, 1] --> [x, y, z]+ u[xi * N: xi * N + len(xs), yi * N: yi * N + len(ys), zi * N: zi * N + len(zs)] = val.detach().cpu().numpy()+ del val+ return u+++def extract_geometry(bound_min, bound_max, resolution, threshold, query_func, use_sdf = False):+ #print('threshold: {}'.format(threshold))+ u = extract_fields(bound_min, bound_max, resolution, query_func)+ if use_sdf:+ u = - 1.0 *u++ #print(u.mean(), u.max(), u.min(), np.percentile(u, 50))++ vertices, triangles = mcubes.marching_cubes(u, threshold)++ b_max_np = bound_max.detach().cpu().numpy()+ b_min_np = bound_min.detach().cpu().numpy()++ vertices = vertices / (resolution - 1.0) * (b_max_np - b_min_np)[None, :] + b_min_np[None, :]++ return vertices, triangles++class Trainer(object):+ def __init__(self,+ name, # name of this experiment+ opt, # extra conf+ model, # network+ depth_model, # depth model+ guidance, # guidance network+ ref_imgs,+ ref_depth,+ ref_mask,+ ori_imgs=None,+ criterion=None, # loss function, if None, assume inline implementation in train_step+ optimizer=None, # optimizer+ ema_decay=None, # if use EMA, set the decay+ lr_scheduler=None, # scheduler+ metrics=[], # metrics for evaluation, if None, use val_loss to measure performance, else use the first metric.+ local_rank=0, # which GPU am I+ world_size=1, # total num of GPUs+ device=None, # device to use, usually setting to None is OK. (auto choose device)+ mute=False, # whether to mute all print+ fp16=False, # amp optimize level+ eval_interval=1, # eval once every $ epoch+ max_keep_ckpt=2, # max num of saved ckpts in disk+ workspace='workspace', # workspace to save logs & ckpts+ best_mode='min', # the smaller/larger result, the better+ use_loss_as_metric=True, # use loss as the first metric+ report_metric_at_train=False, # also report metrics at training+ use_checkpoint="latest", # which ckpt to use at init time+ use_tensorboardX=True, # whether to use tensorboard for logging+ scheduler_update_every_step=False, # whether to call scheduler.step() after every train step+ ):++ self.name = name+ self.opt = opt+ self.mute = mute+ self.metrics = metrics+ self.local_rank = local_rank+ self.world_size = world_size+ self.workspace = workspace+ self.ema_decay = ema_decay+ self.fp16 = fp16+ self.best_mode = best_mode+ self.use_loss_as_metric = use_loss_as_metric+ self.report_metric_at_train = report_metric_at_train+ self.max_keep_ckpt = max_keep_ckpt+ self.eval_interval = eval_interval+ self.use_checkpoint = use_checkpoint+ self.use_tensorboardX = use_tensorboardX+ self.time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S")+ self.scheduler_update_every_step = scheduler_update_every_step+ self.device = device if device is not None else torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else 'cpu')+ self.console = Console()+ self.clip_model, self.clip_preprocess = clip.load("ViT-B/16", device=self.device, jit=False)+ self.ref_imgs = ref_imgs+ self.ori_imgs = ori_imgs+ self.depth_prediction = ref_depth+ self.depth_mask = ref_mask++ model.to(self.device)+ if self.world_size > 1:+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)+ model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])+ self.model = model++ depth_model.to(self.device)+ if self.world_size > 1:+ depth_model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(depth_model)+ depth_model = torch.nn.parallel.DistributedDataParallel(depth_model, device_ids=[local_rank])+ self.depth_model = depth_model+ self.depth_model.eval()++ self.depth_transform = T.Compose(+ [+ T.Resize((384, 384)),+ T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),+ ]+ )++ # guide model+ self.guidance = guidance++ # text prompt+ if self.guidance is not None:++ for p in self.guidance.parameters():+ p.requires_grad = False++ self.prepare_text_embeddings()++ else:+ self.text_z = None++ if isinstance(criterion, nn.Module):+ criterion.to(self.device)+ self.criterion = criterion+ self.pearson = PearsonCorrCoef().to(self.device)+++ if optimizer is None:+ self.optimizer = optim.Adam(self.model.parameters(), lr=0.001, weight_decay=5e-4) # naive adam+ else:+ self.optimizer = optimizer(self.model)++ if lr_scheduler is None:+ self.lr_scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lambda epoch: 1) # fake scheduler+ else:+ self.lr_scheduler = lr_scheduler(self.optimizer)++ if ema_decay is not None:+ self.ema = ExponentialMovingAverage(self.model.parameters(), decay=ema_decay)+ else:+ self.ema = None++ self.scaler = torch.cuda.amp.GradScaler(enabled=self.fp16)++ # variable init+ self.epoch = 0+ self.global_step = 0+ self.local_step = 0+ self.stats = {+ "loss": [],+ "valid_loss": [],+ "results": [], # metrics[0], or valid_loss+ "checkpoints": [], # record path of saved ckpt, to automatically remove old ckpt+ "best_result": None,+ }++ self.aug = T.Compose([+ T.Resize((224, 224)),+ T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),+ ])++ # auto fix+ if len(metrics) == 0 or self.use_loss_as_metric:+ self.best_mode = 'min'++ # workspace prepare+ self.log_ptr = None+ if self.workspace is not None:+ os.makedirs(self.workspace, exist_ok=True)+ self.log_path = os.path.join(workspace, f"log_{self.name}.txt")+ self.log_ptr = open(self.log_path, "a+")++ self.ckpt_path = os.path.join(self.workspace, 'checkpoints')+ self.best_path = f"{self.ckpt_path}/{self.name}.pth"+ self.img_path = os.path.join(self.workspace, 'train')+ os.makedirs(self.img_path, exist_ok=True)++ os.makedirs(self.ckpt_path, exist_ok=True)++ self.log(f'[INFO] Trainer: {self.name} | {self.time_stamp} | {self.device} | {"fp16" if self.fp16 else "fp32"} | {self.workspace}')+ self.log(f'[INFO] #parameters: {sum([p.numel() for p in model.parameters() if p.requires_grad])}')++ if self.workspace is not None:+ if self.use_checkpoint == "scratch":+ self.log("[INFO] Training from scratch ...")+ elif self.use_checkpoint == "latest":+ self.log("[INFO] Loading latest checkpoint ...")+ self.load_checkpoint()+ elif self.use_checkpoint == "latest_model":+ self.log("[INFO] Loading latest checkpoint (model only)...")+ self.load_checkpoint(model_only=True)+ elif self.use_checkpoint == "best":+ if os.path.exists(self.best_path):+ self.log("[INFO] Loading best checkpoint ...")+ self.load_checkpoint(self.best_path)+ else:+ self.log(f"[INFO] {self.best_path} not found, loading latest ...")+ self.load_checkpoint()+ else: # path to ckpt+ self.log(f"[INFO] Loading {self.use_checkpoint} ...")+ self.load_checkpoint(self.use_checkpoint)++ # calculate the text embs.+ def prepare_text_embeddings(self):++ if self.opt.text is None:+ self.log(f"[WARN] text prompt is not provided.")+ self.text_z = None+ return++ self.text = []+ self.text_z = []+ self.text.append(self.opt.text)+ self.text_z.append(self.guidance.get_text_embeds([self.opt.text], [self.opt.negative]))++ # # white background+ # white_text = f"{self.opt.text}, white background"+ # self.text.append(white_text)+ # white_text_z = self.guidance.get_text_embeds([white_text], [self.opt.negative])+ # self.text_z.append(white_text_z)++ if self.opt.need_back:+ text = f"{self.opt.text}, back view"+ negative_text = f"{self.opt.negative}"+ # explicit negative dir-encoded text+ if negative_text != '': negative_text += ', '+ negative_text += "face"+ self.text.append(text)+ text_z = self.guidance.get_text_embeds([text], [negative_text])+ self.text_z.append(text_z)+ else:+ self.text.append(self.opt.text)+ self.text_z.append(self.guidance.get_text_embeds([self.opt.text], [self.opt.negative]))++ print(self.text)++ def __del__(self):+ if self.log_ptr:+ self.log_ptr.close()+++ def log(self, *args, **kwargs):+ if self.local_rank == 0:+ if not self.mute:+ #print(*args)+ self.console.print(*args, **kwargs)+ if self.log_ptr:+ print(*args, file=self.log_ptr)+ self.log_ptr.flush() # write immediately to file++ def img_loss(self, rgb1, rgb2):+ # l2_loss = torch.sum(torch.sqrt(1e-8 + torch.sum((rgb1 - rgb2) ** 2, dim=1, keepdims=True)))+ # return l2_loss+ l1_loss = nn.L1Loss()(rgb1, rgb2)+ return l1_loss++ def depth_loss(self, pearson, pred_depth, depth_gt, mask):+ # l2_loss = torch.sum(torch.sqrt(1e-8 + torch.sum((pred_depth*mask - depth_gt*mask) ** 2, dim=1, keepdims=True)))+ # return l2_loss+ pred_depth = pred_depth.squeeze()+ pred_depth = torch.nan_to_num(pred_depth)+ depth_gt = depth_gt.squeeze().reshape(-1)+ mask = mask.squeeze().reshape(-1)+ pred_depth = pred_depth.reshape(-1)+ mask = (mask==1)+ co = pearson(pred_depth[mask], depth_gt[mask])+ return 1 - co+++ def img_clip_loss(self, rgb1, rgb2):+ image_z_1 = self.clip_model.encode_image(self.aug(rgb1))+ image_z_2 = self.clip_model.encode_image(self.aug(rgb2))+ image_z_1 = image_z_1 / image_z_1.norm(dim=-1, keepdim=True) # normalize features+ image_z_2 = image_z_2 / image_z_2.norm(dim=-1, keepdim=True) # normalize features++ loss = - (image_z_1 * image_z_2).sum(-1).mean()+ return loss++ def img_text_clip_loss(self, rgb, prompt):+ image_z_1 = self.clip_model.encode_image(self.aug(rgb))+ image_z_1 = image_z_1 / image_z_1.norm(dim=-1, keepdim=True) # normalize features++ text = clip.tokenize(prompt).to(self.device)+ text_z = self.clip_model.encode_text(text)+ text_z = text_z / text_z.norm(dim=-1, keepdim=True)+ loss = - (image_z_1 * text_z).sum(-1).mean()+ return loss+ ### ------------------------------++ def train_step(self, data):++ rays_o = data['rays_o'] # [B, N, 3]+ rays_d = data['rays_d'] # [B, N, 3]+ depth_scale = data['depth_scale']++ B, N = rays_o.shape[:2]+ H, W = data['H'], data['W']++ if self.global_step < self.opt.albedo_iters or data['is_front']:+ shading = 'albedo'+ ambient_ratio = 1.0+ else:+ rand = random.random()+ if rand > 0.5:+ shading = 'albedo'+ ambient_ratio = 1.0+ elif rand > 0.4:+ shading = 'textureless'+ ambient_ratio = 0.1+ else:+ shading = 'lambertian'+ ambient_ratio = 0.1++ if self.global_step % 10 == 0:+ verbose = True+ else:+ verbose = False++ ref_imgs = self.ref_imgs+ bg_color = torch.rand(3, device=self.ref_imgs.device) # [3], frame-wise random.+ bg_img = bg_color.expand(1, 512, 512, 3).permute(0, 3, 1, 2).contiguous()+ gt_rgb = ref_imgs[:, :3, :, :] * ref_imgs[:, 3:, :, :] + bg_img * (1 - ref_imgs[:, 3:, :, :])++ # _t = time.time()+ outputs = self.model.render(rays_o, rays_d, depth_scale=depth_scale,+ bg_color=bg_color, staged=False, perturb=True, ambient_ratio=ambient_ratio,+ shading=shading, force_all_rays=True, **vars(self.opt))++ pred_rgb = outputs['image'].reshape(B, H, W, 3).permute(0, 3, 1, 2).contiguous() # [1, 3, H, W]+ pred_depth = outputs['depth'].reshape(B, H, W, 1).permute(0, 3, 1, 2).contiguous() # [1, 1, H, W]+ pred_ws = outputs['weights_sum'].reshape(B, 1, H, W)+++ if data['is_large']:+ text_z = self.text_z[1]+ text = self.text[1]+ else:+ text_z = self.text_z[0]+ text = self.text[0]++ if self.global_step < self.opt.diff_iters or data['is_front']:+ loss = 0+ de_imgs = None+ else:+ loss, de_imgs = self.guidance.train_step(text_z, pred_rgb, clip_model=self.clip_model,+ ref_text=text, islarge=data['is_large'], ref_rgb=gt_rgb, guidance_scale=self.opt.guidance_scale)++ if self.opt.lambda_opacity > 0:+ loss_opacity = (pred_ws ** 2).mean()+ if data['is_large']:+ loss = loss + self.opt.lambda_opacity * loss_opacity * 10+ else:+ loss = loss + self.opt.lambda_opacity * loss_opacity++ if self.opt.lambda_entropy > 0:+ alphas = (pred_ws).clamp(1e-5, 1 - 1e-5)+ # alphas = alphas ** 2 # skewed entropy, favors 0 over 1+ loss_entropy = (- alphas * torch.log2(alphas) - (1 - alphas) * torch.log2(1 - alphas)).mean()+ if self.global_step < self.opt.diff_iters:+ loss = loss + self.opt.lambda_entropy * loss_entropy+ else:+ loss = loss + self.opt.lambda_entropy * loss_entropy * 10++ if verbose:+ print(f"loss_entropy: {loss_entropy}, loss_opacity: {loss_opacity}")++ if self.opt.lambda_orient > 0 and 'loss_orient' in outputs:+ loss_orient = outputs['loss_orient']+ loss = loss + self.opt.lambda_orient * loss_orient+ if self.global_step < self.opt.diff_iters:+ loss = loss + self.opt.lambda_orient * loss_orient+ else:+ loss = loss + self.opt.lambda_orient * loss_orient * 10++ if self.opt.lambda_smooth > 0 and 'loss_smooth' in outputs:+ loss_smooth = outputs['loss_smooth']+ loss = loss + self.opt.lambda_smooth * loss_smooth+++ pred_rgb = F.interpolate(pred_rgb, (512, 512), mode='bilinear', align_corners=True)+ pred_depth = F.interpolate(pred_depth, (512, 512), mode='bilinear', align_corners=True)++ if data['is_front']:+ loss_ref = self.opt.lambda_img * self.img_loss(pred_rgb, gt_rgb)+ loss_depth = self.opt.lambda_depth * self.depth_loss(self.pearson, pred_depth, self.depth_prediction, ~self.depth_mask)+ if verbose:+ print(f"loss_depth: {loss_depth}, loss_img: {loss_ref}")+ loss_ref += loss_depth++ else:+ loss_ref = self.opt.lambda_clip * self.img_clip_loss(pred_rgb, gt_rgb) + \+ self.opt.lambda_clip * self.img_text_clip_loss(pred_rgb, text)++ if self.global_step % 100 == 0 or self.global_step == 1:+ save_image(pred_rgb, os.path.join(self.img_path, f'{self.global_step}.png'))+ save_image(gt_rgb, os.path.join(self.img_path, f'{self.global_step}_gt.png'))+ save_image(pred_depth, os.path.join(self.img_path, f'{self.global_step}_depth.png'))+ save_image(self.depth_prediction * (~self.depth_mask), os.path.join(self.img_path, f'{self.global_step}_ref_depth_mask.png'))+ if de_imgs is not None:+ save_image(de_imgs, os.path.join(self.img_path, f'{self.global_step}_denoise.png'))++ loss = loss + loss_ref # loss_depth = 0.01 * self.opt.lambda_img * (self.img_loss(pred_depth, self.depth_prediction) + 1e-2)+ return pred_rgb, pred_ws, loss++ def eval_step(self, data):++ rays_o = data['rays_o'] # [B, N, 3]+ rays_d = data['rays_d'] # [B, N, 3]+ depth_scale = data['depth_scale']++ B, N = rays_o.shape[:2]+ H, W = data['H'], data['W']++ shading = data['shading'] if 'shading' in data else 'albedo'+ ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0+ light_d = data['light_d'] if 'light_d' in data else None++ outputs = self.model.render(rays_o, rays_d, staged=True, perturb=False, bg_color=None, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading, force_all_rays=True, **vars(self.opt))+ pred_rgb = outputs['image'].reshape(B, H, W, 3)+ pred_depth = outputs['depth'].reshape(B, H, W)+ loss = 0.0++ return pred_rgb, pred_depth, loss++ def test_step(self, data, bg_color=None, perturb=False):+ rays_o = data['rays_o'] # [B, N, 3]+ rays_d = data['rays_d'] # [B, N, 3]+ depth_scale = data['depth_scale']+++ B, N = rays_o.shape[:2]+ H, W = data['H'], data['W']++ if bg_color is not None:+ bg_color = bg_color.to(rays_o.device)+ else:+ bg_color = torch.ones(3, device=rays_o.device) # [3]++ shading = data['shading'] if 'shading' in data else 'albedo'+ ambient_ratio = data['ambient_ratio'] if 'ambient_ratio' in data else 1.0+ light_d = data['light_d'] if 'light_d' in data else None++ outputs = self.model.render(rays_o, rays_d, depth_scale=depth_scale, staged=True, perturb=perturb, light_d=light_d, ambient_ratio=ambient_ratio, shading=shading, force_all_rays=True, bg_color=bg_color, **vars(self.opt))++ pred_rgb = outputs['image'].reshape(B, H, W, 3)+ pred_depth = outputs['depth'].reshape(B, H, W)+ pred_mask = outputs['weights_sum'].reshape(B, H, W)+ if 'normal' in outputs:+ pred_normal = outputs['normal'].reshape(B, H, W, 3)+ return pred_rgb, pred_depth, pred_mask, pred_normal+ else:+ return pred_rgb, pred_depth, pred_mask, None+++ def save_mesh(self, save_path=None, resolution=128):++ if save_path is None:+ save_path = os.path.join(self.workspace, 'mesh')++ self.log(f"==> Saving mesh to {save_path}")++ os.makedirs(save_path, exist_ok=True)++ self.model.export_mesh(save_path, resolution=resolution)++ self.log(f"==> Finished saving mesh.")++ ### ------------------------------++ def train(self, train_loader, valid_loader, max_epochs):++ assert self.text_z is not None, 'Training must provide a text prompt!'++ if self.use_tensorboardX and self.local_rank == 0:+ self.writer = tensorboardX.SummaryWriter(os.path.join(self.workspace, "run", self.name))++ start_t = time.time()++ for epoch in range(self.epoch + 1, max_epochs + 1):+ self.epoch = epoch++ self.train_one_epoch(train_loader)+ if self.epoch % self.eval_interval == 0:+ self.evaluate_one_epoch(valid_loader)+ self.save_checkpoint(full=False, best=False)+ self.save_checkpoint(full=False, best=True)++ end_t = time.time()++ self.log(f"[INFO] training takes {(end_t - start_t)/ 60:.4f} minutes.")++ if self.use_tensorboardX and self.local_rank == 0:+ self.writer.close()++ def evaluate(self, loader, name=None):+ self.use_tensorboardX, use_tensorboardX = False, self.use_tensorboardX+ self.evaluate_one_epoch(loader, name)+ self.use_tensorboardX = use_tensorboardX++ def test(self, loader, save_path=None, name=None, write_video=True):++ if save_path is None:+ save_path = os.path.join(self.workspace, 'result')++ if name is None:+ name = f'{self.name}_ep{self.epoch:04d}'++ os.makedirs(save_path, exist_ok=True)++ self.log(f"==> Start Test, save results to {save_path}")++ pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')+ self.model.eval()++ if write_video:+ all_preds = []+ all_preds_depth = []+ all_preds_normal = []++ all_poses = []+ with torch.no_grad():+ for i, data in enumerate(loader):+ with torch.cuda.amp.autocast(enabled=self.fp16):+ preds, preds_depth, preds_mask, preds_normal = self.test_step(data)++ # print(preds_mask)+ mask = (preds_mask>0.9).int()++ mask = mask[0].detach().cpu().numpy()+ mask = (mask * 255).astype(np.uint8)++ pred = preds[0].detach().cpu().numpy()+ pred = (pred * 255).astype(np.uint8)++ if preds_normal is not None:+ preds_normal = preds_normal[0].detach().cpu().numpy()+ preds_normal = (preds_normal * 255).astype(np.uint8)++ poses = data['poses']+ pose = poses[0].detach().cpu().numpy()+ all_poses.append(pose)++ if write_video:+ pred_depth_cpu = preds_depth[0].detach().cpu().numpy()+ pred_depth_cpu = (pred_depth_cpu * 255.).astype(np.uint8)++ all_preds.append(pred)+ if preds_normal is not None:+ all_preds_normal.append(preds_normal)+ all_preds_depth.append(pred_depth_cpu)++ pred_depth = preds_depth[0].detach().cpu().numpy()+ pred_depth = (pred_depth * 1000.).astype(np.uint16)++ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_rgb.png'), cv2.cvtColor(pred, cv2.COLOR_RGB2BGR))+ if preds_normal is not None:+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_normal.png'), cv2.cvtColor(preds_normal, cv2.COLOR_RGB2BGR))+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_depth.png'), pred_depth)+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_mask.png'), mask)+ pbar.update(loader.batch_size)++ if write_video:+ all_preds = np.stack(all_preds, axis=0)+ all_preds_normal = np.stack(all_preds_normal, axis=0)+ all_preds_depth = np.stack(all_preds_depth, axis=0)+ imageio.mimwrite(os.path.join(save_path, f'{name}_normal.mp4'), all_preds_normal, fps=25, quality=8, macro_block_size=1)+ imageio.mimwrite(os.path.join(save_path, f'{name}_rgb.mp4'), all_preds, fps=25, quality=8, macro_block_size=1)+ imageio.mimwrite(os.path.join(save_path, f'{name}_depth.mp4'), all_preds_depth, fps=25, quality=8, macro_block_size=1)++ all_poses = np.stack(all_poses, axis=0)+ np.save(os.path.join(save_path, f'{name}_poses.npy'), all_poses)++ self.log(f"==> Finished Test.")++ def train_one_epoch(self, loader):+ self.log(f"==> Start Training {self.workspace} Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...")++ total_loss = 0+ if self.local_rank == 0 and self.report_metric_at_train:+ for metric in self.metrics:+ metric.clear()++ self.model.train()++ # distributedSampler: must call set_epoch() to shuffle indices across multiple epochs+ # ref: https://pytorch.org/docs/stable/data.html+ if self.world_size > 1:+ loader.sampler.set_epoch(self.epoch)++ if self.local_rank == 0:+ pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{desc}: {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')++ self.local_step = 0++ for data in loader:++ # update grid every 16 steps+ if self.model.cuda_ray and self.global_step % self.opt.update_extra_interval == 0:+ with torch.cuda.amp.autocast(enabled=self.fp16):+ self.model.update_extra_state()++ self.local_step += 1+ self.global_step += 1++ self.optimizer.zero_grad()++ with torch.cuda.amp.autocast(enabled=self.fp16):+ pred_rgbs, pred_ws, loss = self.train_step(data)+++ self.scaler.scale(loss).backward()+ nn.utils.clip_grad_norm(self.model.parameters(), max_norm=10)+ self.scaler.step(self.optimizer)+ self.scaler.update()++ if self.scheduler_update_every_step:+ self.lr_scheduler.step()++ loss_val = loss.item()+ total_loss += loss_val++ if self.local_rank == 0:++ if self.use_tensorboardX:+ self.writer.add_scalar("train/loss", loss_val, self.global_step)+ self.writer.add_scalar("train/lr", self.optimizer.param_groups[0]['lr'], self.global_step)++ if self.scheduler_update_every_step:+ pbar.set_description(f"loss={loss_val:.4f} ({total_loss/self.local_step:.4f}), lr={self.optimizer.param_groups[0]['lr']:.6f}")+ else:+ pbar.set_description(f"loss={loss_val:.4f} ({total_loss/self.local_step:.4f})")+ pbar.update(loader.batch_size)++ if self.ema is not None:+ self.ema.update()++ average_loss = total_loss / self.local_step+ self.stats["loss"].append(average_loss)++ if self.local_rank == 0:+ pbar.close()+ if self.report_metric_at_train:+ for metric in self.metrics:+ self.log(metric.report(), style="red")+ if self.use_tensorboardX:+ metric.write(self.writer, self.epoch, prefix="train")+ metric.clear()++ if not self.scheduler_update_every_step:+ if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):+ self.lr_scheduler.step(average_loss)+ else:+ self.lr_scheduler.step()++ self.log(f"==> Finished Epoch {self.epoch}.")+++ def evaluate_one_epoch(self, loader, name=None):+ self.log(f"++> Evaluate {self.workspace} at epoch {self.epoch} ...")++ if name is None:+ name = f'{self.name}_ep{self.epoch:04d}'++ total_loss = 0+ if self.local_rank == 0:+ for metric in self.metrics:+ metric.clear()++ self.model.eval()++ if self.ema is not None:+ self.ema.store()+ self.ema.copy_to()++ if self.local_rank == 0:+ pbar = tqdm.tqdm(total=len(loader) * loader.batch_size, bar_format='{desc}: {percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')++ self.local_step = 0++ with torch.no_grad():+ for data in loader:+ self.local_step += 1+ with torch.cuda.amp.autocast(enabled=self.fp16):+ preds, preds_depth, loss = self.eval_step(data)+ # save image+ save_path = os.path.join(self.workspace, 'validation', f'{name}_{self.local_step:04d}_rgb.png')+ save_path_depth = os.path.join(self.workspace, 'validation', f'{name}_{self.local_step:04d}_depth.png')++ os.makedirs(os.path.dirname(save_path), exist_ok=True)+ pred_depth = preds_depth.reshape(1, self.opt.H, self.opt.W, 1).permute(0, 3, 1, 2).contiguous() # [1, 1, H, W]+ preds = preds.reshape(1, self.opt.H, self.opt.W, 3).permute(0, 3, 1, 2).contiguous() # [1, 1, H, W]++ save_image(pred_depth, save_path_depth)+ save_image(preds, save_path)++ pbar.update(loader.batch_size)++ if self.ema is not None:+ self.ema.restore()++ self.log(f"++> Evaluate epoch {self.epoch} Finished.")++ def save_checkpoint(self, name=None, full=False, best=False):++ if name is None:+ name = f'{self.name}_ep{self.epoch:04d}'++ state = {+ 'epoch': self.epoch,+ 'global_step': self.global_step,+ 'stats': self.stats,+ }++ if self.model.cuda_ray:+ state['mean_count'] = self.model.mean_count+ state['mean_density'] = self.model.mean_density++ if full:+ state['optimizer'] = self.optimizer.state_dict()+ state['lr_scheduler'] = self.lr_scheduler.state_dict()+ state['scaler'] = self.scaler.state_dict()+ if self.ema is not None:+ state['ema'] = self.ema.state_dict()++ if not best:++ state['model'] = self.model.state_dict()++ file_path = f"{name}.pth"++ self.stats["checkpoints"].append(file_path)+ torch.save(state, os.path.join(self.ckpt_path, file_path))++ else:+ if len(self.stats["results"]) > 0:+ # always save best since loss cannot reflect performance.+ if True:+ # save ema results+ if self.ema is not None:+ self.ema.store()+ self.ema.copy_to()++ state['model'] = self.model.state_dict()++ if self.ema is not None:+ self.ema.restore()++ torch.save(state, self.best_path)+ else:+ self.log(f"[WARN] no evaluated results found, skip saving best checkpoint.")++ def load_checkpoint(self, checkpoint=None, model_only=False):+ if checkpoint is None:+ checkpoint_list = sorted(glob.glob(f'{self.ckpt_path}/*.pth'))+ if checkpoint_list:+ checkpoint = checkpoint_list[-1]+ self.log(f"[INFO] Latest checkpoint is {checkpoint}")+ else:+ self.log("[WARN] No checkpoint found, model randomly initialized.")+ return++ checkpoint_dict = torch.load(checkpoint, map_location=self.device)+ if 'model' not in checkpoint_dict:+ self.model.load_state_dict(checkpoint_dict)+ self.log("[INFO] loaded model.")+ return++ missing_keys, unexpected_keys = self.model.load_state_dict(checkpoint_dict['model'], strict=False)+ self.log("[INFO] loaded model.")+ if len(missing_keys) > 0:+ self.log(f"[WARN] missing keys: {missing_keys}")+ if len(unexpected_keys) > 0:+ self.log(f"[WARN] unexpected keys: {unexpected_keys}")++ if self.ema is not None and 'ema' in checkpoint_dict:+ try:+ self.ema.load_state_dict(checkpoint_dict['ema'])+ self.log("[INFO] loaded EMA.")+ except:+ self.log("[WARN] failed to loaded EMA.")++ if self.model.cuda_ray:+ if 'mean_count' in checkpoint_dict:+ self.model.mean_count = checkpoint_dict['mean_count']+ if 'mean_density' in checkpoint_dict:+ self.model.mean_density = checkpoint_dict['mean_density']+ if model_only:+ return++ self.stats = checkpoint_dict['stats']+ self.epoch = checkpoint_dict['epoch']+ self.global_step = checkpoint_dict['global_step']+ self.log(f"[INFO] load at epoch {self.epoch}, global step {self.global_step}")++ if self.optimizer and 'optimizer' in checkpoint_dict:+ try:+ self.optimizer.load_state_dict(checkpoint_dict['optimizer'])+ self.log("[INFO] loaded optimizer.")+ except:+ self.log("[WARN] Failed to load optimizer.")++ if self.lr_scheduler and 'lr_scheduler' in checkpoint_dict:+ try:+ self.lr_scheduler.load_state_dict(checkpoint_dict['lr_scheduler'])+ self.log("[INFO] loaded scheduler.")+ except:+ self.log("[WARN] Failed to load scheduler.")++ if self.scaler and 'scaler' in checkpoint_dict:+ try:+ self.scaler.load_state_dict(checkpoint_dict['scaler'])+ self.log("[INFO] loaded scaler.")+ except:+ self.log("[WARN] Failed to load scaler.")\ No newline at end of filediff --git a/optimizer.py b/optimizer.pynew file mode 100644index 0000000..f5bb64f--- /dev/null+++ b/optimizer.py@@ -0,0 +1,325 @@+# Copyright 2022 Garena Online Private Limited+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import math+from typing import List++import torch+from torch import Tensor+from torch.optim.optimizer import Optimizer+++class Adan(Optimizer):+ """+ Implements a pytorch variant of Adan+ Adan was proposed in+ Adan: Adaptive Nesterov Momentum Algorithm for+ Faster Optimizing Deep Models[J].arXiv preprint arXiv:2208.06677, 2022.+ https://arxiv.org/abs/2208.06677+ Arguments:+ params (iterable): iterable of parameters to optimize or+ dicts defining parameter groups.+ lr (float, optional): learning rate. (default: 1e-3)+ betas (Tuple[float, float, flot], optional): coefficients used for+ first- and second-order moments. (default: (0.98, 0.92, 0.99))+ eps (float, optional): term added to the denominator to improve+ numerical stability. (default: 1e-8)+ weight_decay (float, optional): decoupled weight decay+ (L2 penalty) (default: 0)+ max_grad_norm (float, optional): value used to clip+ global grad norm (default: 0.0 no clip)+ no_prox (bool): how to perform the decoupled weight decay+ (default: False)+ foreach (bool): if True would use torch._foreach implementation.+ It's faster but uses slightly more memory. (default: True)+ """+ def __init__(self,+ params,+ lr=1e-3,+ betas=(0.98, 0.92, 0.99),+ eps=1e-8,+ weight_decay=0.0,+ max_grad_norm=0.0,+ no_prox=False,+ foreach: bool = True):+ if not 0.0 <= max_grad_norm:+ raise ValueError('Invalid Max grad norm: {}'.format(max_grad_norm))+ if not 0.0 <= lr:+ raise ValueError('Invalid learning rate: {}'.format(lr))+ if not 0.0 <= eps:+ raise ValueError('Invalid epsilon value: {}'.format(eps))+ if not 0.0 <= betas[0] < 1.0:+ raise ValueError('Invalid beta parameter at index 0: {}'.format(+ betas[0]))+ if not 0.0 <= betas[1] < 1.0:+ raise ValueError('Invalid beta parameter at index 1: {}'.format(+ betas[1]))+ if not 0.0 <= betas[2] < 1.0:+ raise ValueError('Invalid beta parameter at index 2: {}'.format(+ betas[2]))+ defaults = dict(lr=lr,+ betas=betas,+ eps=eps,+ weight_decay=weight_decay,+ max_grad_norm=max_grad_norm,+ no_prox=no_prox,+ foreach=foreach)+ super().__init__(params, defaults)++ def __setstate__(self, state):+ super(Adan, self).__setstate__(state)+ for group in self.param_groups:+ group.setdefault('no_prox', False)++ @torch.no_grad()+ def restart_opt(self):+ for group in self.param_groups:+ group['step'] = 0+ for p in group['params']:+ if p.requires_grad:+ state = self.state[p]+ # State initialization++ # Exponential moving average of gradient values+ state['exp_avg'] = torch.zeros_like(p)+ # Exponential moving average of squared gradient values+ state['exp_avg_sq'] = torch.zeros_like(p)+ # Exponential moving average of gradient difference+ state['exp_avg_diff'] = torch.zeros_like(p)++ @torch.no_grad()+ def step(self, closure=None):+ """Performs a single optimization step."""++ loss = None+ if closure is not None:+ with torch.enable_grad():+ loss = closure()++ if self.defaults['max_grad_norm'] > 0:+ device = self.param_groups[0]['params'][0].device+ global_grad_norm = torch.zeros(1, device=device)++ max_grad_norm = torch.tensor(self.defaults['max_grad_norm'],+ device=device)+ for group in self.param_groups:++ for p in group['params']:+ if p.grad is not None:+ grad = p.grad+ global_grad_norm.add_(grad.pow(2).sum())++ global_grad_norm = torch.sqrt(global_grad_norm)++ clip_global_grad_norm = torch.clamp(+ max_grad_norm / (global_grad_norm + group['eps']),+ max=1.0).item()+ else:+ clip_global_grad_norm = 1.0++ for group in self.param_groups:+ params_with_grad = []+ grads = []+ exp_avgs = []+ exp_avg_sqs = []+ exp_avg_diffs = []+ neg_pre_grads = []++ beta1, beta2, beta3 = group['betas']+ # assume same step across group now to simplify things+ # per parameter step can be easily support+ # by making it tensor, or pass list into kernel+ if 'step' in group:+ group['step'] += 1+ else:+ group['step'] = 1++ bias_correction1 = 1.0 - beta1**group['step']+ bias_correction2 = 1.0 - beta2**group['step']+ bias_correction3 = 1.0 - beta3**group['step']++ for p in group['params']:+ if p.grad is None:+ continue+ params_with_grad.append(p)+ grads.append(p.grad)++ state = self.state[p]+ if len(state) == 0:+ state['exp_avg'] = torch.zeros_like(p)+ state['exp_avg_sq'] = torch.zeros_like(p)+ state['exp_avg_diff'] = torch.zeros_like(p)++ if 'neg_pre_grad' not in state or group['step'] == 1:+ state['neg_pre_grad'] = p.grad.clone().mul_(+ -clip_global_grad_norm)++ exp_avgs.append(state['exp_avg'])+ exp_avg_sqs.append(state['exp_avg_sq'])+ exp_avg_diffs.append(state['exp_avg_diff'])+ neg_pre_grads.append(state['neg_pre_grad'])++ kwargs = dict(+ params=params_with_grad,+ grads=grads,+ exp_avgs=exp_avgs,+ exp_avg_sqs=exp_avg_sqs,+ exp_avg_diffs=exp_avg_diffs,+ neg_pre_grads=neg_pre_grads,+ beta1=beta1,+ beta2=beta2,+ beta3=beta3,+ bias_correction1=bias_correction1,+ bias_correction2=bias_correction2,+ bias_correction3_sqrt=math.sqrt(bias_correction3),+ lr=group['lr'],+ weight_decay=group['weight_decay'],+ eps=group['eps'],+ no_prox=group['no_prox'],+ clip_global_grad_norm=clip_global_grad_norm,+ )++ if group['foreach']:+ _multi_tensor_adan(**kwargs)+ else:+ _single_tensor_adan(**kwargs)++ return loss+++def _single_tensor_adan(+ params: List[Tensor],+ grads: List[Tensor],+ exp_avgs: List[Tensor],+ exp_avg_sqs: List[Tensor],+ exp_avg_diffs: List[Tensor],+ neg_pre_grads: List[Tensor],+ *,+ beta1: float,+ beta2: float,+ beta3: float,+ bias_correction1: float,+ bias_correction2: float,+ bias_correction3_sqrt: float,+ lr: float,+ weight_decay: float,+ eps: float,+ no_prox: bool,+ clip_global_grad_norm: Tensor,+):+ for i, param in enumerate(params):+ grad = grads[i]+ exp_avg = exp_avgs[i]+ exp_avg_sq = exp_avg_sqs[i]+ exp_avg_diff = exp_avg_diffs[i]+ neg_grad_or_diff = neg_pre_grads[i]++ grad.mul_(clip_global_grad_norm)++ # for memory saving, we use `neg_grad_or_diff`+ # to get some temp variable in a inplace way+ neg_grad_or_diff.add_(grad)++ exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) # m_t+ exp_avg_diff.mul_(beta2).add_(neg_grad_or_diff,+ alpha=1 - beta2) # diff_t++ neg_grad_or_diff.mul_(beta2).add_(grad)+ exp_avg_sq.mul_(beta3).addcmul_(neg_grad_or_diff,+ neg_grad_or_diff,+ value=1 - beta3) # n_t++ denom = ((exp_avg_sq).sqrt() / bias_correction3_sqrt).add_(eps)+ step_size_diff = lr * beta2 / bias_correction2+ step_size = lr / bias_correction1++ if no_prox:+ param.mul_(1 - lr * weight_decay)+ param.addcdiv_(exp_avg, denom, value=-step_size)+ param.addcdiv_(exp_avg_diff, denom, value=-step_size_diff)+ else:+ param.addcdiv_(exp_avg, denom, value=-step_size)+ param.addcdiv_(exp_avg_diff, denom, value=-step_size_diff)+ param.div_(1 + lr * weight_decay)++ neg_grad_or_diff.zero_().add_(grad, alpha=-1.0)+++def _multi_tensor_adan(+ params: List[Tensor],+ grads: List[Tensor],+ exp_avgs: List[Tensor],+ exp_avg_sqs: List[Tensor],+ exp_avg_diffs: List[Tensor],+ neg_pre_grads: List[Tensor],+ *,+ beta1: float,+ beta2: float,+ beta3: float,+ bias_correction1: float,+ bias_correction2: float,+ bias_correction3_sqrt: float,+ lr: float,+ weight_decay: float,+ eps: float,+ no_prox: bool,+ clip_global_grad_norm: Tensor,+):+ if len(params) == 0:+ return++ torch._foreach_mul_(grads, clip_global_grad_norm)++ # for memory saving, we use `neg_pre_grads`+ # to get some temp variable in a inplace way+ torch._foreach_add_(neg_pre_grads, grads)++ torch._foreach_mul_(exp_avgs, beta1)+ torch._foreach_add_(exp_avgs, grads, alpha=1 - beta1) # m_t++ torch._foreach_mul_(exp_avg_diffs, beta2)+ torch._foreach_add_(exp_avg_diffs, neg_pre_grads,+ alpha=1 - beta2) # diff_t++ torch._foreach_mul_(neg_pre_grads, beta2)+ torch._foreach_add_(neg_pre_grads, grads)+ torch._foreach_mul_(exp_avg_sqs, beta3)+ torch._foreach_addcmul_(exp_avg_sqs,+ neg_pre_grads,+ neg_pre_grads,+ value=1 - beta3) # n_t++ denom = torch._foreach_sqrt(exp_avg_sqs)+ torch._foreach_div_(denom, bias_correction3_sqrt)+ torch._foreach_add_(denom, eps)++ step_size_diff = lr * beta2 / bias_correction2+ step_size = lr / bias_correction1++ if no_prox:+ torch._foreach_mul_(params, 1 - lr * weight_decay)+ torch._foreach_addcdiv_(params, exp_avgs, denom, value=-step_size)+ torch._foreach_addcdiv_(params,+ exp_avg_diffs,+ denom,+ value=-step_size_diff)+ else:+ torch._foreach_addcdiv_(params, exp_avgs, denom, value=-step_size)+ torch._foreach_addcdiv_(params,+ exp_avg_diffs,+ denom,+ value=-step_size_diff)+ torch._foreach_div_(params, 1 + lr * weight_decay)+ torch._foreach_zero_(neg_pre_grads)+ torch._foreach_add_(neg_pre_grads, grads, alpha=-1.0)\ No newline at end of filediff --git a/raymarching/__init__.py b/raymarching/__init__.pynew file mode 100644index 0000000..26d3cc6--- /dev/null+++ b/raymarching/__init__.py@@ -0,0 +1 @@+from .raymarching import *\ No newline at end of filediff --git a/raymarching/backend.py b/raymarching/backend.pynew file mode 100644index 0000000..a6a9a03--- /dev/null+++ b/raymarching/backend.py@@ -0,0 +1,40 @@+import os+from torch.utils.cpp_extension import load++_src_path = os.path.dirname(os.path.abspath(__file__))++nvcc_flags = [+ '-O3', '-std=c++14',+ '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__',+]++if os.name == "posix":+ c_flags = ['-O3', '-std=c++14']+elif os.name == "nt":+ c_flags = ['/O2', '/std:c++17']++ # find cl.exe+ def find_cl_path():+ import glob+ for edition in ["Enterprise", "Professional", "BuildTools", "Community"]:+ paths = sorted(glob.glob(r"C:\\Program Files (x86)\\Microsoft Visual Studio\\*\\%s\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64" % edition), reverse=True)+ if paths:+ return paths[0]++ # If cl.exe is not on path, try to find it.+ if os.system("where cl.exe >nul 2>nul") != 0:+ cl_path = find_cl_path()+ if cl_path is None:+ raise RuntimeError("Could not locate a supported Microsoft Visual C++ installation")+ os.environ["PATH"] += ";" + cl_path++_backend = load(name='_raymarching',+ extra_cflags=c_flags,+ extra_cuda_cflags=nvcc_flags,+ sources=[os.path.join(_src_path, 'src', f) for f in [+ 'raymarching.cu',+ 'bindings.cpp',+ ]],+ )++__all__ = ['_backend']\ No newline at end of filediff --git a/raymarching/raymarching.py b/raymarching/raymarching.pynew file mode 100644index 0000000..0b7e8d3--- /dev/null+++ b/raymarching/raymarching.py@@ -0,0 +1,471 @@+import numpy as np+import time++import torch+import torch.nn as nn+from torch.autograd import Function+from torch.cuda.amp import custom_bwd, custom_fwd++# lazy building:+# `import raymarching` will not immediately build the extension, only if you actually call any functions.++BACKEND = None++def get_backend():+ global BACKEND++ if BACKEND is None:+ try:+ import _raymarching as _backend+ except ImportError:+ from .backend import _backend++ BACKEND = _backend++ return BACKEND++# ----------------------------------------+# utils+# ----------------------------------------++class _near_far_from_aabb(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, rays_o, rays_d, aabb, min_near=0.2):+ ''' near_far_from_aabb, CUDA implementation+ Calculate rays' intersection time (near and far) with aabb+ Args:+ rays_o: float, [N, 3]+ rays_d: float, [N, 3]+ aabb: float, [6], (xmin, ymin, zmin, xmax, ymax, zmax)+ min_near: float, scalar+ Returns:+ nears: float, [N]+ fars: float, [N]+ '''+ if not rays_o.is_cuda: rays_o = rays_o.cuda()+ if not rays_d.is_cuda: rays_d = rays_d.cuda()++ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)++ N = rays_o.shape[0] # num rays++ nears = torch.empty(N, dtype=rays_o.dtype, device=rays_o.device)+ fars = torch.empty(N, dtype=rays_o.dtype, device=rays_o.device)++ get_backend().near_far_from_aabb(rays_o, rays_d, aabb, N, min_near, nears, fars)++ return nears, fars++near_far_from_aabb = _near_far_from_aabb.apply+++class _sph_from_ray(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, rays_o, rays_d, radius):+ ''' sph_from_ray, CUDA implementation+ get spherical coordinate on the background sphere from rays.+ Assume rays_o are inside the Sphere(radius).+ Args:+ rays_o: [N, 3]+ rays_d: [N, 3]+ radius: scalar, float+ Return:+ coords: [N, 2], in [-1, 1], theta and phi on a sphere. (further-surface)+ '''+ if not rays_o.is_cuda: rays_o = rays_o.cuda()+ if not rays_d.is_cuda: rays_d = rays_d.cuda()++ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)++ N = rays_o.shape[0] # num rays++ coords = torch.empty(N, 2, dtype=rays_o.dtype, device=rays_o.device)++ get_backend().sph_from_ray(rays_o, rays_d, radius, N, coords)++ return coords++sph_from_ray = _sph_from_ray.apply+++class _morton3D(Function):+ @staticmethod+ def forward(ctx, coords):+ ''' morton3D, CUDA implementation+ Args:+ coords: [N, 3], int32, in [0, 128) (for some reason there is no uint32 tensor in torch...)+ TODO: check if the coord range is valid! (current 128 is safe)+ Returns:+ indices: [N], int32, in [0, 128^3)++ '''+ if not coords.is_cuda: coords = coords.cuda()++ N = coords.shape[0]++ indices = torch.empty(N, dtype=torch.int32, device=coords.device)++ get_backend().morton3D(coords.int(), N, indices)++ return indices++morton3D = _morton3D.apply++class _morton3D_invert(Function):+ @staticmethod+ def forward(ctx, indices):+ ''' morton3D_invert, CUDA implementation+ Args:+ indices: [N], int32, in [0, 128^3)+ Returns:+ coords: [N, 3], int32, in [0, 128)++ '''+ if not indices.is_cuda: indices = indices.cuda()++ N = indices.shape[0]++ coords = torch.empty(N, 3, dtype=torch.int32, device=indices.device)++ get_backend().morton3D_invert(indices.int(), N, coords)++ return coords++morton3D_invert = _morton3D_invert.apply+++class _packbits(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, grid, thresh, bitfield=None):+ ''' packbits, CUDA implementation+ Pack up the density grid into a bit field to accelerate ray marching.+ Args:+ grid: float, [C, H * H * H], assume H % 2 == 0+ thresh: float, threshold+ Returns:+ bitfield: uint8, [C, H * H * H / 8]+ '''+ if not grid.is_cuda: grid = grid.cuda()+ grid = grid.contiguous()++ C = grid.shape[0]+ H3 = grid.shape[1]+ N = C * H3 // 8++ if bitfield is None:+ bitfield = torch.empty(N, dtype=torch.uint8, device=grid.device)++ get_backend().packbits(grid, N, thresh, bitfield)++ return bitfield++packbits = _packbits.apply++# ----------------------------------------+# train functions+# ----------------------------------------++class _march_rays_train(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, rays_o, rays_d, bound, density_bitfield, C, H, nears, fars, step_counter=None, mean_count=-1, perturb=False, align=-1, force_all_rays=False, dt_gamma=0, max_steps=1024):+ ''' march rays to generate points (forward only)+ Args:+ rays_o/d: float, [N, 3]+ bound: float, scalar+ density_bitfield: uint8: [CHHH // 8]+ C: int+ H: int+ nears/fars: float, [N]+ step_counter: int32, (2), used to count the actual number of generated points.+ mean_count: int32, estimated mean steps to accelerate training. (but will randomly drop rays if the actual point count exceeded this threshold.)+ perturb: bool+ align: int, pad output so its size is dividable by align, set to -1 to disable.+ force_all_rays: bool, ignore step_counter and mean_count, always calculate all rays. Useful if rendering the whole image, instead of some rays.+ dt_gamma: float, called cone_angle in instant-ngp, exponentially accelerate ray marching if > 0. (very significant effect, but generally lead to worse performance)+ max_steps: int, max number of sampled points along each ray, also affect min_stepsize.+ Returns:+ xyzs: float, [M, 3], all generated points' coords. (all rays concated, need to use `rays` to extract points belonging to each ray)+ dirs: float, [M, 3], all generated points' view dirs.+ deltas: float, [M, 2], all generated points' deltas. (first for RGB, second for Depth)+ rays: int32, [N, 3], all rays' (index, point_offset, point_count), e.g., xyzs[rays[i, 1]:rays[i, 2]] --> points belonging to rays[i, 0]+ '''++ if not rays_o.is_cuda: rays_o = rays_o.cuda()+ if not rays_d.is_cuda: rays_d = rays_d.cuda()+ if not density_bitfield.is_cuda: density_bitfield = density_bitfield.cuda()++ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)+ density_bitfield = density_bitfield.contiguous()++ N = rays_o.shape[0] # num rays+ M = N * max_steps # init max points number in total++ # running average based on previous epoch (mimic `measured_batch_size_before_compaction` in instant-ngp)+ # It estimate the max points number to enable faster training, but will lead to random ignored rays if underestimated.+ if not force_all_rays and mean_count > 0:+ if align > 0:+ mean_count += align - mean_count % align+ M = mean_count++ xyzs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)+ dirs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)+ deltas = torch.zeros(M, 2, dtype=rays_o.dtype, device=rays_o.device)+ rays = torch.empty(N, 3, dtype=torch.int32, device=rays_o.device) # id, offset, num_steps++ if step_counter is None:+ step_counter = torch.zeros(2, dtype=torch.int32, device=rays_o.device) # point counter, ray counter++ if perturb:+ noises = torch.rand(N, dtype=rays_o.dtype, device=rays_o.device)+ else:+ noises = torch.zeros(N, dtype=rays_o.dtype, device=rays_o.device)++ get_backend().march_rays_train(rays_o, rays_d, density_bitfield, bound, dt_gamma, max_steps, N, C, H, M, nears, fars, xyzs, dirs, deltas, rays, step_counter, noises) # m is the actually used points number++ #print(step_counter, M)++ # only used at the first (few) epochs.+ if force_all_rays or mean_count <= 0:+ m = step_counter[0].item() # D2H copy+ if align > 0:+ m += align - m % align+ xyzs = xyzs[:m]+ dirs = dirs[:m]+ deltas = deltas[:m]++ torch.cuda.empty_cache()++ return xyzs, dirs, deltas, rays++march_rays_train = _march_rays_train.apply+++class _composite_rays_train(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, sigmas, rgbs, deltas, rays, T_thresh=1e-4):+ ''' composite rays' rgbs, according to the ray marching formula.+ Args:+ rgbs: float, [M, 3]+ sigmas: float, [M,]+ deltas: float, [M, 2]+ rays: int32, [N, 3]+ Returns:+ weights_sum: float, [N,], the alpha channel+ depth: float, [N, ], the Depth+ image: float, [N, 3], the RGB channel (after multiplying alpha!)+ '''++ sigmas = sigmas.contiguous()+ rgbs = rgbs.contiguous()++ M = sigmas.shape[0]+ N = rays.shape[0]++ weights_sum = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)+ depth = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)+ image = torch.empty(N, 3, dtype=sigmas.dtype, device=sigmas.device)++ get_backend().composite_rays_train_forward(sigmas, rgbs, deltas, rays, M, N, T_thresh, weights_sum, depth, image)++ ctx.save_for_backward(sigmas, rgbs, deltas, rays, weights_sum, depth, image)+ ctx.dims = [M, N, T_thresh]++ return weights_sum, depth, image++ @staticmethod+ @custom_bwd+ def backward(ctx, grad_weights_sum, grad_depth, grad_image):++ # NOTE: grad_depth is not used now! It won't be propagated to sigmas.++ grad_weights_sum = grad_weights_sum.contiguous()+ grad_image = grad_image.contiguous()++ sigmas, rgbs, deltas, rays, weights_sum, depth, image = ctx.saved_tensors+ M, N, T_thresh = ctx.dims++ grad_sigmas = torch.zeros_like(sigmas)+ grad_rgbs = torch.zeros_like(rgbs)++ get_backend().composite_rays_train_backward(grad_weights_sum, grad_image, sigmas, rgbs, deltas, rays, weights_sum, image, M, N, T_thresh, grad_sigmas, grad_rgbs)++ return grad_sigmas, grad_rgbs, None, None, None+++composite_rays_train = _composite_rays_train.apply+++class _composite_sdf_rays_train(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, sigmas, rgbs, deltas, rays, T_thresh=1e-4):+ ''' composite rays' rgbs, according to the ray marching formula.+ Args:+ rgbs: float, [M, 3]+ sigmas: float, [M,]+ deltas: float, [M, 2]+ rays: int32, [N, 3]+ Returns:+ weights_sum: float, [N,], the alpha channel+ depth: float, [N, ], the Depth+ image: float, [N, 3], the RGB channel (after multiplying alpha!)+ '''++ sigmas = sigmas.contiguous()+ rgbs = rgbs.contiguous()++ M = sigmas.shape[0]+ N = rays.shape[0]++ weights_sum = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)+ depth = torch.empty(N, dtype=sigmas.dtype, device=sigmas.device)+ image = torch.empty(N, 3, dtype=sigmas.dtype, device=sigmas.device)++ get_backend().composite_sdf_rays_train_forward(sigmas, rgbs, deltas, rays, M, N, T_thresh, weights_sum, depth, image)++ ctx.save_for_backward(sigmas, rgbs, deltas, rays, weights_sum, depth, image)+ ctx.dims = [M, N, T_thresh]++ return weights_sum, depth, image++ @staticmethod+ @custom_bwd+ def backward(ctx, grad_weights_sum, grad_depth, grad_image):++ # NOTE: grad_depth is not used now! It won't be propagated to sigmas.++ grad_weights_sum = grad_weights_sum.contiguous()+ grad_image = grad_image.contiguous()++ sigmas, rgbs, deltas, rays, weights_sum, depth, image = ctx.saved_tensors+ M, N, T_thresh = ctx.dims++ grad_sigmas = torch.zeros_like(sigmas)+ grad_rgbs = torch.zeros_like(rgbs)++ get_backend().composite_sdf_rays_train_backward(grad_weights_sum, grad_image, sigmas, rgbs, deltas, rays, weights_sum, image, M, N, T_thresh, grad_sigmas, grad_rgbs)++ return grad_sigmas, grad_rgbs, None, None, None+++composite_sdf_rays_train = _composite_sdf_rays_train.apply++# ----------------------------------------+# infer functions+# ----------------------------------------++class _march_rays(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32)+ def forward(ctx, n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, bound, density_bitfield, C, H, near, far, align=-1, perturb=False, dt_gamma=0, max_steps=1024):+ ''' march rays to generate points (forward only, for inference)+ Args:+ n_alive: int, number of alive rays+ n_step: int, how many steps we march+ rays_alive: int, [N], the alive rays' IDs in N (N >= n_alive, but we only use first n_alive)+ rays_t: float, [N], the alive rays' time, we only use the first n_alive.+ rays_o/d: float, [N, 3]+ bound: float, scalar+ density_bitfield: uint8: [CHHH // 8]+ C: int+ H: int+ nears/fars: float, [N]+ align: int, pad output so its size is dividable by align, set to -1 to disable.+ perturb: bool/int, int > 0 is used as the random seed.+ dt_gamma: float, called cone_angle in instant-ngp, exponentially accelerate ray marching if > 0. (very significant effect, but generally lead to worse performance)+ max_steps: int, max number of sampled points along each ray, also affect min_stepsize.+ Returns:+ xyzs: float, [n_alive * n_step, 3], all generated points' coords+ dirs: float, [n_alive * n_step, 3], all generated points' view dirs.+ deltas: float, [n_alive * n_step, 2], all generated points' deltas (here we record two deltas, the first is for RGB, the second for depth).+ '''++ if not rays_o.is_cuda: rays_o = rays_o.cuda()+ if not rays_d.is_cuda: rays_d = rays_d.cuda()++ rays_o = rays_o.contiguous().view(-1, 3)+ rays_d = rays_d.contiguous().view(-1, 3)++ M = n_alive * n_step++ if align > 0:+ M += align - (M % align)++ xyzs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)+ dirs = torch.zeros(M, 3, dtype=rays_o.dtype, device=rays_o.device)+ deltas = torch.zeros(M, 2, dtype=rays_o.dtype, device=rays_o.device) # 2 vals, one for rgb, one for depth++ if perturb:+ # torch.manual_seed(perturb) # test_gui uses spp index as seed+ noises = torch.rand(n_alive, dtype=rays_o.dtype, device=rays_o.device)+ else:+ noises = torch.zeros(n_alive, dtype=rays_o.dtype, device=rays_o.device)++ get_backend().march_rays(n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, bound, dt_gamma, max_steps, C, H, density_bitfield, near, far, xyzs, dirs, deltas, noises)++ return xyzs, dirs, deltas++march_rays = _march_rays.apply+++class _composite_rays(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32) # need to cast sigmas & rgbs to float+ def forward(ctx, n_alive, n_step, rays_alive, rays_t, sigmas, rgbs, normals, deltas, weights_sum, depth, image, normal, T_thresh=1e-2):+ ''' composite rays' rgbs, according to the ray marching formula. (for inference)+ Args:+ n_alive: int, number of alive rays+ n_step: int, how many steps we march+ rays_alive: int, [n_alive], the alive rays' IDs in N (N >= n_alive)+ rays_t: float, [N], the alive rays' time+ sigmas: float, [n_alive * n_step,]+ rgbs: float, [n_alive * n_step, 3]+ normals: float, [n_alive * n_step, 3]+ deltas: float, [n_alive * n_step, 2], all generated points' deltas (here we record two deltas, the first is for RGB, the second for depth).+ In-place Outputs:+ weights_sum: float, [N,], the alpha channel+ depth: float, [N,], the depth value+ image: float, [N, 3], the RGB channel (after multiplying alpha!)+ normal: float, [N, 3], the normal value+ '''+ sigmas = sigmas.float().contiguous()+ rgbs = rgbs.float().contiguous()+ normals = normals.float().contiguous()++ get_backend().composite_rays(n_alive, n_step, T_thresh, rays_alive, rays_t, sigmas, rgbs, normals, deltas, weights_sum, depth, image, normal)+ return tuple()+++composite_rays = _composite_rays.apply++class _composite_sdf_rays(Function):+ @staticmethod+ @custom_fwd(cast_inputs=torch.float32) # need to cast sigmas & rgbs to float+ def forward(ctx, n_alive, n_step, rays_alive, rays_t, sigmas, rgbs, deltas, weights_sum, depth, image, T_thresh=1e-2):+ ''' composite rays' rgbs, according to the ray marching formula. (for inference)+ Args:+ n_alive: int, number of alive rays+ n_step: int, how many steps we march+ rays_alive: int, [n_alive], the alive rays' IDs in N (N >= n_alive)+ rays_t: float, [N], the alive rays' time+ sigmas: float, [n_alive * n_step,]+ rgbs: float, [n_alive * n_step, 3]+ deltas: float, [n_alive * n_step, 2], all generated points' deltas (here we record two deltas, the first is for RGB, the second for depth).+ In-place Outputs:+ weights_sum: float, [N,], the alpha channel+ depth: float, [N,], the depth value+ image: float, [N, 3], the RGB channel (after multiplying alpha!)+ '''+ get_backend().composite_sdf_rays(n_alive, n_step, T_thresh, rays_alive, rays_t, sigmas, rgbs, deltas, weights_sum, depth, image)+ return tuple()+++composite_sdf_rays = _composite_sdf_rays.apply\ No newline at end of filediff --git a/raymarching/setup.py b/raymarching/setup.pynew file mode 100644index 0000000..d974499--- /dev/null+++ b/raymarching/setup.py@@ -0,0 +1,62 @@+import os+from setuptools import setup+from torch.utils.cpp_extension import BuildExtension, CUDAExtension++_src_path = os.path.dirname(os.path.abspath(__file__))++nvcc_flags = [+ '-O3', '-std=c++14',+ '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__',+]++if os.name == "posix":+ c_flags = ['-O3', '-std=c++14']+elif os.name == "nt":+ c_flags = ['/O2', '/std:c++17']++ # find cl.exe+ def find_cl_path():+ import glob+ for edition in ["Enterprise", "Professional", "BuildTools", "Community"]:+ paths = sorted(glob.glob(r"C:\\Program Files (x86)\\Microsoft Visual Studio\\*\\%s\\VC\\Tools\\MSVC\\*\\bin\\Hostx64\\x64" % edition), reverse=True)+ if paths:+ return paths[0]++ # If cl.exe is not on path, try to find it.+ if os.system("where cl.exe >nul 2>nul") != 0:+ cl_path = find_cl_path()+ if cl_path is None:+ raise RuntimeError("Could not locate a supported Microsoft Visual C++ installation")+ os.environ["PATH"] += ";" + cl_path++'''+Usage:++python setup.py build_ext --inplace # build extensions locally, do not install (only can be used from the parent directory)++python setup.py install # build extensions and install (copy) to PATH.+pip install . # ditto but better (e.g., dependency & metadata handling)++python setup.py develop # build extensions and install (symbolic) to PATH.+pip install -e . # ditto but better (e.g., dependency & metadata handling)++'''+setup(+ name='raymarching', # package name, import this to use python API+ ext_modules=[+ CUDAExtension(+ name='_raymarching', # extension name, import this to use CUDA API+ sources=[os.path.join(_src_path, 'src', f) for f in [+ 'raymarching.cu',+ 'bindings.cpp',+ ]],+ extra_compile_args={+ 'cxx': c_flags,+ 'nvcc': nvcc_flags,+ }+ ),+ ],+ cmdclass={+ 'build_ext': BuildExtension,+ }+)\ No newline at end of filediff --git a/raymarching/src/bindings.cpp b/raymarching/src/bindings.cppnew file mode 100644index 0000000..119b807--- /dev/null+++ b/raymarching/src/bindings.cpp@@ -0,0 +1,23 @@+#include <torch/extension.h>++#include "raymarching.h"++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {+ // utils+ m.def("packbits", &packbits, "packbits (CUDA)");+ m.def("near_far_from_aabb", &near_far_from_aabb, "near_far_from_aabb (CUDA)");+ m.def("sph_from_ray", &sph_from_ray, "sph_from_ray (CUDA)");+ m.def("morton3D", &morton3D, "morton3D (CUDA)");+ m.def("morton3D_invert", &morton3D_invert, "morton3D_invert (CUDA)");+ // train+ m.def("march_rays_train", &march_rays_train, "march_rays_train (CUDA)");+ m.def("composite_rays_train_forward", &composite_rays_train_forward, "composite_rays_train_forward (CUDA)");+ m.def("composite_rays_train_backward", &composite_rays_train_backward, "composite_rays_train_backward (CUDA)");+ m.def("composite_sdf_rays_train_forward", &composite_sdf_rays_train_forward, "composite_sdf_rays_train_forward (CUDA)");+ m.def("composite_sdf_rays_train_backward", &composite_sdf_rays_train_backward, "composite_sdf_rays_train_backward (CUDA)");++ // infer+ m.def("march_rays", &march_rays, "march rays (CUDA)");+ m.def("composite_rays", &composite_rays, "composite rays (CUDA)");+ m.def("composite_sdf_rays", &composite_sdf_rays, "composite sdf rays (CUDA)");+}\ No newline at end of filediff --git a/raymarching/src/raymarching.cu b/raymarching/src/raymarching.cunew file mode 100644index 0000000..39e7456--- /dev/null+++ b/raymarching/src/raymarching.cu@@ -0,0 +1,1222 @@+#include <cuda.h>+#include <cuda_fp16.h>+#include <cuda_runtime.h>++#include <ATen/cuda/CUDAContext.h>+#include <torch/torch.h>++#include <cstdio>+#include <stdint.h>+#include <stdexcept>+#include <limits>++#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor")+#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be a contiguous tensor")+#define CHECK_IS_INT(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, #x " must be an int tensor")+#define CHECK_IS_FLOATING(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Float || x.scalar_type() == at::ScalarType::Half || x.scalar_type() == at::ScalarType::Double, #x " must be a floating tensor")+++inline constexpr __device__ float SQRT3() { return 1.7320508075688772f; }+inline constexpr __device__ float RSQRT3() { return 0.5773502691896258f; }+inline constexpr __device__ float PI() { return 3.141592653589793f; }+inline constexpr __device__ float RPI() { return 0.3183098861837907f; }+++template <typename T>+inline __host__ __device__ T div_round_up(T val, T divisor) {+ return (val + divisor - 1) / divisor;+}++inline __host__ __device__ float signf(const float x) {+ return copysignf(1.0, x);+}++inline __host__ __device__ float clamp(const float x, const float min, const float max) {+ return fminf(max, fmaxf(min, x));+}++inline __host__ __device__ void swapf(float& a, float& b) {+ float c = a; a = b; b = c;+}++inline __device__ int mip_from_pos(const float x, const float y, const float z, const float max_cascade) {+ const float mx = fmaxf(fabsf(x), fmaxf(fabs(y), fabs(z)));+ int exponent;+ frexpf(mx, &exponent); // [0, 0.5) --> -1, [0.5, 1) --> 0, [1, 2) --> 1, [2, 4) --> 2, ...+ return fminf(max_cascade - 1, fmaxf(0, exponent));+}++inline __device__ int mip_from_dt(const float dt, const float H, const float max_cascade) {+ const float mx = dt * H * 0.5;+ int exponent;+ frexpf(mx, &exponent);+ return fminf(max_cascade - 1, fmaxf(0, exponent));+}++inline __host__ __device__ uint32_t __expand_bits(uint32_t v)+{+ v = (v * 0x00010001u) & 0xFF0000FFu;+ v = (v * 0x00000101u) & 0x0F00F00Fu;+ v = (v * 0x00000011u) & 0xC30C30C3u;+ v = (v * 0x00000005u) & 0x49249249u;+ return v;+}++inline __host__ __device__ uint32_t __morton3D(uint32_t x, uint32_t y, uint32_t z)+{+ uint32_t xx = __expand_bits(x);+ uint32_t yy = __expand_bits(y);+ uint32_t zz = __expand_bits(z);+ return xx | (yy << 1) | (zz << 2);+}++inline __host__ __device__ uint32_t __morton3D_invert(uint32_t x)+{+ x = x & 0x49249249;+ x = (x | (x >> 2)) & 0xc30c30c3;+ x = (x | (x >> 4)) & 0x0f00f00f;+ x = (x | (x >> 8)) & 0xff0000ff;+ x = (x | (x >> 16)) & 0x0000ffff;+ return x;+}+++////////////////////////////////////////////////////+///////////// utils /////////////+////////////////////////////////////////////////////++// rays_o/d: [N, 3]+// nears/fars: [N]+// scalar_t should always be float in use.+template <typename scalar_t>+__global__ void kernel_near_far_from_aabb(+ const scalar_t * __restrict__ rays_o,+ const scalar_t * __restrict__ rays_d,+ const scalar_t * __restrict__ aabb,+ const uint32_t N,+ const float min_near,+ scalar_t * nears, scalar_t * fars+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ rays_o += n * 3;+ rays_d += n * 3;++ const float ox = rays_o[0], oy = rays_o[1], oz = rays_o[2];+ const float dx = rays_d[0], dy = rays_d[1], dz = rays_d[2];+ const float rdx = 1 / dx, rdy = 1 / dy, rdz = 1 / dz;++ // get near far (assume cube scene)+ float near = (aabb[0] - ox) * rdx;+ float far = (aabb[3] - ox) * rdx;+ if (near > far) swapf(near, far);++ float near_y = (aabb[1] - oy) * rdy;+ float far_y = (aabb[4] - oy) * rdy;+ if (near_y > far_y) swapf(near_y, far_y);++ if (near > far_y || near_y > far) {+ nears[n] = fars[n] = std::numeric_limits<scalar_t>::max();+ return;+ }++ if (near_y > near) near = near_y;+ if (far_y < far) far = far_y;++ float near_z = (aabb[2] - oz) * rdz;+ float far_z = (aabb[5] - oz) * rdz;+ if (near_z > far_z) swapf(near_z, far_z);++ if (near > far_z || near_z > far) {+ nears[n] = fars[n] = std::numeric_limits<scalar_t>::max();+ return;+ }++ if (near_z > near) near = near_z;+ if (far_z < far) far = far_z;++ if (near < min_near) near = min_near;++ nears[n] = near;+ fars[n] = far;+}+++void near_far_from_aabb(const at::Tensor rays_o, const at::Tensor rays_d, const at::Tensor aabb, const uint32_t N, const float min_near, at::Tensor nears, at::Tensor fars) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ rays_o.scalar_type(), "near_far_from_aabb", ([&] {+ kernel_near_far_from_aabb<<<div_round_up(N, N_THREAD), N_THREAD>>>(rays_o.data_ptr<scalar_t>(), rays_d.data_ptr<scalar_t>(), aabb.data_ptr<scalar_t>(), N, min_near, nears.data_ptr<scalar_t>(), fars.data_ptr<scalar_t>());+ }));+}+++// rays_o/d: [N, 3]+// radius: float+// coords: [N, 2]+template <typename scalar_t>+__global__ void kernel_sph_from_ray(+ const scalar_t * __restrict__ rays_o,+ const scalar_t * __restrict__ rays_d,+ const float radius,+ const uint32_t N,+ scalar_t * coords+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ rays_o += n * 3;+ rays_d += n * 3;+ coords += n * 2;++ const float ox = rays_o[0], oy = rays_o[1], oz = rays_o[2];+ const float dx = rays_d[0], dy = rays_d[1], dz = rays_d[2];+ const float rdx = 1 / dx, rdy = 1 / dy, rdz = 1 / dz;++ // solve t from || o + td || = radius+ const float A = dx * dx + dy * dy + dz * dz;+ const float B = ox * dx + oy * dy + oz * dz; // in fact B / 2+ const float C = ox * ox + oy * oy + oz * oz - radius * radius;++ const float t = (- B + sqrtf(B * B - A * C)) / A; // always use the larger solution (positive)++ // solve theta, phi (assume y is the up axis)+ const float x = ox + t * dx, y = oy + t * dy, z = oz + t * dz;+ const float theta = atan2(sqrtf(x * x + z * z), y); // [0, PI)+ const float phi = atan2(z, x); // [-PI, PI)++ // normalize to [-1, 1]+ coords[0] = 2 * theta * RPI() - 1;+ coords[1] = phi * RPI();+}+++void sph_from_ray(const at::Tensor rays_o, const at::Tensor rays_d, const float radius, const uint32_t N, at::Tensor coords) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ rays_o.scalar_type(), "sph_from_ray", ([&] {+ kernel_sph_from_ray<<<div_round_up(N, N_THREAD), N_THREAD>>>(rays_o.data_ptr<scalar_t>(), rays_d.data_ptr<scalar_t>(), radius, N, coords.data_ptr<scalar_t>());+ }));+}+++// coords: int32, [N, 3]+// indices: int32, [N]+__global__ void kernel_morton3D(+ const int * __restrict__ coords,+ const uint32_t N,+ int * indices+) {+ // parallel+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ coords += n * 3;+ indices[n] = __morton3D(coords[0], coords[1], coords[2]);+}+++void morton3D(const at::Tensor coords, const uint32_t N, at::Tensor indices) {+ static constexpr uint32_t N_THREAD = 128;+ kernel_morton3D<<<div_round_up(N, N_THREAD), N_THREAD>>>(coords.data_ptr<int>(), N, indices.data_ptr<int>());+}+++// indices: int32, [N]+// coords: int32, [N, 3]+__global__ void kernel_morton3D_invert(+ const int * __restrict__ indices,+ const uint32_t N,+ int * coords+) {+ // parallel+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ coords += n * 3;++ const int ind = indices[n];++ coords[0] = __morton3D_invert(ind >> 0);+ coords[1] = __morton3D_invert(ind >> 1);+ coords[2] = __morton3D_invert(ind >> 2);+}+++void morton3D_invert(const at::Tensor indices, const uint32_t N, at::Tensor coords) {+ static constexpr uint32_t N_THREAD = 128;+ kernel_morton3D_invert<<<div_round_up(N, N_THREAD), N_THREAD>>>(indices.data_ptr<int>(), N, coords.data_ptr<int>());+}+++// grid: float, [C, H, H, H]+// N: int, C * H * H * H / 8+// density_thresh: float+// bitfield: uint8, [N]+template <typename scalar_t>+__global__ void kernel_packbits(+ const scalar_t * __restrict__ grid,+ const uint32_t N,+ const float density_thresh,+ uint8_t * bitfield+) {+ // parallel per byte+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ grid += n * 8;++ uint8_t bits = 0;++ #pragma unroll+ for (uint8_t i = 0; i < 8; i++) {+ bits |= (grid[i] > density_thresh) ? ((uint8_t)1 << i) : 0;+ }++ bitfield[n] = bits;+}+++void packbits(const at::Tensor grid, const uint32_t N, const float density_thresh, at::Tensor bitfield) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ grid.scalar_type(), "packbits", ([&] {+ kernel_packbits<<<div_round_up(N, N_THREAD), N_THREAD>>>(grid.data_ptr<scalar_t>(), N, density_thresh, bitfield.data_ptr<uint8_t>());+ }));+}++////////////////////////////////////////////////////+///////////// training /////////////+////////////////////////////////////////////////////++// rays_o/d: [N, 3]+// grid: [CHHH / 8]+// xyzs, dirs, deltas: [M, 3], [M, 3], [M, 2]+// dirs: [M, 3]+// rays: [N, 3], idx, offset, num_steps+template <typename scalar_t>+__global__ void kernel_march_rays_train(+ const scalar_t * __restrict__ rays_o,+ const scalar_t * __restrict__ rays_d,+ const uint8_t * __restrict__ grid,+ const float bound,+ const float dt_gamma, const uint32_t max_steps,+ const uint32_t N, const uint32_t C, const uint32_t H, const uint32_t M,+ const scalar_t* __restrict__ nears,+ const scalar_t* __restrict__ fars,+ scalar_t * xyzs, scalar_t * dirs, scalar_t * deltas,+ int * rays,+ int * counter,+ const scalar_t* __restrict__ noises+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ rays_o += n * 3;+ rays_d += n * 3;++ // ray marching+ const float ox = rays_o[0], oy = rays_o[1], oz = rays_o[2];+ const float dx = rays_d[0], dy = rays_d[1], dz = rays_d[2];+ const float rdx = 1 / dx, rdy = 1 / dy, rdz = 1 / dz;+ const float rH = 1 / (float)H;+ const float H3 = H * H * H;++ const float near = nears[n];+ const float far = fars[n];+ const float noise = noises[n];++ const float dt_min = 2 * SQRT3() / max_steps;+ const float dt_max = 2 * SQRT3() * (1 << (C - 1)) / H;++ float t0 = near;++ // perturb+ t0 += clamp(t0 * dt_gamma, dt_min, dt_max) * noise;++ // first pass: estimation of num_steps+ float t = t0;+ uint32_t num_steps = 0;++ //if (t < far) printf("valid ray %d t=%f near=%f far=%f \n", n, t, near, far);++ while (t < far && num_steps < max_steps) {+ // current point+ const float x = clamp(ox + t * dx, -bound, bound);+ const float y = clamp(oy + t * dy, -bound, bound);+ const float z = clamp(oz + t * dz, -bound, bound);++ const float dt = clamp(t * dt_gamma, dt_min, dt_max);++ // get mip level+ const int level = max(mip_from_pos(x, y, z, C), mip_from_dt(dt, H, C)); // range in [0, C - 1]++ const float mip_bound = fminf(scalbnf(1.0f, level), bound);+ const float mip_rbound = 1 / mip_bound;++ // convert to nearest grid position+ const int nx = clamp(0.5 * (x * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int ny = clamp(0.5 * (y * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int nz = clamp(0.5 * (z * mip_rbound + 1) * H, 0.0f, (float)(H - 1));++ const uint32_t index = level * H3 + __morton3D(nx, ny, nz);+ const bool occ = grid[index / 8] & (1 << (index % 8));++ // if occpuied, advance a small step, and write to output+ //if (n == 0) printf("t=%f density=%f vs thresh=%f step=%d\n", t, density, density_thresh, num_steps);++ if (occ) {+ num_steps++;+ t += dt;+ // else, skip a large step (basically skip a voxel grid)+ } else {+ // calc distance to next voxel+ const float tx = (((nx + 0.5f + 0.5f * signf(dx)) * rH * 2 - 1) * mip_bound - x) * rdx;+ const float ty = (((ny + 0.5f + 0.5f * signf(dy)) * rH * 2 - 1) * mip_bound - y) * rdy;+ const float tz = (((nz + 0.5f + 0.5f * signf(dz)) * rH * 2 - 1) * mip_bound - z) * rdz;++ const float tt = t + fmaxf(0.0f, fminf(tx, fminf(ty, tz)));+ // step until next voxel+ do {+ t += clamp(t * dt_gamma, dt_min, dt_max);+ } while (t < tt);+ }+ }++ //printf("[n=%d] num_steps=%d, near=%f, far=%f, dt=%f, max_steps=%f\n", n, num_steps, near, far, dt_min, (far - near) / dt_min);++ // second pass: really locate and write points & dirs+ uint32_t point_index = atomicAdd(counter, num_steps);+ uint32_t ray_index = atomicAdd(counter + 1, 1);++ //printf("[n=%d] num_steps=%d, point_index=%d, ray_index=%d\n", n, num_steps, point_index, ray_index);++ // write rays+ rays[ray_index * 3] = n;+ rays[ray_index * 3 + 1] = point_index;+ rays[ray_index * 3 + 2] = num_steps;++ if (num_steps == 0) return;+ if (point_index + num_steps > M) return;++ xyzs += point_index * 3;+ dirs += point_index * 3;+ deltas += point_index * 2;++ t = t0;+ uint32_t step = 0;++ float last_t = t;++ while (t < far && step < num_steps) {+ // current point+ const float x = clamp(ox + t * dx, -bound, bound);+ const float y = clamp(oy + t * dy, -bound, bound);+ const float z = clamp(oz + t * dz, -bound, bound);++ const float dt = clamp(t * dt_gamma, dt_min, dt_max);++ // get mip level+ const int level = max(mip_from_pos(x, y, z, C), mip_from_dt(dt, H, C)); // range in [0, C - 1]++ const float mip_bound = fminf(scalbnf(1.0f, level), bound);+ const float mip_rbound = 1 / mip_bound;++ // convert to nearest grid position+ const int nx = clamp(0.5 * (x * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int ny = clamp(0.5 * (y * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int nz = clamp(0.5 * (z * mip_rbound + 1) * H, 0.0f, (float)(H - 1));++ // query grid+ const uint32_t index = level * H3 + __morton3D(nx, ny, nz);+ const bool occ = grid[index / 8] & (1 << (index % 8));++ // if occpuied, advance a small step, and write to output+ if (occ) {+ // write step+ xyzs[0] = x;+ xyzs[1] = y;+ xyzs[2] = z;+ dirs[0] = dx;+ dirs[1] = dy;+ dirs[2] = dz;+ t += dt;+ deltas[0] = dt;+ deltas[1] = t - last_t; // used to calc depth+ last_t = t;+ xyzs += 3;+ dirs += 3;+ deltas += 2;+ step++;+ // else, skip a large step (basically skip a voxel grid)+ } else {+ // calc distance to next voxel+ const float tx = (((nx + 0.5f + 0.5f * signf(dx)) * rH * 2 - 1) * mip_bound - x) * rdx;+ const float ty = (((ny + 0.5f + 0.5f * signf(dy)) * rH * 2 - 1) * mip_bound - y) * rdy;+ const float tz = (((nz + 0.5f + 0.5f * signf(dz)) * rH * 2 - 1) * mip_bound - z) * rdz;+ const float tt = t + fmaxf(0.0f, fminf(tx, fminf(ty, tz)));+ // step until next voxel+ do {+ t += clamp(t * dt_gamma, dt_min, dt_max);+ } while (t < tt);+ }+ }+}++void march_rays_train(const at::Tensor rays_o, const at::Tensor rays_d, const at::Tensor grid, const float bound, const float dt_gamma, const uint32_t max_steps, const uint32_t N, const uint32_t C, const uint32_t H, const uint32_t M, const at::Tensor nears, const at::Tensor fars, at::Tensor xyzs, at::Tensor dirs, at::Tensor deltas, at::Tensor rays, at::Tensor counter, at::Tensor noises) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ rays_o.scalar_type(), "march_rays_train", ([&] {+ kernel_march_rays_train<<<div_round_up(N, N_THREAD), N_THREAD>>>(rays_o.data_ptr<scalar_t>(), rays_d.data_ptr<scalar_t>(), grid.data_ptr<uint8_t>(), bound, dt_gamma, max_steps, N, C, H, M, nears.data_ptr<scalar_t>(), fars.data_ptr<scalar_t>(), xyzs.data_ptr<scalar_t>(), dirs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), rays.data_ptr<int>(), counter.data_ptr<int>(), noises.data_ptr<scalar_t>());+ }));+}+++// sigmas: [M]+// rgbs: [M, 3]+// deltas: [M, 2]+// rays: [N, 3], idx, offset, num_steps+// weights_sum: [N], final pixel alpha+// depth: [N,]+// image: [N, 3]+template <typename scalar_t>+__global__ void kernel_composite_rays_train_forward(+ const scalar_t * __restrict__ sigmas,+ const scalar_t * __restrict__ rgbs,+ const scalar_t * __restrict__ deltas,+ const int * __restrict__ rays,+ const uint32_t M, const uint32_t N, const float T_thresh,+ scalar_t * weights_sum,+ scalar_t * depth,+ scalar_t * image+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ uint32_t index = rays[n * 3];+ uint32_t offset = rays[n * 3 + 1];+ uint32_t num_steps = rays[n * 3 + 2];++ // empty ray, or ray that exceed max step count.+ if (num_steps == 0 || offset + num_steps > M) {+ weights_sum[index] = 0;+ depth[index] = 0;+ image[index * 3] = 0;+ image[index * 3 + 1] = 0;+ image[index * 3 + 2] = 0;+ return;+ }++ sigmas += offset;+ rgbs += offset * 3;+ deltas += offset * 2;++ // accumulate+ uint32_t step = 0;++ scalar_t T = 1.0f;+ scalar_t r = 0, g = 0, b = 0, ws = 0, t = 0, d = 0;++ while (step < num_steps) {++ const scalar_t alpha = 1.0f - __expf(- sigmas[0] * deltas[0]);+ const scalar_t weight = alpha * T;++ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];++ t += deltas[1]; // real delta+ d += weight * t;++ ws += weight;++ T *= 1.0f - alpha;++ // minimal remained transmittence+ if (T < T_thresh) break;++ //printf("[n=%d] num_steps=%d, alpha=%f, w=%f, T=%f, sum_dt=%f, d=%f\n", n, step, alpha, weight, T, sum_delta, d);++ // locate+ sigmas++;+ rgbs += 3;+ deltas += 2;++ step++;+ }++ //printf("[n=%d] rgb=(%f, %f, %f), d=%f\n", n, r, g, b, d);++ // write+ weights_sum[index] = ws; // weights_sum+ depth[index] = d;+ image[index * 3] = r;+ image[index * 3 + 1] = g;+ image[index * 3 + 2] = b;+}+++void composite_rays_train_forward(const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor weights_sum, at::Tensor depth, at::Tensor image) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ sigmas.scalar_type(), "composite_rays_train_forward", ([&] {+ kernel_composite_rays_train_forward<<<div_round_up(N, N_THREAD), N_THREAD>>>(sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), rays.data_ptr<int>(), M, N, T_thresh, weights_sum.data_ptr<scalar_t>(), depth.data_ptr<scalar_t>(), image.data_ptr<scalar_t>());+ }));+}+++// grad_weights_sum: [N,]+// grad: [N, 3]+// sigmas: [M]+// rgbs: [M, 3]+// deltas: [M, 2]+// rays: [N, 3], idx, offset, num_steps+// weights_sum: [N,], weights_sum here+// image: [N, 3]+// grad_sigmas: [M]+// grad_rgbs: [M, 3]+template <typename scalar_t>+__global__ void kernel_composite_rays_train_backward(+ const scalar_t * __restrict__ grad_weights_sum,+ const scalar_t * __restrict__ grad_image,+ const scalar_t * __restrict__ sigmas,+ const scalar_t * __restrict__ rgbs,+ const scalar_t * __restrict__ deltas,+ const int * __restrict__ rays,+ const scalar_t * __restrict__ weights_sum,+ const scalar_t * __restrict__ image,+ const uint32_t M, const uint32_t N, const float T_thresh,+ scalar_t * grad_sigmas,+ scalar_t * grad_rgbs+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ uint32_t index = rays[n * 3];+ uint32_t offset = rays[n * 3 + 1];+ uint32_t num_steps = rays[n * 3 + 2];++ if (num_steps == 0 || offset + num_steps > M) return;++ grad_weights_sum += index;+ grad_image += index * 3;+ weights_sum += index;+ image += index * 3;+ sigmas += offset;+ rgbs += offset * 3;+ deltas += offset * 2;+ grad_sigmas += offset;+ grad_rgbs += offset * 3;++ // accumulate+ uint32_t step = 0;++ scalar_t T = 1.0f;+ const scalar_t r_final = image[0], g_final = image[1], b_final = image[2], ws_final = weights_sum[0];+ scalar_t r = 0, g = 0, b = 0, ws = 0;++ while (step < num_steps) {++ const scalar_t alpha = 1.0f - __expf(- sigmas[0] * deltas[0]);+ const scalar_t weight = alpha * T;++ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];+ ws += weight;++ T *= 1.0f - alpha;++ // check https://note.kiui.moe/others/nerf_gradient/ for the gradient calculation.+ // write grad_rgbs+ grad_rgbs[0] = grad_image[0] * weight;+ grad_rgbs[1] = grad_image[1] * weight;+ grad_rgbs[2] = grad_image[2] * weight;++ // write grad_sigmas+ grad_sigmas[0] = deltas[0] * (+ grad_image[0] * (T * rgbs[0] - (r_final - r)) ++ grad_image[1] * (T * rgbs[1] - (g_final - g)) ++ grad_image[2] * (T * rgbs[2] - (b_final - b)) ++ grad_weights_sum[0] * (1 - ws_final)+ );++ //printf("[n=%d] num_steps=%d, T=%f, grad_sigmas=%f, r_final=%f, r=%f\n", n, step, T, grad_sigmas[0], r_final, r);+ // minimal remained transmittence+ if (T < T_thresh) break;++ // locate+ sigmas++;+ rgbs += 3;+ deltas += 2;+ grad_sigmas++;+ grad_rgbs += 3;++ step++;+ }+}+++void composite_rays_train_backward(const at::Tensor grad_weights_sum, const at::Tensor grad_image, const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const at::Tensor weights_sum, const at::Tensor image, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor grad_sigmas, at::Tensor grad_rgbs) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ grad_image.scalar_type(), "composite_rays_train_backward", ([&] {+ kernel_composite_rays_train_backward<<<div_round_up(N, N_THREAD), N_THREAD>>>(grad_weights_sum.data_ptr<scalar_t>(), grad_image.data_ptr<scalar_t>(), sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), rays.data_ptr<int>(), weights_sum.data_ptr<scalar_t>(), image.data_ptr<scalar_t>(), M, N, T_thresh, grad_sigmas.data_ptr<scalar_t>(), grad_rgbs.data_ptr<scalar_t>());+ }));+}+++////////////////////////////////////////////////////+///////////// sdf /////////////+////////////////////////////////////////////////////+++// sigmas: [M]+// rgbs: [M, 3]+// deltas: [M, 2]+// rays: [N, 3], idx, offset, num_steps+// weights_sum: [N], final pixel alpha+// depth: [N,]+// image: [N, 3]+template <typename scalar_t>+__global__ void kernel_composite_sdf_rays_train_forward(+ const scalar_t * __restrict__ sigmas,+ const scalar_t * __restrict__ rgbs,+ const scalar_t * __restrict__ deltas,+ const int * __restrict__ rays,+ const uint32_t M, const uint32_t N, const float T_thresh,+ scalar_t * weights_sum,+ scalar_t * depth,+ scalar_t * image+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ uint32_t index = rays[n * 3];+ uint32_t offset = rays[n * 3 + 1];+ uint32_t num_steps = rays[n * 3 + 2];++ // empty ray, or ray that exceed max step count.+ if (num_steps == 0 || offset + num_steps > M) {+ weights_sum[index] = 0;+ depth[index] = 0;+ image[index * 3] = 0;+ image[index * 3 + 1] = 0;+ image[index * 3 + 2] = 0;+ return;+ }++ sigmas += offset;+ rgbs += offset * 3;+ deltas += offset * 2;++ // accumulate+ uint32_t step = 0;++ scalar_t T = 1.0f;+ scalar_t r = 0, g = 0, b = 0, t = 0, d = 0;++ while (step < num_steps) {++ const scalar_t alpha = sigmas[0]; //1.0f - __expf(- sigmas[0] * deltas[0]);+ const scalar_t weight = alpha * T;++ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];++ t += deltas[1]; // real delta+ d += weight * t;++ T *= 1.0f - alpha;++ // minimal remained transmittence+ if (T < T_thresh) break;++ //printf("[n=%d] num_steps=%d, alpha=%f, w=%f, T=%f, sum_dt=%f, d=%f\n", n, step, alpha, weight, T, sum_delta, d);++ // locate+ sigmas++;+ rgbs += 3;+ deltas += 2;++ step++;+ }++ //printf("[n=%d] rgb=(%f, %f, %f), d=%f\n", n, r, g, b, d);++ // write+ weights_sum[index] = 1.0f - T; // weights_sum+ depth[index] = d;+ image[index * 3] = r;+ image[index * 3 + 1] = g;+ image[index * 3 + 2] = b;+}+++void composite_sdf_rays_train_forward(const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor weights_sum, at::Tensor depth, at::Tensor image) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ sigmas.scalar_type(), "composite_sdf_rays_train_forward", ([&] {+ kernel_composite_sdf_rays_train_forward<<<div_round_up(N, N_THREAD), N_THREAD>>>(sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), rays.data_ptr<int>(), M, N, T_thresh, weights_sum.data_ptr<scalar_t>(), depth.data_ptr<scalar_t>(), image.data_ptr<scalar_t>());+ }));+}+++// grad_weights_sum: [N,]+// grad: [N, 3]+// sigmas: [M]+// rgbs: [M, 3]+// deltas: [M, 2]+// rays: [N, 3], idx, offset, num_steps+// weights_sum: [N,], weights_sum here+// image: [N, 3]+// grad_sigmas: [M]+// grad_rgbs: [M, 3]+template <typename scalar_t>+__global__ void kernel_composite_sdf_rays_train_backward(+ const scalar_t * __restrict__ grad_weights_sum,+ const scalar_t * __restrict__ grad_image,+ const scalar_t * __restrict__ sigmas,+ const scalar_t * __restrict__ rgbs,+ const scalar_t * __restrict__ deltas,+ const int * __restrict__ rays,+ const scalar_t * __restrict__ weights_sum,+ const scalar_t * __restrict__ image,+ const uint32_t M, const uint32_t N, const float T_thresh,+ scalar_t * grad_sigmas,+ scalar_t * grad_rgbs+) {+ // parallel per ray+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= N) return;++ // locate+ uint32_t index = rays[n * 3];+ uint32_t offset = rays[n * 3 + 1];+ uint32_t num_steps = rays[n * 3 + 2];++ if (num_steps == 0 || offset + num_steps > M) return;++ grad_weights_sum += index;+ grad_image += index * 3;+ weights_sum += index;+ image += index * 3;+ sigmas += offset;+ rgbs += offset * 3;+ deltas += offset * 2;+ grad_sigmas += offset;+ grad_rgbs += offset * 3;++ // accumulate+ uint32_t step = 0;++ scalar_t T = 1.0f;+ const scalar_t r_final = image[0], g_final = image[1], b_final = image[2], ws_final = weights_sum[0];+ scalar_t r = 0, g = 0, b = 0;++ while (step < num_steps) {++ const scalar_t alpha = sigmas[0]; //1.0f - __expf(- sigmas[0] * deltas[0]);+ const scalar_t weight = alpha * T;++ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];++ T *= 1.0f - alpha;++ // check https://note.kiui.moe/others/nerf_gradient/ for the gradient calculation.+ // write grad_rgbs+ grad_rgbs[0] = grad_image[0] * weight;+ grad_rgbs[1] = grad_image[1] * weight;+ grad_rgbs[2] = grad_image[2] * weight;++ // write grad_sigmas+ grad_sigmas[0] = deltas[0] * (+ grad_image[0] * (T * rgbs[0] - (r_final - r)) ++ grad_image[1] * (T * rgbs[1] - (g_final - g)) ++ grad_image[2] * (T * rgbs[2] - (b_final - b)) ++ grad_weights_sum[0] * (1 - ws_final)+ );++ //printf("[n=%d] num_steps=%d, T=%f, grad_sigmas=%f, r_final=%f, r=%f\n", n, step, T, grad_sigmas[0], r_final, r);+ // minimal remained transmittence+ if (T < T_thresh) break;++ // locate+ sigmas++;+ rgbs += 3;+ deltas += 2;+ grad_sigmas++;+ grad_rgbs += 3;++ step++;+ }+}+++void composite_sdf_rays_train_backward(const at::Tensor grad_weights_sum, const at::Tensor grad_image, const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const at::Tensor weights_sum, const at::Tensor image, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor grad_sigmas, at::Tensor grad_rgbs) {++ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ grad_image.scalar_type(), "composite_sdf_rays_train_backward", ([&] {+ kernel_composite_sdf_rays_train_backward<<<div_round_up(N, N_THREAD), N_THREAD>>>(grad_weights_sum.data_ptr<scalar_t>(), grad_image.data_ptr<scalar_t>(), sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), rays.data_ptr<int>(), weights_sum.data_ptr<scalar_t>(), image.data_ptr<scalar_t>(), M, N, T_thresh, grad_sigmas.data_ptr<scalar_t>(), grad_rgbs.data_ptr<scalar_t>());+ }));+}++++////////////////////////////////////////////////////+///////////// infernce /////////////+////////////////////////////////////////////////////++template <typename scalar_t>+__global__ void kernel_march_rays(+ const uint32_t n_alive,+ const uint32_t n_step,+ const int* __restrict__ rays_alive,+ const scalar_t* __restrict__ rays_t,+ const scalar_t* __restrict__ rays_o,+ const scalar_t* __restrict__ rays_d,+ const float bound,+ const float dt_gamma, const uint32_t max_steps,+ const uint32_t C, const uint32_t H,+ const uint8_t * __restrict__ grid,+ const scalar_t* __restrict__ nears,+ const scalar_t* __restrict__ fars,+ scalar_t* xyzs, scalar_t* dirs, scalar_t* deltas,+ const scalar_t* __restrict__ noises+) {+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= n_alive) return;++ const int index = rays_alive[n]; // ray id+ const float noise = noises[n];++ // locate+ rays_o += index * 3;+ rays_d += index * 3;+ xyzs += n * n_step * 3;+ dirs += n * n_step * 3;+ deltas += n * n_step * 2;++ const float ox = rays_o[0], oy = rays_o[1], oz = rays_o[2];+ const float dx = rays_d[0], dy = rays_d[1], dz = rays_d[2];+ const float rdx = 1 / dx, rdy = 1 / dy, rdz = 1 / dz;+ const float rH = 1 / (float)H;+ const float H3 = H * H * H;++ float t = rays_t[index]; // current ray's t+ const float near = nears[index], far = fars[index];++ const float dt_min = 2 * SQRT3() / max_steps;+ const float dt_max = 2 * SQRT3() * (1 << (C - 1)) / H;++ // march for n_step steps, record points+ uint32_t step = 0;++ // introduce some randomness+ t += clamp(t * dt_gamma, dt_min, dt_max) * noise;++ float last_t = t;++ while (t < far && step < n_step) {+ // current point+ const float x = clamp(ox + t * dx, -bound, bound);+ const float y = clamp(oy + t * dy, -bound, bound);+ const float z = clamp(oz + t * dz, -bound, bound);++ const float dt = clamp(t * dt_gamma, dt_min, dt_max);++ // get mip level+ const int level = max(mip_from_pos(x, y, z, C), mip_from_dt(dt, H, C)); // range in [0, C - 1]++ const float mip_bound = fminf(scalbnf(1, level), bound);+ const float mip_rbound = 1 / mip_bound;++ // convert to nearest grid position+ const int nx = clamp(0.5 * (x * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int ny = clamp(0.5 * (y * mip_rbound + 1) * H, 0.0f, (float)(H - 1));+ const int nz = clamp(0.5 * (z * mip_rbound + 1) * H, 0.0f, (float)(H - 1));++ const uint32_t index = level * H3 + __morton3D(nx, ny, nz);+ const bool occ = grid[index / 8] & (1 << (index % 8));++ // if occpuied, advance a small step, and write to output+ if (occ) {+ // write step+ xyzs[0] = x;+ xyzs[1] = y;+ xyzs[2] = z;+ dirs[0] = dx;+ dirs[1] = dy;+ dirs[2] = dz;+ // calc dt+ t += dt;+ deltas[0] = dt;+ deltas[1] = t - last_t; // used to calc depth+ last_t = t;+ // step+ xyzs += 3;+ dirs += 3;+ deltas += 2;+ step++;++ // else, skip a large step (basically skip a voxel grid)+ } else {+ // calc distance to next voxel+ const float tx = (((nx + 0.5f + 0.5f * signf(dx)) * rH * 2 - 1) * mip_bound - x) * rdx;+ const float ty = (((ny + 0.5f + 0.5f * signf(dy)) * rH * 2 - 1) * mip_bound - y) * rdy;+ const float tz = (((nz + 0.5f + 0.5f * signf(dz)) * rH * 2 - 1) * mip_bound - z) * rdz;+ const float tt = t + fmaxf(0.0f, fminf(tx, fminf(ty, tz)));+ // step until next voxel+ do {+ t += clamp(t * dt_gamma, dt_min, dt_max);+ } while (t < tt);+ }+ }+}+++void march_rays(const uint32_t n_alive, const uint32_t n_step, const at::Tensor rays_alive, const at::Tensor rays_t, const at::Tensor rays_o, const at::Tensor rays_d, const float bound, const float dt_gamma, const uint32_t max_steps, const uint32_t C, const uint32_t H, const at::Tensor grid, const at::Tensor near, const at::Tensor far, at::Tensor xyzs, at::Tensor dirs, at::Tensor deltas, at::Tensor noises) {+ static constexpr uint32_t N_THREAD = 128;++ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ rays_o.scalar_type(), "march_rays", ([&] {+ kernel_march_rays<<<div_round_up(n_alive, N_THREAD), N_THREAD>>>(n_alive, n_step, rays_alive.data_ptr<int>(), rays_t.data_ptr<scalar_t>(), rays_o.data_ptr<scalar_t>(), rays_d.data_ptr<scalar_t>(), bound, dt_gamma, max_steps, C, H, grid.data_ptr<uint8_t>(), near.data_ptr<scalar_t>(), far.data_ptr<scalar_t>(), xyzs.data_ptr<scalar_t>(), dirs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), noises.data_ptr<scalar_t>());+ }));+}++template <typename scalar_t>+__global__ void kernel_composite_rays(+ const uint32_t n_alive,+ const uint32_t n_step,+ const float T_thresh,+ int* rays_alive,+ scalar_t* rays_t,+ const scalar_t* __restrict__ sigmas,+ const scalar_t* __restrict__ rgbs,+ const scalar_t* __restrict__ normals,+ const scalar_t* __restrict__ deltas,+ scalar_t* weights_sum, scalar_t* depth, scalar_t* image, scalar_t* normal+) {+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= n_alive) return;++ const int index = rays_alive[n]; // ray id++ // locate+ sigmas += n * n_step;+ rgbs += n * n_step * 3;+ normals += n * n_step * 3;+ deltas += n * n_step * 2;++ rays_t += index;+ weights_sum += index;+ depth += index;+ image += index * 3;+ normal += index * 3;++ float t = rays_t[0];+ float d = depth[0], r = image[0], g = image[1], b = image[2], x_ = normal[0], y_ = normal[1], z_ = normal[2], weight_sum = weights_sum[0];++ // accumulate+ uint32_t step = 0;+ while (step < n_step) {++ // ray is terminated if t == 0+ if (deltas[0] == 0) break;++ const float alpha = 1.0f - __expf(- sigmas[0] * deltas[0]);++ /*+ T_0 = 1; T_i = \prod_{j=0}^{i-1} (1 - alpha_j)+ w_i = alpha_i * T_i+ -->+ T_i = 1 - \sum_{j=0}^{i-1} w_j+ */+ const float T = 1 - weight_sum;+ const float weight = alpha * T;+ weight_sum += weight;++ t += deltas[1];+ d += weight * t; // real depth+ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];+ x_ += weight * normals[0];+ y_ += weight * normals[1];+ z_ += weight * normals[2];++ //printf("[n=%d] num_steps=%d, alpha=%f, w=%f, T=%f, sum_dt=%f, d=%f\n", n, step, alpha, weight, T, sum_delta, d);++ // ray is terminated if T is too small+ // use a larger bound to further accelerate inference+ if (T < T_thresh) break;++ // locate+ sigmas++;+ rgbs += 3;+ normals += 3;+ deltas += 2;+ step++;+ }++ //printf("[n=%d] rgb=(%f, %f, %f), d=%f\n", n, r, g, b, d);++ // rays_alive = -1 means ray is terminated early.+ if (step < n_step) {+ rays_alive[n] = -1;+ } else {+ rays_t[0] = t;+ }++ weights_sum[0] = weight_sum; // this is the thing I needed!+ depth[0] = d;+ image[0] = r;+ image[1] = g;+ image[2] = b;+ normal[0] = x_;+ normal[1] = y_;+ normal[2] = z_;+}+++void composite_rays(const uint32_t n_alive, const uint32_t n_step, const float T_thresh, at::Tensor rays_alive, at::Tensor rays_t, at::Tensor sigmas, at::Tensor rgbs, at::Tensor normals, at::Tensor deltas, at::Tensor weights, at::Tensor depth, at::Tensor image, at::Tensor normal) {+ static constexpr uint32_t N_THREAD = 128;+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ image.scalar_type(), "composite_rays", ([&] {+ kernel_composite_rays<<<div_round_up(n_alive, N_THREAD), N_THREAD>>>(n_alive, n_step, T_thresh, rays_alive.data_ptr<int>(), rays_t.data_ptr<scalar_t>(), sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), normals.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), weights.data_ptr<scalar_t>(), depth.data_ptr<scalar_t>(), image.data_ptr<scalar_t>(), normal.data_ptr<scalar_t>());+ }));+}++template <typename scalar_t>+__global__ void kernel_composite_sdf_rays(+ const uint32_t n_alive,+ const uint32_t n_step,+ const float T_thresh,+ int* rays_alive,+ scalar_t* rays_t,+ const scalar_t* __restrict__ sigmas,+ const scalar_t* __restrict__ rgbs,+ const scalar_t* __restrict__ deltas,+ scalar_t* weights_sum, scalar_t* depth, scalar_t* image+) {+ const uint32_t n = threadIdx.x + blockIdx.x * blockDim.x;+ if (n >= n_alive) return;++ const int index = rays_alive[n]; // ray id++ // locate+ sigmas += n * n_step;+ rgbs += n * n_step * 3;+ deltas += n * n_step * 2;++ rays_t += index;+ weights_sum += index;+ depth += index;+ image += index * 3;++ scalar_t t = rays_t[0]; // current ray's t++ scalar_t weight_sum = weights_sum[0];+ scalar_t d = depth[0];+ scalar_t r = image[0];+ scalar_t g = image[1];+ scalar_t b = image[2];++ // accumulate+ uint32_t step = 0;+ while (step < n_step) {++ // ray is terminated if delta == 0+ if (deltas[0] == 0) break;++ const scalar_t alpha = sigmas[0]; //1.0f - __expf(- sigmas[0] * deltas[0]);++ /*+ T_0 = 1; T_i = \prod_{j=0}^{i-1} (1 - alpha_j)+ w_i = alpha_i * T_i+ -->+ T_i = 1 - \sum_{j=0}^{i-1} w_j+ */+ const scalar_t T = 1 - weight_sum;+ const scalar_t weight = alpha * T;+ weight_sum += weight;++ t += deltas[1]; // real delta+ d += weight * t;+ r += weight * rgbs[0];+ g += weight * rgbs[1];+ b += weight * rgbs[2];++ //printf("[n=%d] num_steps=%d, alpha=%f, w=%f, T=%f, sum_dt=%f, d=%f\n", n, step, alpha, weight, T, sum_delta, d);++ // ray is terminated if T is too small+ // use a larger bound to further accelerate inference+ if (T < T_thresh) break;++ // locate+ sigmas++;+ rgbs += 3;+ deltas += 2;+ step++;+ }++ //printf("[n=%d] rgb=(%f, %f, %f), d=%f\n", n, r, g, b, d);++ // rays_alive = -1 means ray is terminated early.+ if (step < n_step) {+ rays_alive[n] = -1;+ } else {+ rays_t[0] = t;+ }++ weights_sum[0] = weight_sum; // this is the thing I needed!+ depth[0] = d;+ image[0] = r;+ image[1] = g;+ image[2] = b;+}+++void composite_sdf_rays(const uint32_t n_alive, const uint32_t n_step, const float T_thresh, at::Tensor rays_alive, at::Tensor rays_t, at::Tensor sigmas, at::Tensor rgbs, at::Tensor deltas, at::Tensor weights, at::Tensor depth, at::Tensor image) {+ static constexpr uint32_t N_THREAD = 128;+ AT_DISPATCH_FLOATING_TYPES_AND_HALF(+ image.scalar_type(), "composite_sdf_rays", ([&] {+ kernel_composite_sdf_rays<<<div_round_up(n_alive, N_THREAD), N_THREAD>>>(n_alive, n_step, T_thresh, rays_alive.data_ptr<int>(), rays_t.data_ptr<scalar_t>(), sigmas.data_ptr<scalar_t>(), rgbs.data_ptr<scalar_t>(), deltas.data_ptr<scalar_t>(), weights.data_ptr<scalar_t>(), depth.data_ptr<scalar_t>(), image.data_ptr<scalar_t>());+ }));+}\ No newline at end of filediff --git a/raymarching/src/raymarching.h b/raymarching/src/raymarching.hnew file mode 100644index 0000000..8d16b19--- /dev/null+++ b/raymarching/src/raymarching.h@@ -0,0 +1,22 @@+#pragma once++#include <stdint.h>+#include <torch/torch.h>+++void near_far_from_aabb(const at::Tensor rays_o, const at::Tensor rays_d, const at::Tensor aabb, const uint32_t N, const float min_near, at::Tensor nears, at::Tensor fars);+void sph_from_ray(const at::Tensor rays_o, const at::Tensor rays_d, const float radius, const uint32_t N, at::Tensor coords);+void morton3D(const at::Tensor coords, const uint32_t N, at::Tensor indices);+void morton3D_invert(const at::Tensor indices, const uint32_t N, at::Tensor coords);+void packbits(const at::Tensor grid, const uint32_t N, const float density_thresh, at::Tensor bitfield);++void march_rays_train(const at::Tensor rays_o, const at::Tensor rays_d, const at::Tensor grid, const float bound, const float dt_gamma, const uint32_t max_steps, const uint32_t N, const uint32_t C, const uint32_t H, const uint32_t M, const at::Tensor nears, const at::Tensor fars, at::Tensor xyzs, at::Tensor dirs, at::Tensor deltas, at::Tensor rays, at::Tensor counter, at::Tensor noises);+void composite_rays_train_forward(const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor weights_sum, at::Tensor depth, at::Tensor image);+void composite_rays_train_backward(const at::Tensor grad_weights_sum, const at::Tensor grad_image, const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const at::Tensor weights_sum, const at::Tensor image, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor grad_sigmas, at::Tensor grad_rgbs);+void composite_sdf_rays_train_forward(const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor weights_sum, at::Tensor depth, at::Tensor image);+void composite_sdf_rays_train_backward(const at::Tensor grad_weights_sum, const at::Tensor grad_image, const at::Tensor sigmas, const at::Tensor rgbs, const at::Tensor deltas, const at::Tensor rays, const at::Tensor weights_sum, const at::Tensor image, const uint32_t M, const uint32_t N, const float T_thresh, at::Tensor grad_sigmas, at::Tensor grad_rgbs);+++void march_rays(const uint32_t n_alive, const uint32_t n_step, const at::Tensor rays_alive, const at::Tensor rays_t, const at::Tensor rays_o, const at::Tensor rays_d, const float bound, const float dt_gamma, const uint32_t max_steps, const uint32_t C, const uint32_t H, const at::Tensor grid, const at::Tensor nears, const at::Tensor fars, at::Tensor xyzs, at::Tensor dirs, at::Tensor deltas, at::Tensor noises);+void composite_rays(const uint32_t n_alive, const uint32_t n_step, const float T_thresh, at::Tensor rays_alive, at::Tensor rays_t, at::Tensor sigmas, at::Tensor rgbs, at::Tensor normals, at::Tensor deltas, at::Tensor weights_sum, at::Tensor depth, at::Tensor image, at::Tensor normal);+void composite_sdf_rays(const uint32_t n_alive, const uint32_t n_step, const float T_thresh, at::Tensor rays_alive, at::Tensor rays_t, at::Tensor sigmas, at::Tensor rgbs, at::Tensor deltas, at::Tensor weights_sum, at::Tensor depth, at::Tensor image);\ No newline at end of filediff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..d170999--- /dev/null+++ b/requirements.txt@@ -0,0 +1,22 @@+ninja+trimesh+opencv-python+tensorboardX+numpy+pandas+tqdm+matplotlib+PyMCubes+rich+dearpygui+scipy+xatlas+scikit-learn+imageio+imageio-ffmpeg+timm+einops+open3d==0.9.0.0+torchmetrics+tensorboard+torch-ema\ No newline at end of file