From a5c61399944d913bcf219d7268475f45b084b031 Mon Sep 17 00:00:00 2001 From: Chung Min Kim Date: Fri, 31 Mar 2023 21:38:43 +0000 Subject: [PATCH] Consolidate lerf to diff proj, pip-installable --- nerfstudio/configs/method_configs.py | 45 --- .../data/datamanagers/lerf_datamanager.py | 108 ------ nerfstudio/data/utils/dino_dataloader.py | 190 --------- nerfstudio/data/utils/dino_extractor.py | 363 ------------------ nerfstudio/data/utils/feature_dataloader.py | 41 -- nerfstudio/data/utils/patched_dataloader.py | 149 ------- nerfstudio/data/utils/pyramid_interpolator.py | 145 ------- nerfstudio/fields/visibility_field.py | 100 ----- .../models => projects-lerf/lerf}/lerf.py | 4 +- projects-lerf/lerf/lerf_config.py | 59 +++ .../lerf}/lerf_encoders.py | 0 .../lerf}/lerf_field.py | 0 .../lerf}/lerf_pipeline.py | 30 +- projects-lerf/pyproject.toml | 6 + 14 files changed, 73 insertions(+), 1167 deletions(-) delete mode 100644 nerfstudio/data/datamanagers/lerf_datamanager.py delete mode 100644 nerfstudio/data/utils/dino_dataloader.py delete mode 100644 nerfstudio/data/utils/dino_extractor.py delete mode 100644 nerfstudio/data/utils/feature_dataloader.py delete mode 100644 nerfstudio/data/utils/patched_dataloader.py delete mode 100644 nerfstudio/data/utils/pyramid_interpolator.py delete mode 100644 nerfstudio/fields/visibility_field.py rename {nerfstudio/models => projects-lerf/lerf}/lerf.py (98%) create mode 100644 projects-lerf/lerf/lerf_config.py rename {nerfstudio/pipelines => projects-lerf/lerf}/lerf_encoders.py (100%) rename {nerfstudio/fields => projects-lerf/lerf}/lerf_field.py (100%) rename {nerfstudio/pipelines => projects-lerf/lerf}/lerf_pipeline.py (78%) create mode 100644 projects-lerf/pyproject.toml diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py index 253f01338..22635a911 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -67,7 +67,6 @@ from nerfstudio.plugins.registry import discover_methods method_configs: Dict[str, TrainerConfig] = {} descriptions = { - "lerf": "TODO", "nerfacto": "Recommended real-time model tuned for real captures. This model will be continually updated.", "depth-nerfacto": "Nerfacto with depth supervision.", "volinga": "Real-time rendering model from Volinga. Directly exportable to NVOL format at https://volinga.ai/", @@ -84,50 +83,6 @@ descriptions = { "neus": "Implementation of NeuS. (slow)", } -from nerfstudio.data.datamanagers.lerf_datamanager import LERFDataManagerConfig -from nerfstudio.models.lerf import LERFModelConfig -from nerfstudio.pipelines.lerf_pipeline import LERFPipelineConfig, OpenCLIPNetworkConfig - -method_configs["lerf"] = TrainerConfig( - method_name="lerf", - steps_per_eval_batch=500, - steps_per_save=2000, - max_num_iterations=30000, - mixed_precision=True, - pipeline=LERFPipelineConfig( - datamanager=LERFDataManagerConfig( - dataparser=NerfstudioDataParserConfig(train_split_fraction=0.99), - train_num_rays_per_batch=4096, - eval_num_rays_per_batch=4096, - camera_optimizer=CameraOptimizerConfig( - mode="SO3xR3", optimizer=AdamOptimizerConfig(lr=6e-4, eps=1e-8, weight_decay=1e-2) - ), - ), - model=LERFModelConfig(eval_num_rays_per_chunk=1 << 16), - network=OpenCLIPNetworkConfig( - clip_model_type = "ViT-B-16", - clip_model_pretrained = "laion2b_s34b_b88k", - clip_n_dims= 512 - ) - ), - optimizers={ - "proposal_networks": { - "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), - "scheduler": None, - }, - "fields": { - "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), - "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-3, max_steps=30000), - }, - "lerf": { - "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), - "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-3, max_steps=7000), - }, - }, - viewer=ViewerConfig(num_rays_per_chunk=1 << 15), - vis="viewer", -) - method_configs["nerfacto"] = TrainerConfig( method_name="nerfacto", steps_per_eval_batch=500, diff --git a/nerfstudio/data/datamanagers/lerf_datamanager.py b/nerfstudio/data/datamanagers/lerf_datamanager.py deleted file mode 100644 index 7c5a411d0..000000000 --- a/nerfstudio/data/datamanagers/lerf_datamanager.py +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright 2022 The Nerfstudio Team. All rights reserved. -# -# 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. - -""" -Datamanager. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, Type, Union - -import torch -from rich.progress import Console - -from nerfstudio.data.utils.nerfstudio_collate import nerfstudio_collate -from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes -from nerfstudio.model_components.ray_generators import RayGenerator -from nerfstudio.utils.misc import IterableWrapper - -CONSOLE = Console(width=120) - -from nerfstudio.data.datamanagers.base_datamanager import ( - VanillaDataManager, - VanillaDataManagerConfig, -) -from nerfstudio.data.utils.dino_dataloader import DinoDataloader -from nerfstudio.data.utils.patched_dataloader import PatchedDataloader -from nerfstudio.pipelines.lerf_encoders import ImageEncoder - - -@dataclass -class LERFDataManagerConfig(VanillaDataManagerConfig): - _target: Type = field(default_factory=lambda: LERFDataManager) - - -class LERFDataManager(VanillaDataManager): # pylint: disable=abstract-method - """Basic stored data manager implementation. - - This is pretty much a port over from our old dataloading utilities, and is a little jank - under the hood. We may clean this up a little bit under the hood with more standard dataloading - components that can be strung together, but it can be just used as a black box for now since - only the constructor is likely to change in the future, or maybe passing in step number to the - next_train and next_eval functions. - - Args: - config: the DataManagerConfig used to instantiate class - """ - - config: LERFDataManagerConfig - - def __init__( - self, - config: LERFDataManagerConfig, - device: Union[torch.device, str] = "cpu", - test_mode: Literal["test", "val", "inference"] = "val", - world_size: int = 1, - local_rank: int = 0, - **kwargs, # pylint: disable=unused-argument - ): - super().__init__( - config=config, device=device, test_mode=test_mode, world_size=world_size, local_rank=local_rank, **kwargs - ) - self.image_encoder: ImageEncoder = kwargs["image_encoder"] - images = [self.train_dataset[i]["image"].permute(2, 0, 1)[None, ...] for i in range(len(self.train_dataset))] - images = torch.cat(images) - self.clip_interpolator = PatchedDataloader( - image_list=images, - device=self.device, - cfg={ - "tile_size_range": (0.05, 0.5), - "tile_size_res": 7, - "stride_scaler": 0.6, - }, - cache_dir=Path(f"outputs/{self.config.dataparser.data.name}"), - model=self.image_encoder, - ) - self.dino_dataloader = DinoDataloader( - image_list=images, device=self.device, cfg={}, cache_dir=Path(f"outputs/{self.config.dataparser.data.name}") - ) - - def next_train(self, step: int) -> Tuple[RayBundle, Dict]: - """Returns the next batch of data from the train dataloader.""" - self.train_count += 1 - image_batch = next(self.iter_train_image_dataloader) - assert self.train_pixel_sampler is not None - batch = self.train_pixel_sampler.sample(image_batch) - ray_indices = batch["indices"] - ray_bundle = self.train_ray_generator(ray_indices) - batch["clip"], clip_scale = self.clip_interpolator(ray_indices) - batch["dino"] = self.dino_dataloader(ray_indices) - ray_bundle.metadata["clip_scales"] = clip_scale - # assume all cameras have the same focal length and image width - ray_bundle.metadata["fx"] = self.train_dataset.cameras[0].fx.item() - ray_bundle.metadata["width"] = self.train_dataset.cameras[0].width.item() - return ray_bundle, batch diff --git a/nerfstudio/data/utils/dino_dataloader.py b/nerfstudio/data/utils/dino_dataloader.py deleted file mode 100644 index af79a015d..000000000 --- a/nerfstudio/data/utils/dino_dataloader.py +++ /dev/null @@ -1,190 +0,0 @@ -import dataclasses -import os -import typing - -import numpy as np -import torch -from tqdm import tqdm - -from nerfstudio.data.utils.dino_extractor import ViTExtractor -from nerfstudio.data.utils.feature_dataloader import FeatureDataloader - - -@dataclasses.dataclass -class DinoDataloader(FeatureDataloader): - def __post_init__(self): - self.cfg["dino_vit"] = {} - self.cfg["dino_vit"]["model_type"] = "dino_vits8" - self.cfg["dino_vit"]["stride"] = 8 - self.cfg["dino_vit"]["load_size"] = 500 - self.cfg["dino_vit"]["layer"] = 11 - self.cfg["dino_vit"]["facet"] = "key" - self.cfg["dino_vit"]["bin"] = False - self.try_load(self.cache_dir) - print("after load dino", torch.cuda.memory_allocated()) - - def create(self): - extractor = ViTExtractor( - self.cfg["dino_vit"]["model_type"], - self.cfg["dino_vit"]["stride"], - ) - - preproc_image_lst = extractor.preprocess(self.image_list, self.cfg["dino_vit"]["load_size"])[0].to(self.device) - - dino_embeds = [] - for image in tqdm(preproc_image_lst, desc="dino", total=len(self.image_list), leave=False): - descriptors = extractor.extract_descriptors( - image.unsqueeze(0), - [self.cfg["dino_vit"]["layer"]], - self.cfg["dino_vit"]["facet"], - self.cfg["dino_vit"]["bin"], - ) - descriptors = descriptors.reshape(extractor.num_patches[0], extractor.num_patches[1], -1) - dino_embeds.append(descriptors.cpu().detach()) - - self.data_dict = {} - self.data_dict["all"] = torch.stack(dino_embeds, dim=0) - self.cfg["img_scale"] = ( - self.data_dict["all"].shape[1] / self.image_list.shape[2], - self.data_dict["all"].shape[2] / self.image_list.shape[3], - ) - - def load(self, cache_path): - self.data_dict = {} - self.data_dict["all"] = torch.from_numpy(np.load(os.path.join(cache_path, "dino.npy"))) - - self.cfg["img_scale"] = ( - self.data_dict["all"].shape[1] / self.image_list.shape[2], - self.data_dict["all"].shape[2] / self.image_list.shape[3], - ) - - def save(self, cache_path): - np.save(os.path.join(cache_path, "dino.npy"), self.data_dict["all"].cpu().numpy()) - - def __call__(self, img_points): - # img_points: (B, 3) # (img_ind, x, y) - x_ind, y_ind = (img_points[:, 1] * self.cfg["img_scale"][0]).long(), ( - img_points[:, 2] * self.cfg["img_scale"][1] - ).long() - return (self.data_dict["all"][img_points[:, 0].long(), x_ind, y_ind]).to(self.device) - - -# @dataclasses.dataclass -# class DinoDataloader(): -# image_lst: torch.Tensor # (N, 3, H, W) -# device: torch.device -# dino_embeds: np.ndarray = None -# dino_embeds_smap: np.ndarray = None -# do_cache: bool = True -# cache_path: str = None -# load_size: int = 500 -# stride: int = 8 -# model_type: str = 'dino_vits8' -# facet: str = 'key' -# layer: typing.Tuple[int] = (11,) -# all_layers: bool = False -# bin: bool = False - -# def __post_init__(self): -# # if cached version exists + want to use cache ver, use it -# if self.all_layers: -# self.layer = list(range(12)) - -# if ( -# self.do_cache and self.cache_path is not None -# and os.path.exists(os.path.join(self.cache_path, f"cache_dino.npy")) -# and os.path.exists(os.path.join(self.cache_path, f"cache_dino_smap.npy")) -# ): -# self.dino_embeds = np.load(os.path.join(self.cache_path, f"cache_dino.npy")) -# self.dino_embeds_smap = np.load(os.path.join(self.cache_path, f"cache_dino_smap.npy")) - -# if len(self.layer) == 1: -# self.dino_embeds = self.dino_embeds[:, :, :, :] -# else: -# self.dino_embeds = self.dino_embeds[:, self.layer, :, :] -# else: -# self.calculate_dino() - -# self.dino_img_scale = ( -# self.dino_embeds.shape[2]/self.image_lst.shape[2], -# self.dino_embeds.shape[3]/self.image_lst.shape[3] -# ) - -# print(self.dino_embeds.shape) -# del self.image_lst - -# def calculate_dino(self): -# self.extractor = ViTExtractor(self.model_type, self.stride, device=self.device) -# self.dino_embeds_smap = [] -# self.dino_embeds = [] - -# preproc_image_lst = self.extractor.preprocess(self.image_lst, self.load_size)[0].to(self.device) -# for image in tqdm(preproc_image_lst, desc='dino', total=len(self.image_lst), leave=False): -# descriptors = self.extractor.extract_descriptors(image.unsqueeze(0), self.layer, self.facet, self.bin) -# descriptors = descriptors.reshape((len(self.layer), self.extractor.num_patches[0], self.extractor.num_patches[1], -1)) -# self.dino_embeds.append(descriptors.cpu().detach().numpy()) - -# saliency_maps = self.extractor.extract_saliency_maps(image.unsqueeze(0)) -# saliency_maps = saliency_maps.reshape((self.extractor.num_patches[0], self.extractor.num_patches[1], -1)) -# self.dino_embeds_smap.append(saliency_maps.cpu().detach().numpy()) - -# self.dino_embeds = np.stack(self.dino_embeds, axis=0) # (# of imgs, # of layers, # of patches, # of patches, descriptor_dim) -# self.dino_embeds_smap = np.stack(self.dino_embeds_smap, axis=0) - -# if self.do_cache and self.cache_path is not None: -# os.makedirs(self.cache_path,exist_ok=True) -# np.save(os.path.join(self.cache_path, f"cache_dino.npy"), self.dino_embeds) -# np.save(os.path.join(self.cache_path, f"cache_dino_smap.npy"), self.dino_embeds_smap) - -# self.cleanup() - -# def cleanup(self): -# del self.extractor -# torch.cuda.empty_cache() - -# def __call__(self, img_points, layer=None): -# # img_points: (B, 3) # (img_ind, x, y) -# # return: (B, descriptor_dim), (B, smap_dim), (B, 1) - -# img_ind = img_points[:, 0] -# x_ind = (img_points[:, 1]*self.dino_img_scale[0]).long() -# y_ind = (img_points[:, 2]*self.dino_img_scale[1]).long() - -# if layer is None: -# layer = np.random.randint(low=0, high=len(self.layer), size=(img_points.shape[0],1)) -# # layer = np.random.choice(self.layer, size=(img_points.shape[0], 1)) - -# saliency = self.dino_embeds_smap[img_ind, x_ind, y_ind] - -# # nearest neighbor interpolation -# return ( -# torch.from_numpy(self.dino_embeds[img_ind, layer.flatten(), x_ind, y_ind]).to(self.device), -# torch.from_numpy(saliency).to(self.device), -# (torch.Tensor(self.layer)[layer]/11).to(self.device), -# ) - -if __name__ == "__main__": - import itertools - import time - - import torchvision - from PIL import Image - - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - img_inputs = [ - Image.open("/home/jkerr/nerfstudio/data/cmk_mug/images/frame_00001.jpg"), - Image.open("/home/jkerr/nerfstudio/data/cmk_mug/images/frame_00007.jpg"), - Image.open("/home/jkerr/nerfstudio/data/cmk_mug/images/frame_00056.jpg"), - ] - dl = DinoDataloader(img_inputs, device) - - img_lst = torch.cat([torchvision.transforms.ToTensor()(img).unsqueeze(0) for img in img_inputs]).to(device) - x = np.arange(0, img_lst.shape[2], 10) - y = np.arange(0, img_lst.shape[3], 10) - img_points = torch.from_numpy(np.stack(list(itertools.product(np.arange(img_lst.shape[0]), x, y)))) - inds, gx_, gy_ = img_points[:, 0].long(), img_points[:, 1].long(), img_points[:, 2].long() - - start = time.time() - dino_embeds = dl(img_points.numpy()) - end = time.time() - print(end - start) diff --git a/nerfstudio/data/utils/dino_extractor.py b/nerfstudio/data/utils/dino_extractor.py deleted file mode 100644 index 8b5a9cc03..000000000 --- a/nerfstudio/data/utils/dino_extractor.py +++ /dev/null @@ -1,363 +0,0 @@ -# taken from https://github.com/ShirAmir/dino-vit-features - -import argparse -import torch -import torchvision.transforms -from torch import nn -from torchvision import transforms -import torch.nn.modules.utils as nn_utils -import math -import timm -import types -from pathlib import Path -from typing import Union, List, Tuple -from PIL import Image - - -class ViTExtractor: - """ This class facilitates extraction of features, descriptors, and saliency maps from a ViT. - - We use the following notation in the documentation of the module's methods: - B - batch size - h - number of heads. usually takes place of the channel dimension in pytorch's convention BxCxHxW - p - patch size of the ViT. either 8 or 16. - t - number of tokens. equals the number of patches + 1, e.g. HW / p**2 + 1. Where H and W are the height and width - of the input image. - d - the embedding dimension in the ViT. - """ - - def __init__(self, model_type: str = 'dino_vits8', stride: int = 4, model: nn.Module = None, device: str = 'cuda'): - """ - :param model_type: A string specifying the type of model to extract from. - [dino_vits8 | dino_vits16 | dino_vitb8 | dino_vitb16 | vit_small_patch8_224 | - vit_small_patch16_224 | vit_base_patch8_224 | vit_base_patch16_224] - :param stride: stride of first convolution layer. small stride -> higher resolution. - :param model: Optional parameter. The nn.Module to extract from instead of creating a new one in ViTExtractor. - should be compatible with model_type. - """ - self.model_type = model_type - self.device = device - if model is not None: - self.model = model - else: - self.model = ViTExtractor.create_model(model_type) - - self.model = ViTExtractor.patch_vit_resolution(self.model, stride=stride) - self.model.eval() - self.model.to(self.device) - self.p = self.model.patch_embed.patch_size - self.stride = self.model.patch_embed.proj.stride - - self.mean = (0.485, 0.456, 0.406) if "dino" in self.model_type else (0.5, 0.5, 0.5) - self.std = (0.229, 0.224, 0.225) if "dino" in self.model_type else (0.5, 0.5, 0.5) - - self._feats = [] - self.hook_handlers = [] - self.load_size = None - self.num_patches = None - - @staticmethod - def create_model(model_type: str) -> nn.Module: - """ - :param model_type: a string specifying which model to load. [dino_vits8 | dino_vits16 | dino_vitb8 | - dino_vitb16 | vit_small_patch8_224 | vit_small_patch16_224 | vit_base_patch8_224 | - vit_base_patch16_224] - :return: the model - """ - if 'dino' in model_type: - model = torch.hub.load('facebookresearch/dino:main', model_type) - else: # model from timm -- load weights from timm to dino model (enables working on arbitrary size images). - temp_model = timm.create_model(model_type, pretrained=True) - model_type_dict = { - 'vit_small_patch16_224': 'dino_vits16', - 'vit_small_patch8_224': 'dino_vits8', - 'vit_base_patch16_224': 'dino_vitb16', - 'vit_base_patch8_224': 'dino_vitb8' - } - model = torch.hub.load('facebookresearch/dino:main', model_type_dict[model_type]) - temp_state_dict = temp_model.state_dict() - del temp_state_dict['head.weight'] - del temp_state_dict['head.bias'] - model.load_state_dict(temp_state_dict) - return model - - @staticmethod - def _fix_pos_enc(patch_size: int, stride_hw: Tuple[int, int]): - """ - Creates a method for position encoding interpolation. - :param patch_size: patch size of the model. - :param stride_hw: A tuple containing the new height and width stride respectively. - :return: the interpolation method - """ - def interpolate_pos_encoding(self, x: torch.Tensor, w: int, h: int) -> torch.Tensor: - npatch = x.shape[1] - 1 - N = self.pos_embed.shape[1] - 1 - if npatch == N and w == h: - return self.pos_embed - class_pos_embed = self.pos_embed[:, 0] - patch_pos_embed = self.pos_embed[:, 1:] - dim = x.shape[-1] - # compute number of tokens taking stride into account - w0 = 1 + (w - patch_size) // stride_hw[1] - h0 = 1 + (h - patch_size) // stride_hw[0] - assert (w0 * h0 == npatch), f"""got wrong grid size for {h}x{w} with patch_size {patch_size} and - stride {stride_hw} got {h0}x{w0}={h0 * w0} expecting {npatch}""" - # we add a small number to avoid floating point error in the interpolation - # see discussion at https://github.com/facebookresearch/dino/issues/8 - w0, h0 = w0 + 0.1, h0 + 0.1 - patch_pos_embed = nn.functional.interpolate( - patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), - scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), - mode='bicubic', - align_corners=False, recompute_scale_factor=False - ) - assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1] - patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) - return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) - - return interpolate_pos_encoding - - @staticmethod - def patch_vit_resolution(model: nn.Module, stride: int) -> nn.Module: - """ - change resolution of model output by changing the stride of the patch extraction. - :param model: the model to change resolution for. - :param stride: the new stride parameter. - :return: the adjusted model - """ - patch_size = model.patch_embed.patch_size - if stride == patch_size: # nothing to do - return model - - stride = nn_utils._pair(stride) - assert all([(patch_size // s_) * s_ == patch_size for s_ in - stride]), f'stride {stride} should divide patch_size {patch_size}' - - # fix the stride - model.patch_embed.proj.stride = stride - # fix the positional encoding code - model.interpolate_pos_encoding = types.MethodType(ViTExtractor._fix_pos_enc(patch_size, stride), model) - return model - - def preprocess(self, image: torch.Tensor, - load_size: Union[int, Tuple[int, int]] = None) -> Tuple[torch.Tensor, Image.Image]: - """ - Preprocesses an image before extraction. - :param image_path: path to image to be extracted. - :param load_size: optional. Size to resize image before the rest of preprocessing. - :return: a tuple containing: - (1) the preprocessed image as a tensor to insert the model of shape BxCxHxW. - (2) the pil image in relevant dimensions - """ - # pil_image = image.convert('RGB') - # if load_size is not None: - # pil_image = transforms.Resize(load_size, interpolation=transforms.InterpolationMode.LANCZOS)(pil_image) - prep = transforms.Compose([ - # transforms.ToTensor(), - transforms.Resize(load_size), - transforms.Normalize(mean=self.mean, std=self.std) - ]) - prep_img = prep(image)[None, ...] - return prep_img - - def _get_hook(self, facet: str): - """ - generate a hook method for a specific block and facet. - """ - if facet in ['attn', 'token']: - def _hook(model, input, output): - self._feats.append(output) - return _hook - - if facet == 'query': - facet_idx = 0 - elif facet == 'key': - facet_idx = 1 - elif facet == 'value': - facet_idx = 2 - else: - raise TypeError(f"{facet} is not a supported facet.") - - def _inner_hook(module, input, output): - input = input[0] - B, N, C = input.shape - qkv = module.qkv(input).reshape(B, N, 3, module.num_heads, C // module.num_heads).permute(2, 0, 3, 1, 4) - self._feats.append(qkv[facet_idx]) #Bxhxtxd - return _inner_hook - - def _register_hooks(self, layers: List[int], facet: str) -> None: - """ - register hook to extract features. - :param layers: layers from which to extract features. - :param facet: facet to extract. One of the following options: ['key' | 'query' | 'value' | 'token' | 'attn'] - """ - for block_idx, block in enumerate(self.model.blocks): - if block_idx in layers: - if facet == 'token': - self.hook_handlers.append(block.register_forward_hook(self._get_hook(facet))) - elif facet == 'attn': - self.hook_handlers.append(block.attn.attn_drop.register_forward_hook(self._get_hook(facet))) - elif facet in ['key', 'query', 'value']: - self.hook_handlers.append(block.attn.register_forward_hook(self._get_hook(facet))) - else: - raise TypeError(f"{facet} is not a supported facet.") - - def _unregister_hooks(self) -> None: - """ - unregisters the hooks. should be called after feature extraction. - """ - for handle in self.hook_handlers: - handle.remove() - self.hook_handlers = [] - - def _extract_features(self, batch: torch.Tensor, layers: List[int] = 11, facet: str = 'key') -> List[torch.Tensor]: - """ - extract features from the model - :param batch: batch to extract features for. Has shape BxCxHxW. - :param layers: layer to extract. A number between 0 to 11. - :param facet: facet to extract. One of the following options: ['key' | 'query' | 'value' | 'token' | 'attn'] - :return : tensor of features. - if facet is 'key' | 'query' | 'value' has shape Bxhxtxd - if facet is 'attn' has shape Bxhxtxt - if facet is 'token' has shape Bxtxd - """ - B, C, H, W = batch.shape - self._feats = [] - self._register_hooks(layers, facet) - _ = self.model(batch) - self._unregister_hooks() - self.load_size = (H, W) - self.num_patches = (1 + (H - self.p) // self.stride[0], 1 + (W - self.p) // self.stride[1]) - return self._feats - - def _log_bin(self, x: torch.Tensor, hierarchy: int = 2) -> torch.Tensor: - """ - create a log-binned descriptor. - :param x: tensor of features. Has shape Bxhxtxd. - :param hierarchy: how many bin hierarchies to use. - """ - B = x.shape[0] - num_bins = 1 + 8 * hierarchy - - bin_x = x.permute(0, 2, 3, 1).flatten(start_dim=-2, end_dim=-1) # Bx(t-1)x(dxh) - bin_x = bin_x.permute(0, 2, 1) - bin_x = bin_x.reshape(B, bin_x.shape[1], self.num_patches[0], self.num_patches[1]) - # Bx(dxh)xnum_patches[0]xnum_patches[1] - sub_desc_dim = bin_x.shape[1] - - avg_pools = [] - # compute bins of all sizes for all spatial locations. - for k in range(0, hierarchy): - # avg pooling with kernel 3**kx3**k - win_size = 3 ** k - avg_pool = torch.nn.AvgPool2d(win_size, stride=1, padding=win_size // 2, count_include_pad=False) - avg_pools.append(avg_pool(bin_x)) - - bin_x = torch.zeros((B, sub_desc_dim * num_bins, self.num_patches[0], self.num_patches[1])).to(self.device) - for y in range(self.num_patches[0]): - for x in range(self.num_patches[1]): - part_idx = 0 - # fill all bins for a spatial location (y, x) - for k in range(0, hierarchy): - kernel_size = 3 ** k - for i in range(y - kernel_size, y + kernel_size + 1, kernel_size): - for j in range(x - kernel_size, x + kernel_size + 1, kernel_size): - if i == y and j == x and k != 0: - continue - if 0 <= i < self.num_patches[0] and 0 <= j < self.num_patches[1]: - bin_x[:, part_idx * sub_desc_dim: (part_idx + 1) * sub_desc_dim, y, x] = avg_pools[k][ - :, :, i, j] - else: # handle padding in a more delicate way than zero padding - temp_i = max(0, min(i, self.num_patches[0] - 1)) - temp_j = max(0, min(j, self.num_patches[1] - 1)) - bin_x[:, part_idx * sub_desc_dim: (part_idx + 1) * sub_desc_dim, y, x] = avg_pools[k][ - :, :, temp_i, - temp_j] - part_idx += 1 - bin_x = bin_x.flatten(start_dim=-2, end_dim=-1).permute(0, 2, 1).unsqueeze(dim=1) - # Bx1x(t-1)x(dxh) - return bin_x - - def extract_descriptors(self, batch: torch.Tensor, layer: List[int], facet: str = 'key', - bin: bool = False, include_cls: bool = False) -> torch.Tensor: - """ - extract descriptors from the model - :param batch: batch to extract descriptors for. Has shape BxCxHxW. - :param layers: layer to extract. A number between 0 to 11. - :param facet: facet to extract. One of the following options: ['key' | 'query' | 'value' | 'token'] - :param bin: apply log binning to the descriptor. default is False. - :return: tensor of descriptors. Bx1xtxd' where d' is the dimension of the descriptors. - """ - assert facet in ['key', 'query', 'value', 'token'], f"""{facet} is not a supported facet for descriptors. - choose from ['key' | 'query' | 'value' | 'token'] """ - self._extract_features(batch, layer, facet) - x = torch.concat(self._feats) - # if facet == 'token': - # x.unsqueeze_(dim=1) #Bx1xtxd - if not include_cls: - x = x[:, :, 1:, :] # remove cls token - else: - assert not bin, "bin = True and include_cls = True are not supported together, set one of them False." - if not bin: - desc = x.permute(0, 2, 3, 1).flatten(start_dim=-2, end_dim=-1).unsqueeze(dim=1) # Bx1xtx(dxh) - else: - desc = self._log_bin(x) - return desc - - def extract_saliency_maps(self, batch: torch.Tensor) -> torch.Tensor: - """ - extract saliency maps. The saliency maps are extracted by averaging several attention heads from the last layer - in of the CLS token. All values are then normalized to range between 0 and 1. - :param batch: batch to extract saliency maps for. Has shape BxCxHxW. - :return: a tensor of saliency maps. has shape Bxt-1 - """ - assert self.model_type == "dino_vits8", f"saliency maps are supported only for dino_vits model_type." - self._extract_features(batch, [11], 'attn') - head_idxs = [0, 2, 4, 5] - curr_feats = self._feats[0] #Bxhxtxt - cls_attn_map = curr_feats[:, head_idxs, 0, 1:].mean(dim=1) #Bx(t-1) - temp_mins, temp_maxs = cls_attn_map.min(dim=1)[0], cls_attn_map.max(dim=1)[0] - cls_attn_maps = (cls_attn_map - temp_mins) / (temp_maxs - temp_mins) # normalize to range [0,1] - return cls_attn_maps - -""" taken from https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse""" -def str2bool(v): - if isinstance(v, bool): - return v - if v.lower() in ('yes', 'true', 't', 'y', '1'): - return True - elif v.lower() in ('no', 'false', 'f', 'n', '0'): - return False - else: - raise argparse.ArgumentTypeError('Boolean value expected.') - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Facilitate ViT Descriptor extraction.') - parser.add_argument('--image_path', type=str, required=True, help='path of the extracted image.') - parser.add_argument('--output_path', type=str, required=True, help='path to file containing extracted descriptors.') - parser.add_argument('--load_size', default=224, type=int, help='load size of the input image.') - parser.add_argument('--stride', default=4, type=int, help="""stride of first convolution layer. - small stride -> higher resolution.""") - parser.add_argument('--model_type', default='dino_vits8', type=str, - help="""type of model to extract. - Choose from [dino_vits8 | dino_vits16 | dino_vitb8 | dino_vitb16 | vit_small_patch8_224 | - vit_small_patch16_224 | vit_base_patch8_224 | vit_base_patch16_224]""") - parser.add_argument('--facet', default='key', type=str, help="""facet to create descriptors from. - options: ['key' | 'query' | 'value' | 'token']""") - parser.add_argument('--layer', default=11, type=int, help="layer to create descriptors from.") - parser.add_argument('--bin', default='False', type=str2bool, help="create a binned descriptor if True.") - - args = parser.parse_args() - - with torch.no_grad(): - device = 'cuda' if torch.cuda.is_available() else 'cpu' - extractor = ViTExtractor(args.model_type, args.stride, device=device) - image_batch, image_pil = extractor.preprocess(args.image_path, args.load_size) - print(f"Image {args.image_path} is preprocessed to tensor of size {image_batch.shape}.") - descriptors = extractor.extract_descriptors(image_batch.to(device), args.layer, args.facet, args.bin) - print(f"Descriptors are of size: {descriptors.shape}") - torch.save(descriptors, args.output_path) - print(f"Descriptors saved to: {args.output_path}") - - import pdb; pdb.set_trace() - print() diff --git a/nerfstudio/data/utils/feature_dataloader.py b/nerfstudio/data/utils/feature_dataloader.py deleted file mode 100644 index d000ae89e..000000000 --- a/nerfstudio/data/utils/feature_dataloader.py +++ /dev/null @@ -1,41 +0,0 @@ -import dataclasses -import os -import typing -from abc import ABC, ABCMeta, abstractmethod -from pathlib import Path - -import torch - - -@dataclasses.dataclass -class FeatureDataloader(ABC): - image_list: torch.Tensor # (N, 3, H, W) - device: torch.device - cfg: dict - cache_dir: Path - data_dict: typing.Dict[int, torch.Tensor] = None # N-length dict of (multi-channel, H_d, W_d) - - @abstractmethod - def __call__(self, img_points): - # img_points: (B, 3) # (img_ind, x, y) - pass - - @abstractmethod - def create(self): - pass - - @abstractmethod - def load(self, cache_path): - pass - - @abstractmethod - def save(self, cache_path): - pass - - def try_load(self, cache_path: Path): - cache_path.mkdir(parents=True, exist_ok=True) - try: - self.load(cache_path) - except FileNotFoundError: - self.create() - self.save(cache_path) diff --git a/nerfstudio/data/utils/patched_dataloader.py b/nerfstudio/data/utils/patched_dataloader.py deleted file mode 100644 index 106579109..000000000 --- a/nerfstudio/data/utils/patched_dataloader.py +++ /dev/null @@ -1,149 +0,0 @@ -import dataclasses -import os -from dataclasses import field - -import clip -import numpy as np -import torch -from tqdm import tqdm - -from nerfstudio.data.utils.feature_dataloader import FeatureDataloader -from nerfstudio.data.utils.pyramid_interpolator import PyramidInterpolator -from nerfstudio.pipelines.lerf_encoders import ImageEncoder - - -@dataclasses.dataclass -class PatchedDataloader(FeatureDataloader): - model: ImageEncoder = None - - def __post_init__(self): - assert "tile_size_range" in self.cfg - assert "tile_size_res" in self.cfg - assert "stride_scaler" in self.cfg - - self.cfg["tile_sizes"] = torch.linspace(*self.cfg["tile_size_range"], self.cfg["tile_size_res"]).to(self.device) - self.try_load(self.cache_dir) - self.embed_size = self.model.embedding_dim - - def __call__(self, img_points, scale=None): - if scale is None: - return self._random_scales(img_points) - else: - return self._uniform_scales(img_points, scale) - - def create(self): - self.data_dict = {} - for i, tr in enumerate(tqdm(self.cfg["tile_sizes"], desc="scale", leave=False)): - stride_scaler = np.interp(tr.item(), [0.05, 0.15], [0.6, self.cfg["stride_scaler"]]) - self.data_dict[i] = PyramidInterpolator( - image_list=self.image_list, - device=self.device, - model=self.model, - tile_ratio=tr, - stride_ratio=tr * stride_scaler, - ) - for level in self.data_dict: - self.data_dict[level].image_list = None - self.data_dict[level].img_embeds_np = None - - # def sample_pixels(self, N_patch: int, N_samp: int, interp=True): - # remnant code for deblur LERF (could be interesting still) - # """ - # returns {'indices':(N_patch*N_samp, 3), 'image',(N_patch*N_samp, 3), - # 'clip': (N_patch, 512)}, clip_scale:((N_patch*N_samp, 1)) - # """ - # # 1. sample patch_ids: N_patch samples into the whole dataset. (N_patch,4) 4 == (im_id,x_ind,y_ind,scale) - # im_ids = torch.randint(self.image_list.shape[0], (N_patch, 1)) - # col_ind = torch.randint(self.image_list.shape[3], (N_patch, 1)) - # row_ind = torch.randint(self.image_list.shape[2], (N_patch, 1)) - # scale_ind = torch.randint(len(self.data_dict), (N_patch, 1)) - # patch_ids = torch.concat([im_ids, row_ind, col_ind, scale_ind], dim=-1).to(self.device) - # # 3. use the interpolators to upsample each patch sample into (N_patch*N_samp,4) - # # 4 == (im_id,x_ind,y_ind,scale), and (N_patch,512) - # # this is batch['indices'] (after removing scale) and batch['clip'] - # upsampled_ids, clips, scales = [], [], [] - # for i in self.data_dict: - # relevant_ids = patch_ids[patch_ids[:, 3] == i, :3] - # if interp: - # res = self.data_dict[i].upsample_interp(relevant_ids, N_samp) - # else: - # res = self.data_dict[i].upsample(relevant_ids, N_samp) - # if res is None: - # continue - # u, c = res - # s = ( - # torch.rand((u.shape[0], 1), device=u.device, dtype=torch.float32) * 0.1 - # + self.cfg["tile_sizes"][i] / 2 - # - 0.05 - # ) - # upsampled_ids.append(u) - # clips.append(c) - # scales.append(s) - # upsampled_ids, clips, scales = ( - # torch.concat(upsampled_ids, dim=0), - # torch.concat(clips, dim=0), - # torch.concat(scales, dim=0), - # ) - # # 4. index into the images to get the color values (this is batch['image']) - # image = self.image_list[upsampled_ids[:, 0], :, upsampled_ids[:, 1], upsampled_ids[:, 2]] - # # 5. clip_scale is the 4th dim of step 3 - # return {"image": image, "clip": clips, "indices": upsampled_ids.cpu()}, scales - - def load(self, cache_path): - assert os.path.exists(cache_path) - self.data_dict = {} - for i, tr in enumerate(tqdm(self.cfg["tile_sizes"], desc="scale", leave=False)): - clip_embeds = np.load(os.path.join(cache_path, f"cache{i}.npy")) - stride_scaler = np.interp(tr.item(), [0.05, 0.15], [0.6, self.cfg["stride_scaler"]]) - self.data_dict[i] = PyramidInterpolator( - image_list=self.image_list, - device=self.device, - img_embeds_np=clip_embeds, - tile_ratio=tr, - stride_ratio=tr * stride_scaler, - ) - self.data_dict[i].image_list = None - self.data_dict[i].img_embeds_np = None - - def save(self, cache_path): - os.makedirs(cache_path, exist_ok=True) - for i, interp in self.data_dict.items(): - np.save(os.path.join(cache_path, f"cache{i}.npy"), interp.img_embeds.detach().cpu().numpy()) - - def _random_scales(self, img_points): - # img_points: (B, 3) # (img_ind, x, y) - # return: (B, 512), some random scale (between 0, 1) - tile_sizes = self.cfg["tile_sizes"] - - random_scale_bin = torch.randint(tile_sizes.shape[0] - 1, size=(img_points.shape[0],), device=self.device) - random_scale_weight = torch.rand(img_points.shape[0], dtype=torch.float16, device=self.device) - - stepsize = (tile_sizes[1] - tile_sizes[0]) / (tile_sizes[-1] - tile_sizes[0]) - - bottom_interp = torch.zeros((img_points.shape[0], self.embed_size), dtype=torch.float16, device=self.device) - top_interp = torch.zeros((img_points.shape[0], self.embed_size), dtype=torch.float16, device=self.device) - - for i in range(len(tile_sizes) - 1): - bottom_interp[random_scale_bin == i] = self.data_dict[i](img_points[random_scale_bin == i]) - top_interp[random_scale_bin == i] = self.data_dict[i + 1](img_points[random_scale_bin == i]) - - return ( - torch.lerp(bottom_interp, top_interp, random_scale_weight[..., None]), - (random_scale_bin * stepsize + random_scale_weight * stepsize)[..., None], - ) - - def _uniform_scales(self, img_points, scale): - tile_sizes = self.cfg["tile_sizes"] - - scale_bin = torch.floor( - (scale - tile_sizes[0]) / (tile_sizes[-1] - tile_sizes[0]) * (tile_sizes.shape[0] - 1) - ).to(torch.int64) - scale_weight = (scale - tile_sizes[scale_bin]) / (tile_sizes[scale_bin + 1] - tile_sizes[scale_bin]) - interp_lst = torch.stack([interp(img_points) for interp in self.data_dict.values()]) - point_inds = torch.arange(img_points.shape[0]) - interp = torch.lerp( - interp_lst[scale_bin, point_inds], - interp_lst[scale_bin + 1, point_inds], - torch.Tensor([scale_weight]).half().to(self.device)[..., None], - ) - return interp / interp.norm(dim=-1, keepdim=True), scale diff --git a/nerfstudio/data/utils/pyramid_interpolator.py b/nerfstudio/data/utils/pyramid_interpolator.py deleted file mode 100644 index 88ae2bb57..000000000 --- a/nerfstudio/data/utils/pyramid_interpolator.py +++ /dev/null @@ -1,145 +0,0 @@ -import dataclasses - -import numpy as np -import torch -from tqdm import tqdm - -from nerfstudio.pipelines.lerf_encoders import ImageEncoder - - -@dataclasses.dataclass -class PyramidInterpolator: - image_list: torch.Tensor # (N, 3, H, W) - device: torch.device - img_embeds: str = None # path to np array, (N, center_x, center_y, 512) - img_embeds_np: np.ndarray = None - cache_path: str = None - tile_ratio: float = 0.2 - stride_ratio: float = 0.05 - model: ImageEncoder = None - - def __post_init__(self): - # initialize self.center_x, self.center_y, self.unfold_func - self.image_list = self.image_list.to(self.device) - self.imlist_shape = self.image_list.shape - self._setup_tile_images() - - # initialize self.img_embeds - if self.img_embeds_np is not None: - self.img_embeds = self.img_embeds_np - elif self.img_embeds is not None: - self.img_embeds = np.load(self.img_embeds) - else: - assert self.model is not None - - self.embed_size = self.model.embedding_dim - - self.img_embeds = [] - for img in tqdm(self.image_list, desc="Embedding images", leave=False): - self.img_embeds.append(self._embed_clip_tiles(img.unsqueeze(0))) - self.img_embeds = np.stack(self.img_embeds) - - if self.cache_path is not None: - np.save(self.cache_path, self.img_embeds) - - self._post_setup_cleanup() - self.img_embeds = torch.from_numpy(self.img_embeds).half() - - def __call__(self, img_points, mode="interp"): - # img_points: (B, 3) # (img_ind, x, y) (img_ind, row, col) - # return: (B, 512) - img_points = img_points.to(self.device) - img_ind, img_points_x, img_points_y = img_points[:, 0], img_points[:, 1], img_points[:, 2] - - x_ind = torch.searchsorted(self.center_x, img_points_x, side="left") - 1 - y_ind = torch.searchsorted(self.center_y, img_points_y, side="left") - 1 - return self.interp_inds(img_ind, x_ind, y_ind, img_points_x, img_points_y) - - def interp_inds(self, img_ind, x_ind, y_ind, img_points_x, img_points_y): - topleft = self.img_embeds[img_ind, x_ind, y_ind].to(self.device) - topright = self.img_embeds[img_ind, x_ind + 1, y_ind].to(self.device) - botleft = self.img_embeds[img_ind, x_ind, y_ind + 1].to(self.device) - botright = self.img_embeds[img_ind, x_ind + 1, y_ind + 1].to(self.device) - - x_stride = self.stride - y_stride = self.stride - right_w = ((img_points_x - (self.center_x[x_ind])) / x_stride).half() - top = torch.lerp(topleft, topright, right_w[:, None]) - bot = torch.lerp(botleft, botright, right_w[:, None]) - - bot_w = ((img_points_y - (self.center_y[y_ind])) / y_stride).half() - return torch.lerp(top, bot, bot_w[:, None]) - - # def upsample_interp(self, input_ids, N_samp): - # B = input_ids.shape[0] - # if B == 0: - # return None - # img_ind, img_points_x, img_points_y = input_ids[:, 0], input_ids[:, 1], input_ids[:, 2] - - # x_ind = torch.searchsorted(self.center_x, img_points_x, side="left") - 1 - # y_ind = torch.searchsorted(self.center_y, img_points_y, side="left") - 1 - # gt_embeds = self.interp_inds(img_ind, x_ind, y_ind, img_points_x, img_points_y) - - # blur_size = 0.5 * self.kernel_size - - # x_start = img_points_x - blur_size / 2 # (N_patch, 1) - # x_start = x_start[:, None].repeat_interleave(N_samp, 0) # (N_patcH*N_samp,1) - # y_start = img_points_y - blur_size / 2 - # y_start = y_start[:, None].repeat_interleave(N_samp, 0) - - # new_xs = torch.rand((N_samp * B, 1), device=self.device) * blur_size + x_start - # new_ys = torch.rand((N_samp * B, 1), device=self.device) * blur_size + y_start - # new_xs = torch.clip(new_xs, 0, self.imlist_shape[2] - 1) - # new_ys = torch.clip(new_ys, 0, self.imlist_shape[3] - 1) - # new_imids = img_ind[:, None].repeat_interleave(N_samp, 0) - # return torch.concat((new_imids, new_xs.long(), new_ys.long()), dim=1), gt_embeds.to(self.device) - - def _post_setup_cleanup(self): - del self.unfold_func - torch.cuda.empty_cache() - - def _setup_tile_images(self): - # compute image crops, using torch's Unfold - self.kernel_size = int(self.image_list.shape[2] * self.tile_ratio) - self.stride = int(self.image_list.shape[2] * self.stride_ratio) - self.padding = self.kernel_size // 2 - - self.unfold_func = torch.nn.Unfold( - kernel_size=self.kernel_size, - stride=self.stride, - padding=self.padding, - ).to(self.device) - - self.center_x = ( - (self.kernel_size - 1) / 2 - - self.padding - + self.stride - * np.arange( - np.floor((self.image_list.shape[2] + 2 * self.padding - (self.kernel_size - 1) - 1) / self.stride + 1) - ) - ) - self.center_y = ( - (self.kernel_size - 1) / 2 - - self.padding - + self.stride - * np.arange( - np.floor((self.image_list.shape[3] + 2 * self.padding - (self.kernel_size - 1) - 1) / self.stride + 1) - ) - ) - self.center_x = torch.from_numpy(self.center_x).to(self.device) - self.center_y = torch.from_numpy(self.center_y).to(self.device) - - def _embed_clip_tiles(self, image): - # image augmentation: slow-ish (0.02s for 600x800 image per augmentation) - aug_imgs = torch.cat([image]) - - tiles = self.unfold_func(aug_imgs).permute(2, 0, 1).reshape(-1, 3, self.kernel_size, self.kernel_size) - - with torch.no_grad(): - clip_embeds = self.model.encode_image(tiles) - clip_embeds /= clip_embeds.norm(dim=-1, keepdim=True) - - clip_embeds = clip_embeds.reshape((self.center_x.shape[0], self.center_y.shape[0], -1)) - clip_embeds = torch.concat((clip_embeds, clip_embeds[:, [-1], :]), dim=1) - clip_embeds = torch.concat((clip_embeds, clip_embeds[[-1], :, :]), dim=0) - return clip_embeds.detach().cpu().numpy() diff --git a/nerfstudio/fields/visibility_field.py b/nerfstudio/fields/visibility_field.py deleted file mode 100644 index 5cd44cf41..000000000 --- a/nerfstudio/fields/visibility_field.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright 2022 The Plenoptix Team. All rights reserved. -# -# 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. - -"""Visibility Field""" - - -from typing import Optional - -import torch -from torch import nn -from torch.nn.parameter import Parameter -from torchtyping import TensorType - -from nerfstudio.cameras.cameras import Cameras -from nerfstudio.cameras.rays import RaySamples -from nerfstudio.data.scene_box import SceneBox -from nerfstudio.field_components.encodings import Encoding, Identity, SHEncoding -from nerfstudio.field_components.field_heads import FieldHeadNames, RGBFieldHead -from nerfstudio.field_components.mlp import MLP -from nerfstudio.fields.base_field import Field - - -class VisibilityField(Field): - """Visibility Field""" - - def __init__(self, cameras: Cameras) -> None: - super().__init__() - # training camera tranforms - # TODO: use optimized cameras - self.c2ws = cameras.camera_to_worlds - self.c2whs = torch.cat([self.c2ws, torch.zeros_like(self.c2ws[:, :1, :])], dim=1) - self.c2whs[:, 3, 3] = 1.0 - self.w2chs = torch.inverse(self.c2whs) - self.K = cameras.get_intrinsics_matrices().to("cuda") - self.image_height = cameras.height - self.image_width = cameras.width - - @torch.no_grad() - def forward(self, ray_samples: RaySamples, camera_chunk_size=50, ray_chunk_size=4096): - """ - Args: - ray_samples: Ray samples. - camera_chunk_size: Number of cameras to process at once to avoid memory issues. - ray_chunk_size: Number of rays to process at once to avoid memory issues. - Returns: - """ - # get positions - positions = ray_samples.frustums.get_positions() # [N, S, 3] - # project positions into each camera - # move to homogeneous coordinates - positions = torch.cat([positions, torch.ones_like(positions[..., :1])], dim=-1) - N, S, _ = positions.shape - B = self.w2chs.shape[0] # num cameras - p = positions.view(N * S, 4).transpose(0, 1).unsqueeze(0) # [1, 4, N*S] - p = p.expand(B, *p.shape[1:]) # [B, 4, N*S] - - num_views = torch.zeros([N, S, 1], device=positions.device) - for i in range(0, B, camera_chunk_size): - CCS = min(camera_chunk_size, B - i) - for j in range(0, N, ray_chunk_size): - RCS = min(ray_chunk_size, N - j) - - ptemp = p.reshape(B, 4, N, S)[i : i + CCS, :, j : j + RCS, :].reshape(CCS, 4, RCS * S) - cam_coords = torch.bmm(self.w2chs[i : i + CCS, :], ptemp) - - # flip y and z axes - cam_coords[:, 1, :] *= -1 - cam_coords[:, 2, :] *= -1 - - z = cam_coords[:, 2:3, :].transpose(1, 2).view(CCS, RCS, S, 1) # [CS, RCS, S, 1] - mask_z = z[..., 0] > 0 - - # divide by z - cam_coords = cam_coords[:, :3, :] / cam_coords[:, 2:3, :] - - cam_points = torch.bmm(self.K[i : i + CCS], cam_coords) - - pixel_coords = cam_points[:, :2, :].transpose(1, 2).view(CCS, RCS, S, 2) # [CS, RCS, S, 2] - x = pixel_coords[..., 0] - y = pixel_coords[..., 1] - mask_x = (x >= 0) & (x < self.image_width.view(B, 1, 1)[i : i + CCS]) - mask_y = (y >= 0) & (y < self.image_height.view(B, 1, 1)[i : i + CCS]) - mask = mask_x & mask_y & mask_z - # sum over the batch dimension - nv = mask.sum(dim=0).unsqueeze(-1) - # nv is [N, S, 1] # this is the number of camera frustums that the point belongs to - # for this particular chunk of cameras - num_views[j : j + RCS] += nv - return num_views diff --git a/nerfstudio/models/lerf.py b/projects-lerf/lerf/lerf.py similarity index 98% rename from nerfstudio/models/lerf.py rename to projects-lerf/lerf/lerf.py index a18d56271..f9d82d77d 100644 --- a/nerfstudio/models/lerf.py +++ b/projects-lerf/lerf/lerf.py @@ -11,7 +11,6 @@ from nerfstudio.cameras.rays import RayBundle, RaySamples from nerfstudio.data.scene_box import SceneBox from nerfstudio.field_components.field_heads import FieldHeadNames from nerfstudio.field_components.spatial_distortions import SceneContraction -from nerfstudio.fields.lerf_field import LERFField from nerfstudio.model_components.ray_samplers import PDFSampler from nerfstudio.model_components.renderers import ( CLIPRenderer, @@ -19,7 +18,8 @@ from nerfstudio.model_components.renderers import ( MeanRenderer, ) from nerfstudio.models.nerfacto import NerfactoModel, NerfactoModelConfig -from nerfstudio.pipelines.lerf_encoders import ImageEncoder +from lerf.lerf_encoders import ImageEncoder +from lerf.lerf_field import LERFField @dataclass diff --git a/projects-lerf/lerf/lerf_config.py b/projects-lerf/lerf/lerf_config.py new file mode 100644 index 000000000..f8f3c4914 --- /dev/null +++ b/projects-lerf/lerf/lerf_config.py @@ -0,0 +1,59 @@ +""" +LERF configuration file. +""" + +from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig +from nerfstudio.configs.base_config import ViewerConfig +from nerfstudio.data.dataparsers.nerfstudio_dataparser import NerfstudioDataParserConfig +from nerfstudio.engine.optimizers import AdamOptimizerConfig, RAdamOptimizerConfig +from nerfstudio.engine.schedulers import ExponentialDecaySchedulerConfig +from nerfstudio.engine.trainer import TrainerConfig +from nerfstudio.plugins.types import MethodSpecification + +from lerf.data.lerf_datamanager import LERFDataManagerConfig +from lerf.lerf import LERFModelConfig +from lerf.lerf_pipeline import LERFPipelineConfig +from lerf.lerf_encoders import OpenCLIPNetworkConfig + +lerf_method = MethodSpecification( + config=TrainerConfig( + method_name="lerf", + steps_per_eval_batch=500, + steps_per_save=2000, + max_num_iterations=30000, + mixed_precision=True, + pipeline=LERFPipelineConfig( + datamanager=LERFDataManagerConfig( + dataparser=NerfstudioDataParserConfig(train_split_fraction=0.99), + train_num_rays_per_batch=4096, + eval_num_rays_per_batch=4096, + camera_optimizer=CameraOptimizerConfig( + mode="SO3xR3", optimizer=AdamOptimizerConfig(lr=6e-4, eps=1e-8, weight_decay=1e-2) + ), + ), + model=LERFModelConfig(eval_num_rays_per_chunk=1 << 16), + network=OpenCLIPNetworkConfig( + clip_model_type = "ViT-B-16", + clip_model_pretrained = "laion2b_s34b_b88k", + clip_n_dims= 512 + ) + ), + optimizers={ + "proposal_networks": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + "fields": { + "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-3, max_steps=30000), + }, + "lerf": { + "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-3, max_steps=7000), + }, + }, + viewer=ViewerConfig(num_rays_per_chunk=1 << 15), + vis="viewer", + ), + description="TODO" +) \ No newline at end of file diff --git a/nerfstudio/pipelines/lerf_encoders.py b/projects-lerf/lerf/lerf_encoders.py similarity index 100% rename from nerfstudio/pipelines/lerf_encoders.py rename to projects-lerf/lerf/lerf_encoders.py diff --git a/nerfstudio/fields/lerf_field.py b/projects-lerf/lerf/lerf_field.py similarity index 100% rename from nerfstudio/fields/lerf_field.py rename to projects-lerf/lerf/lerf_field.py diff --git a/nerfstudio/pipelines/lerf_pipeline.py b/projects-lerf/lerf/lerf_pipeline.py similarity index 78% rename from nerfstudio/pipelines/lerf_pipeline.py rename to projects-lerf/lerf/lerf_pipeline.py index 05f674e46..8ab166536 100644 --- a/nerfstudio/pipelines/lerf_pipeline.py +++ b/projects-lerf/lerf/lerf_pipeline.py @@ -1,41 +1,23 @@ import typing -from abc import abstractmethod, abstractproperty from dataclasses import dataclass, field -from typing import List, Literal, Tuple, Type +from typing import Literal, Type import torch.distributed as dist -import torchvision from torch.nn.parallel import DistributedDataParallel as DDP from nerfstudio.configs import base_config as cfg -from nerfstudio.data.datamanagers.base_datamanager import ( - DataManagerConfig, - VanillaDataManagerConfig, -) -from nerfstudio.data.datamanagers.lerf_datamanager import ( - LERFDataManager, - LERFDataManagerConfig, -) from nerfstudio.models.base_model import ModelConfig -from nerfstudio.models.lerf import LERFModel, LERFModelConfig from nerfstudio.pipelines.base_pipeline import ( - Pipeline, VanillaPipeline, VanillaPipelineConfig, ) -try: - import open_clip -except ImportError: - assert False, "open_clip is not installed, install it with `pip install open-clip-torch`" - -import torch - -from nerfstudio.pipelines.lerf_encoders import ( - ImageEncoder, - OpenCLIPNetwork, - OpenCLIPNetworkConfig, +from lerf.data.lerf_datamanager import ( + LERFDataManager, + LERFDataManagerConfig, ) +from lerf.lerf import LERFModel, LERFModelConfig +from lerf.lerf_encoders import OpenCLIPNetwork, OpenCLIPNetworkConfig @dataclass diff --git a/projects-lerf/pyproject.toml b/projects-lerf/pyproject.toml new file mode 100644 index 000000000..aff2088c1 --- /dev/null +++ b/projects-lerf/pyproject.toml @@ -0,0 +1,6 @@ +[project] +name = "lerf" +version = "0.1.0" + +[project.entry-points.'nerfstudio.method_configs'] +lerf = 'lerf.lerf_config:lerf_method'