rename files, add gitignore for data folder in lerf

This commit is contained in:
Justin committed 2023-04-03 18:46:12 +00:00
1 parent 39ffc38d97
commit ca7f381622
18 files changed
+8 -50

No files matched your search

+1
View File
@@ -0,0 +1 @@
!lerf/data
+2
View File
@@ -0,0 +1,2 @@
# LERF Implementation
TODO
+125
View File
@@ -0,0 +1,125 @@
# 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
import os.path as osp
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple, Type, Union
import torch
import yaml
from rich.progress import Console
from nerfstudio.cameras.rays import RayBundle
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 lerf.data.utils.dino_dataloader import DinoDataloader
from lerf.data.utils.pyramid_embedding_dataloader import PyramidEmbeddingDataloader
from lerf.encoders.image_encoder import BaseImageEncoder
from nerfstudio.data.datamanagers.base_datamanager import (
VanillaDataManager,
VanillaDataManagerConfig,
)
@dataclass
class LERFDataManagerConfig(VanillaDataManagerConfig):
_target: Type = field(default_factory=lambda: LERFDataManager)
patch_tile_size_range: Tuple[int, int] = (0.05, 0.5)
patch_tile_size_res: int = 7
patch_stride_scaler: float = 0.5
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: BaseImageEncoder = 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)
cache_dir = f"outputs/{self.config.dataparser.data.name}"
clip_cache_path = Path(osp.join(cache_dir, f"clip_{self.image_encoder.name}"))
dino_cache_path = Path(osp.join(cache_dir, "dino.npy"))
# NOTE: cache config is sensitive to list vs. tuple, because it checks for dict equality
self.clip_interpolator = PyramidEmbeddingDataloader(
image_list=images,
device=self.device,
cfg={
"tile_size_range": [0.05, 0.5],
"tile_size_res": 7,
"stride_scaler": 0.5,
"image_shape": list(images.shape[2:4]),
"model_name": self.image_encoder.name
},
cache_path=clip_cache_path,
model=self.image_encoder,
)
self.dino_dataloader = DinoDataloader(
image_list=images,
device=self.device,
cfg={"image_shape": list(images.shape[2:4])},
cache_path=dino_cache_path,
)
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
@@ -0,0 +1,54 @@
import typing
import torch
from tqdm import tqdm
from lerf.data.utils.dino_extractor import ViTExtractor
from lerf.data.utils.feature_dataloader import FeatureDataloader
class DinoDataloader(FeatureDataloader):
dino_model_type = "dino_vits8"
dino_stride = 8
dino_load_size = 500
dino_layer = 11
dino_facet = "key"
dino_bin = False
def __init__(
self,
cfg: dict,
device: torch.device,
image_list: torch.Tensor,
cache_path: str = None,
):
assert "image_shape" in cfg
super().__init__(cfg, device, image_list, cache_path)
def create(self, image_list):
extractor = ViTExtractor(self.dino_model_type, self.dino_stride)
preproc_image_lst = extractor.preprocess(image_list, self.dino_load_size)[0].to(self.device)
dino_embeds = []
for image in tqdm(preproc_image_lst, desc="dino", total=len(image_list), leave=False):
descriptors = extractor.extract_descriptors(
image.unsqueeze(0),
[self.dino_layer],
self.dino_facet,
self.dino_bin,
)
descriptors = descriptors.reshape(extractor.num_patches[0], extractor.num_patches[1], -1)
dino_embeds.append(descriptors.cpu().detach())
self.data = torch.stack(dino_embeds, dim=0)
def __call__(self, img_points):
# img_points: (B, 3) # (img_ind, x, y)
img_scale = (
self.data.shape[1] / self.cfg["image_shape"][0],
self.data.shape[2] / self.cfg["image_shape"][1],
)
x_ind, y_ind = (img_points[:, 1] * img_scale[0]).long(), (
img_points[:, 2] * img_scale[1]
).long()
return (self.data[img_points[:, 0].long(), x_ind, y_ind]).to(self.device)
@@ -0,0 +1,363 @@
# 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()
@@ -0,0 +1,54 @@
import os
import typing
from abc import ABC, ABCMeta, abstractmethod
from pathlib import Path
import json
import numpy as np
import torch
class FeatureDataloader(ABC):
def __init__(
self,
cfg: dict,
device: torch.device,
image_list: torch.Tensor, # (N, 3, H, W)
cache_path: Path,
):
self.cfg = cfg
self.device = device
self.cache_path = cache_path
self.data = None # only expect data to be cached, nothing else
self.try_load(image_list) # don't save image_list, avoid duplicates
@abstractmethod
def __call__(self, img_points):
# img_points: (B, 3) # (img_ind, x, y)
pass
@abstractmethod
def create(self, image_list: torch.Tensor):
pass
def load(self):
cache_info_path = self.cache_path.with_suffix(".info")
if not cache_info_path.exists():
raise FileNotFoundError
with open(cache_info_path, "r") as f:
cfg = json.loads(f.read())
if cfg != self.cfg:
raise ValueError("Config mismatch")
self.data = torch.from_numpy(np.load(self.cache_path))
def save(self):
cache_info_path = self.cache_path.with_suffix(".info")
with open(cache_info_path, "w") as f:
f.write(json.dumps(self.cfg))
np.save(self.cache_path, self.data)
def try_load(self, img_list: torch.Tensor):
try:
self.load()
except (FileNotFoundError, ValueError):
self.create(img_list)
self.save()
@@ -0,0 +1,125 @@
import numpy as np
import torch
from lerf.data.utils.feature_dataloader import FeatureDataloader
from lerf.encoders.image_encoder import BaseImageEncoder
from tqdm import tqdm
class PatchEmbeddingDataloader(FeatureDataloader):
def __init__(
self,
cfg: dict,
device: torch.device,
model: BaseImageEncoder,
image_list: torch.Tensor = None,
cache_path: str = None,
):
assert "tile_ratio" in cfg
assert "stride_ratio" in cfg
assert "image_shape" in cfg
assert "model_name" in cfg
self.kernel_size = int(cfg["image_shape"][0] * cfg["tile_ratio"])
self.stride = int(self.kernel_size * cfg["stride_ratio"])
self.padding = self.kernel_size // 2
self.center_x = (
(self.kernel_size - 1) / 2
- self.padding
+ self.stride
* np.arange(
np.floor((cfg["image_shape"][0] + 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((cfg["image_shape"][1] + 2 * self.padding - (self.kernel_size - 1) - 1) / self.stride + 1)
)
)
self.center_x = torch.from_numpy(self.center_x).to(device)
self.center_y = torch.from_numpy(self.center_y).to(device)
self.model = model
self.embed_size = self.model.embedding_dim
super().__init__(cfg, device, image_list, cache_path)
def create(self, image_list):
assert self.model is not None, "model must be provided to generate features"
assert image_list is not None, "image_list must be provided to generate features"
unfold_func = torch.nn.Unfold(
kernel_size=self.kernel_size,
stride=self.stride,
padding=self.padding,
).to(self.device)
img_embeds = []
for img in tqdm(image_list, desc="Embedding images", leave=False):
img_embeds.append(self._embed_clip_tiles(img.unsqueeze(0), unfold_func))
self.data = torch.from_numpy(np.stack(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.data[img_ind, x_ind, y_ind].to(self.device)
topright = self.data[img_ind, x_ind + 1, y_ind].to(self.device)
botleft = self.data[img_ind, x_ind, y_ind + 1].to(self.device)
botright = self.data[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 _embed_clip_tiles(self, image, unfold_func):
# image augmentation: slow-ish (0.02s for 600x800 image per augmentation)
aug_imgs = torch.cat([image])
tiles = unfold_func(aug_imgs).permute(2, 0, 1).reshape(-1, 3, self.kernel_size, self.kernel_size).to("cuda")
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()
# 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)
@@ -0,0 +1,162 @@
import os
import numpy as np
import torch
from lerf.data.utils.feature_dataloader import FeatureDataloader
from lerf.data.utils.patch_embedding_dataloader import PatchEmbeddingDataloader
from lerf.encoders.image_encoder import BaseImageEncoder
from tqdm import tqdm
from pathlib import Path
import json
class PyramidEmbeddingDataloader(FeatureDataloader):
def __init__(
self,
cfg: dict,
device: torch.device,
model: BaseImageEncoder,
image_list: torch.Tensor = None,
cache_path: str = None,
):
assert "tile_size_range" in cfg
assert "tile_size_res" in cfg
assert "stride_scaler" in cfg
assert "image_shape" in cfg
assert "model_name" in cfg
self.tile_sizes = torch.linspace(*cfg["tile_size_range"], cfg["tile_size_res"]).to(device)
self.strider_scaler_list = [self._stride_scaler(tr.item(), cfg["stride_scaler"]) for tr in self.tile_sizes]
self.model = model
self.embed_size = self.model.embedding_dim
self.data_dict = {}
super().__init__(cfg, device, image_list, cache_path)
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 _stride_scaler(self, tile_ratio, stride_scaler):
return np.interp(tile_ratio, [0.05, 0.15], [1.0, stride_scaler])
def load(self):
# don't create anything, PatchEmbeddingDataloader will create itself
cache_info_path = self.cache_path.with_suffix(".info")
# check if cache exists
if not cache_info_path.exists():
raise FileNotFoundError
# if config is different, remove all cached content
with open(cache_info_path, "r") as f:
cfg = json.loads(f.read())
if cfg != self.cfg:
for f in os.listdir(self.cache_path):
os.remove(os.path.join(self.cache_path, f))
raise ValueError("Config mismatch")
raise FileNotFoundError # trigger create
def create(self, image_list):
os.makedirs(self.cache_path, exist_ok=True)
for i, tr in enumerate(tqdm(self.tile_sizes, desc="Scales")):
stride_scaler = self.strider_scaler_list[i]
self.data_dict[i] = PatchEmbeddingDataloader(
cfg={
"tile_ratio": tr.item(),
"stride_ratio": stride_scaler,
"image_shape": self.cfg["image_shape"],
"model_name": self.cfg["model_name"]
},
device=self.device,
model=self.model,
image_list=image_list,
cache_path=Path(f"{self.cache_path}/level_{i}.npy"),
)
def save(self):
cache_info_path = self.cache_path.with_suffix(".info")
with open(cache_info_path, "w") as f:
f.write(json.dumps(self.cfg))
# don't save anything, PatchEmbeddingDataloader will save itself
pass
def _random_scales(self, img_points):
# img_points: (B, 3) # (img_ind, x, y)
# return: (B, 512), some random scale (between 0, 1)
random_scale_bin = torch.randint(self.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 = (self.tile_sizes[1] - self.tile_sizes[0]) / (self.tile_sizes[-1] - self.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(self.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):
scale_bin = torch.floor(
(scale - self.tile_sizes[0]) / (self.tile_sizes[-1] - self.tile_sizes[0]) * (self.tile_sizes.shape[0] - 1)
).to(torch.int64)
scale_weight = (scale - self.tile_sizes[scale_bin]) / (self.tile_sizes[scale_bin + 1] - self.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
# 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
@@ -0,0 +1,88 @@
from dataclasses import dataclass, field
from typing import Tuple, Type
import torch
import torchvision
try:
import clip
except ImportError:
assert False, "clip is not installed, install it with `pip install clip`"
from lerf.encoders.image_encoder import BaseImageEncoder, BaseImageEncoderConfig
@dataclass
class CLIPNetworkConfig(BaseImageEncoderConfig):
_target: Type = field(default_factory=lambda: CLIPNetwork)
clip_model_type: str = "ViT-B/16"
clip_n_dims: int = 512
negatives: Tuple[str] = ("object", "things", "stuff", "texture")
class CLIPNetwork(BaseImageEncoder):
def __init__(self, config: CLIPNetworkConfig):
self.config = config
self.process = torchvision.transforms.Compose(
[
torchvision.transforms.Resize((224, 224)),
torchvision.transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
model, _ = clip.load(self.config.clip_model_type)
model.eval()
self.tokenizer = clip.tokenize
self.model = model.to("cuda")
self.clip_n_dims = self.config.clip_n_dims
self.positives = ["hand sanitizer"]
self.negatives = self.config.negatives
with torch.no_grad():
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.positives]).to("cuda")
self.pos_embeds = model.encode_text(tok_phrases)
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.negatives]).to("cuda")
self.neg_embeds = model.encode_text(tok_phrases)
self.pos_embeds /= self.pos_embeds.norm(dim=-1, keepdim=True)
self.neg_embeds /= self.neg_embeds.norm(dim=-1, keepdim=True)
assert (
self.pos_embeds.shape[1] == self.neg_embeds.shape[1]
), "Positive and negative embeddings must have the same dimensionality"
assert (
self.pos_embeds.shape[1] == self.clip_n_dims
), "Embedding dimensionality must match the model dimensionality"
@property
def name(self) -> str:
return "clip_openai_{}".format(self.config.clip_model_type)
@property
def embedding_dim(self) -> int:
return self.config.clip_n_dims
def set_positives(self, text_list):
self.positives = text_list
with torch.no_grad():
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.positives]).to("cuda")
self.pos_embeds = self.model.encode_text(tok_phrases)
self.pos_embeds /= self.pos_embeds.norm(dim=-1, keepdim=True)
def get_relevancy(self, embed: torch.Tensor, positive_id: int) -> torch.Tensor:
phrases_embeds = torch.cat([self.pos_embeds, self.neg_embeds], dim=0)
p = phrases_embeds.to(embed.dtype) # phrases x 512
output = torch.mm(embed, p.T) # rays x phrases
positive_vals = output[..., positive_id : positive_id + 1] # rays x 1
negative_vals = output[..., len(self.positives) :] # rays x N_phrase
repeated_pos = positive_vals.repeat(1, len(self.negatives)) # rays x N_phrase
sims = torch.stack((repeated_pos, negative_vals), dim=-1) # rays x N-phrase x 2
softmax = torch.softmax(10 * sims, dim=-1) # rays x n-phrase x 2
best_id = softmax[..., 0].argmin(dim=1) # rays x 2
return torch.gather(softmax, 1, best_id[..., None, None].expand(best_id.shape[0], len(self.negatives), 2))[
:, 0, :
]
def encode_image(self, input):
processed_input = self.process(input).half()
return self.model.encode_image(processed_input)
@@ -0,0 +1,36 @@
from abc import abstractmethod, abstractproperty
from dataclasses import dataclass, field
from typing import Type
import torch
from nerfstudio.configs import base_config as cfg
@dataclass
class BaseImageEncoderConfig(cfg.InstantiateConfig):
_target: Type = field(default_factory=lambda: BaseImageEncoder)
class BaseImageEncoder:
@abstractproperty
def name(self) -> str:
"""
returns the name of the encoder
"""
@abstractproperty
def embedding_dim(self) -> int:
"""
returns the dimension of the embeddings
"""
@abstractmethod
def encode_image(self, input: torch.Tensor) -> torch.Tensor:
"""
Given a batch of input images, return their encodings
"""
@abstractmethod
def get_relevancy(self, embed: torch.Tensor, positive_id: int) -> torch.Tensor:
"""
Given a batch of embeddings, return the relevancy to the given positive id
"""
@@ -0,0 +1,94 @@
from dataclasses import dataclass, field
from typing import Tuple, Type
import torch
import torchvision
try:
import open_clip
except ImportError:
assert False, "open_clip is not installed, install it with `pip install open-clip-torch`"
from lerf.encoders.image_encoder import BaseImageEncoder, BaseImageEncoderConfig
@dataclass
class OpenCLIPNetworkConfig(BaseImageEncoderConfig):
_target: Type = field(default_factory=lambda: OpenCLIPNetwork)
clip_model_type: str = "ViT-B-16"
clip_model_pretrained: str = "laion2b_s34b_b88k"
clip_n_dims: int = 512
negatives: Tuple[str] = ("object", "things", "stuff", "texture")
class OpenCLIPNetwork(BaseImageEncoder):
def __init__(self, config: OpenCLIPNetworkConfig):
self.config = config
self.process = torchvision.transforms.Compose(
[
torchvision.transforms.Resize((224, 224)),
torchvision.transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711],
),
]
)
model, _, _ = open_clip.create_model_and_transforms(
self.config.clip_model_type, # e.g., ViT-B-16
pretrained=self.config.clip_model_pretrained, # e.g., laion2b_s34b_b88k
precision="fp16",
)
model.eval()
self.tokenizer = open_clip.get_tokenizer(self.config.clip_model_type)
self.model = model.to("cuda")
self.clip_n_dims = self.config.clip_n_dims
self.positives = ["hand sanitizer"]
self.negatives = self.config.negatives
with torch.no_grad():
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.positives]).to("cuda")
self.pos_embeds = model.encode_text(tok_phrases)
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.negatives]).to("cuda")
self.neg_embeds = model.encode_text(tok_phrases)
self.pos_embeds /= self.pos_embeds.norm(dim=-1, keepdim=True)
self.neg_embeds /= self.neg_embeds.norm(dim=-1, keepdim=True)
assert (
self.pos_embeds.shape[1] == self.neg_embeds.shape[1]
), "Positive and negative embeddings must have the same dimensionality"
assert (
self.pos_embeds.shape[1] == self.clip_n_dims
), "Embedding dimensionality must match the model dimensionality"
@property
def name(self) -> str:
return "openclip_{}_{}".format(self.config.clip_model_type, self.config.clip_model_pretrained)
@property
def embedding_dim(self) -> int:
return self.config.clip_n_dims
def set_positives(self, text_list):
self.positives = text_list
with torch.no_grad():
tok_phrases = torch.cat([self.tokenizer(phrase) for phrase in self.positives]).to("cuda")
self.pos_embeds = self.model.encode_text(tok_phrases)
self.pos_embeds /= self.pos_embeds.norm(dim=-1, keepdim=True)
def get_relevancy(self, embed: torch.Tensor, positive_id: int) -> torch.Tensor:
phrases_embeds = torch.cat([self.pos_embeds, self.neg_embeds], dim=0)
p = phrases_embeds.to(embed.dtype) # phrases x 512
output = torch.mm(embed, p.T) # rays x phrases
positive_vals = output[..., positive_id : positive_id + 1] # rays x 1
negative_vals = output[..., len(self.positives) :] # rays x N_phrase
repeated_pos = positive_vals.repeat(1, len(self.negatives)) # rays x N_phrase
sims = torch.stack((repeated_pos, negative_vals), dim=-1) # rays x N-phrase x 2
softmax = torch.softmax(10 * sims, dim=-1) # rays x n-phrase x 2
best_id = softmax[..., 0].argmin(dim=1) # rays x 2
return torch.gather(softmax, 1, best_id[..., None, None].expand(best_id.shape[0], len(self.negatives), 2))[
:, 0, :
]
def encode_image(self, input):
processed_input = self.process(input).half()
return self.model.encode_image(processed_input)
+219
View File
@@ -0,0 +1,219 @@
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Type
import numpy as np
import open_clip
import torch
from lerf.encoders.image_encoder import BaseImageEncoder
from lerf.lerf_field import LERFField
from lerf.lerf_fieldheadnames import LERFFieldHeadNames
from lerf.lerf_renderers import CLIPRenderer, MeanRenderer
from torch.nn import Parameter
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.model_components.ray_samplers import PDFSampler
from nerfstudio.model_components.renderers import DepthRenderer
from nerfstudio.models.nerfacto import NerfactoModel, NerfactoModelConfig
@dataclass
class LERFModelConfig(NerfactoModelConfig):
_target: Type = field(default_factory=lambda: LERFModel)
clip_loss_weight: float = 0.1
n_scales: int = 30
max_scale: float = 1.5
"""maximum scale used to compute relevancy with"""
num_lerf_samples: int = 24
hashgrid_layers: Tuple[int] = (12, 12)
hashgrid_resolutions: Tuple[Tuple[int]] = ((16, 128), (128, 512))
hashgrid_sizes: Tuple[int] = (19, 19)
class LERFModel(NerfactoModel):
config: LERFModelConfig
def populate_modules(self):
super().populate_modules()
self.renderer_clip = CLIPRenderer()
self.renderer_mean = MeanRenderer()
self.image_encoder: BaseImageEncoder = self.kwargs["image_encoder"]
self.lerf_field = LERFField(
self.config.hashgrid_layers,
self.config.hashgrid_sizes,
self.config.hashgrid_resolutions,
clip_n_dims=self.image_encoder.embedding_dim,
)
def get_max_across(self, ray_samples, weights, hashgrid_field, scales_shape, preset_scales=None):
# TODO smoothen this out
if preset_scales is not None:
assert len(preset_scales) == len(self.image_encoder.positives)
scales_list = torch.tensor(preset_scales)
else:
scales_list = torch.linspace(0.0, self.config.max_scale, self.config.n_scales)
# probably not a good idea bc it's prob going to be a lot of memory
n_phrases = len(self.image_encoder.positives)
n_phrases_maxs = [None for _ in range(n_phrases)]
n_phrases_sims = [None for _ in range(n_phrases)]
for _, scale in enumerate(scales_list):
scale = scale.item()
with torch.no_grad():
clip_output = self.lerf_field.get_output_from_hashgrid(
ray_samples,
hashgrid_field,
torch.full(scales_shape, scale, device=weights.device, dtype=hashgrid_field.dtype),
)
clip_output = self.renderer_clip(embeds=clip_output, weights=weights.detach())
for i in range(n_phrases):
probs = self.image_encoder.get_relevancy(clip_output, i)
pos_prob = probs[..., 0:1]
if n_phrases_maxs[i] is None or pos_prob.max() > n_phrases_sims[i].max():
n_phrases_maxs[i] = scale
n_phrases_sims[i] = pos_prob
return torch.stack(n_phrases_sims), torch.Tensor(n_phrases_maxs)
def get_outputs(self, ray_bundle: RayBundle):
ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns)
ray_samples_list.append(ray_samples)
nerfacto_field_outputs, outputs, weights = self._get_outputs_nerfacto(ray_samples)
lerf_weights, best_ids = torch.topk(weights, self.config.num_lerf_samples, dim=-2, sorted=False)
def gather_fn(tens):
return torch.gather(tens, -2, best_ids.expand(*best_ids.shape[:-1], tens.shape[-1]))
dataclass_fn = lambda dc: dc._apply_fn_to_fields(gather_fn, dataclass_fn)
lerf_samples = ray_samples._apply_fn_to_fields(gather_fn, dataclass_fn)
if self.training:
clip_scales = ray_bundle.metadata["clip_scales"]
clip_scales = clip_scales[..., None]
dist = lerf_samples.spacing_to_euclidean_fn(lerf_samples.spacing_starts.squeeze(-1)).unsqueeze(-1)
clip_scales = clip_scales * ray_bundle.metadata["width"] * (1 / ray_bundle.metadata["fx"]) * dist
else:
clip_scales = torch.ones_like(lerf_samples.spacing_starts, device=self.device)
override_scales = (
None if "override_scales" not in ray_bundle.metadata else ray_bundle.metadata["override_scales"]
)
weights_list.append(weights)
if self.training:
outputs["weights_list"] = weights_list
outputs["ray_samples_list"] = ray_samples_list
for i in range(self.config.num_proposal_iterations):
outputs[f"prop_depth_{i}"] = self.renderer_depth(weights=weights_list[i], ray_samples=ray_samples_list[i])
lerf_field_outputs = self.lerf_field.get_outputs(lerf_samples, clip_scales)
if self.training:
outputs["clip"] = self.renderer_clip(
embeds=lerf_field_outputs[LERFFieldHeadNames.CLIP], weights=lerf_weights.detach()
)
outputs["dino"] = self.renderer_mean(
embeds=lerf_field_outputs[LERFFieldHeadNames.DINO], weights=lerf_weights.detach()
)
if not self.training:
with torch.no_grad():
max_across, best_scales = self.get_max_across(
lerf_samples,
lerf_weights,
lerf_field_outputs[LERFFieldHeadNames.HASHGRID],
clip_scales.shape,
preset_scales=override_scales,
)
outputs["raw_relevancy"] = max_across # N x B x 1
outputs["best_scales"] = best_scales.to(self.device) # N
return outputs
@torch.no_grad()
def get_outputs_for_camera_ray_bundle(self, camera_ray_bundle: RayBundle) -> Dict[str, torch.Tensor]:
"""Takes in camera parameters and computes the output of the model.
LERF overrides this from base_model since we need to compute the max_across relevancy in multiple batches,
which are not independent since they need to use the same scale
Args:
camera_ray_bundle: ray bundle to calculate outputs over
"""
# TODO(justin) implement max across behavior
num_rays_per_chunk = self.config.eval_num_rays_per_chunk
image_height, image_width = camera_ray_bundle.origins.shape[:2]
num_rays = len(camera_ray_bundle)
outputs_lists = defaultdict(list) # dict from name:list of outputs (1 per bundle)
for i in range(0, num_rays, num_rays_per_chunk):
start_idx = i
end_idx = i + num_rays_per_chunk
ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
outputs = self.forward(ray_bundle=ray_bundle)
# take the best scale for each query across each ray bundle
if i == 0:
best_scales = outputs["best_scales"]
best_relevancies = [m.max() for m in outputs["raw_relevancy"]]
else:
for phrase_i in range(outputs["best_scales"].shape[0]):
m = outputs["raw_relevancy"][phrase_i, ...].max()
if m > best_relevancies[phrase_i]:
best_scales[phrase_i] = outputs["best_scales"][phrase_i]
best_relevancies[phrase_i] = m
# re-render the max_across outputs using the best scales across all batches
for i in range(0, num_rays, num_rays_per_chunk):
start_idx = i
end_idx = i + num_rays_per_chunk
ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
ray_bundle.metadata["override_scales"] = best_scales
outputs = self.forward(ray_bundle=ray_bundle)
# standard nerfstudio concatting
for output_name, output in outputs.items(): # type: ignore
if output_name == "best_scales":
continue
if output_name == "raw_relevancy":
for r_id in range(output.shape[0]):
outputs_lists[f"relevancy_{r_id}"].append(output[r_id, ...])
else:
outputs_lists[output_name].append(output)
outputs = {}
for output_name, outputs_list in outputs_lists.items():
if not torch.is_tensor(outputs_list[0]):
# TODO: handle lists of tensors as well
continue
outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore
return outputs
def _get_outputs_nerfacto(self, ray_samples: RaySamples):
field_outputs = self.field(ray_samples, compute_normals=self.config.predict_normals)
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
rgb = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB], weights=weights)
depth = self.renderer_depth(weights=weights, ray_samples=ray_samples)
accumulation = self.renderer_accumulation(weights=weights)
outputs = {
"rgb": rgb,
"accumulation": accumulation,
"depth": depth,
}
return field_outputs, outputs, weights
def get_loss_dict(self, outputs, batch, metrics_dict=None):
loss_dict = super().get_loss_dict(outputs, batch, metrics_dict)
loss_dict["clip_loss"] = self.config.clip_loss_weight * torch.nn.functional.huber_loss(
outputs["clip"], batch["clip"], delta=1.25
)
loss_dict["dino_loss"] = torch.nn.functional.mse_loss(outputs["dino"], batch["dino"])
return loss_dict
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = super().get_param_groups()
param_groups["lerf"] = list(self.lerf_field.parameters())
return param_groups
+165
View File
@@ -0,0 +1,165 @@
"""
LERF configuration file.
"""
from lerf.data.lerf_datamanager import LERFDataManagerConfig
from lerf.lerf import LERFModelConfig
from lerf.lerf_pipeline import LERFPipelineConfig
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
"""
Swap out the network config to use OpenCLIP or CLIP here.
"""
from lerf.encoders.clip_encoder import CLIPNetworkConfig
from lerf.encoders.openclip_encoder 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 << 15,
hashgrid_sizes=(19, 19),
hashgrid_layers=(12, 12),
hashgrid_resolutions=((16, 128), (128, 512)),
num_lerf_samples=24,
),
network=OpenCLIPNetworkConfig(
clip_model_type="ViT-B-16", clip_model_pretrained="laion2b_s34b_b88k", clip_n_dims=512
),
# You can swap the type of input encoder by specifying different NetworkConfigs, the one below uses OpenAI CLIP, the one above uses OpenCLIP
# network=CLIPNetworkConfig(
# clip_model_type="ViT-B/16", 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="Base config for LERF",
)
lerf_method_big = MethodSpecification(
config=TrainerConfig(
method_name="lerf-big",
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 << 15,
hashgrid_sizes=(19, 19),
hashgrid_layers=(16, 16),
hashgrid_resolutions=((16, 128), (128, 512)),
num_lerf_samples=32,
),
network=OpenCLIPNetworkConfig(
clip_model_type="ViT-L-14", clip_model_pretrained="laion2b_s32b_b82k", clip_n_dims=768
),
),
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=3000),
},
},
viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
vis="viewer",
),
description="A larger version of LERF with a higher memory footprint, bigger CLIP model, and more hashgrid capacity",
)
lerf_method_lite = MethodSpecification(
config=TrainerConfig(
method_name="lerf-lite",
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 << 15,
hashgrid_sizes=(19,),
hashgrid_layers=(16,),
hashgrid_resolutions=((16, 512),),
num_lerf_samples=12,
),
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="A lightweight version of LERF designed to work on smaller GPUs",
)
+116
View File
@@ -0,0 +1,116 @@
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
from lerf.lerf_fieldheadnames import LERFFieldHeadNames
from torch import nn
from torch.nn.parameter import Parameter
from torchtyping import TensorType
from nerfstudio.cameras.rays import RaySamples
from nerfstudio.data.scene_box import SceneBox
from nerfstudio.field_components.activations import trunc_exp
from nerfstudio.field_components.field_heads import FieldHeadNames
from nerfstudio.field_components.spatial_distortions import (
SceneContraction,
SpatialDistortion,
)
from nerfstudio.fields.base_field import Field
try:
import tinycudann as tcnn
except ImportError:
pass
class LERFField(Field):
def __init__(
self,
grid_layers,
grid_sizes,
grid_resolutions,
clip_n_dims: int,
spatial_distortion: SpatialDistortion = SceneContraction(),
):
super().__init__()
assert len(grid_layers) == len(grid_sizes) and len(grid_resolutions) == len(grid_layers)
self.spatial_distortion = spatial_distortion
self.clip_encs = torch.nn.ModuleList(
[
LERFField._get_encoding(
grid_resolutions[i][0], grid_resolutions[i][1], grid_layers[i], indim=3, hash_size=grid_sizes[i]
) for i in range(len(grid_layers))
]
)
tot_out_dims = sum([e.n_output_dims for e in self.clip_encs])
self.clip_net = tcnn.Network(
n_input_dims=tot_out_dims + 1,
n_output_dims=clip_n_dims,
network_config={
"otype": "CutlassMLP",
"activation": "ReLU",
"output_activation": "None",
"n_neurons": 256,
"n_hidden_layers": 4,
},
)
self.dino_net = tcnn.Network(
n_input_dims=tot_out_dims,
n_output_dims=384,
network_config={
"otype": "CutlassMLP",
"activation": "ReLU",
"output_activation": "None",
"n_neurons": 256,
"n_hidden_layers": 1,
},
)
@staticmethod
def _get_encoding(start_res, end_res, levels, indim=3, hash_size=19):
growth = np.exp((np.log(end_res) - np.log(start_res)) / (levels - 1))
enc = tcnn.Encoding(
n_input_dims=indim,
encoding_config={
"otype": "HashGrid",
"n_levels": levels,
"n_features_per_level": 8,
"log2_hashmap_size": hash_size,
"base_resolution": start_res,
"per_level_scale": growth,
},
)
return enc
def get_outputs(self, ray_samples: RaySamples, clip_scales) -> Dict[LERFFieldHeadNames, TensorType]:
# random scales, one scale
outputs = {}
positions = ray_samples.frustums.get_positions().detach()
positions = self.spatial_distortion(positions)
positions = (positions + 2.0) / 4.0
xs = [e(positions.view(-1, 3)) for e in self.clip_encs]
x = torch.concat(xs, dim=-1)
outputs[LERFFieldHeadNames.HASHGRID] = x.view(*ray_samples.frustums.shape, -1)
clip_pass = self.clip_net(torch.cat([x, clip_scales.view(-1, 1)], dim=-1)).view(*ray_samples.frustums.shape, -1)
outputs[LERFFieldHeadNames.CLIP] = clip_pass / clip_pass.norm(dim=-1, keepdim=True)
dino_pass = self.dino_net(x).view(*ray_samples.frustums.shape, -1)
outputs[LERFFieldHeadNames.DINO] = dino_pass
return outputs
def get_output_from_hashgrid(self, ray_samples: RaySamples, hashgrid_field, scale):
# designated scales, run outputs for each scale
hashgrid_field = hashgrid_field.view(-1, self.clip_net.n_input_dims - 1)
clip_pass = self.clip_net(torch.cat([hashgrid_field, scale.view(-1, 1)], dim=-1)).view(
*ray_samples.frustums.shape, -1
)
output = clip_pass / clip_pass.norm(dim=-1, keepdim=True)
return output
@@ -0,0 +1,8 @@
from enum import Enum
# from nerfstudio.field_components.field_heads import FieldHeadNames
class LERFFieldHeadNames(Enum):
"""Possible field outputs"""
HASHGRID = "hashgrid"
CLIP = "clip"
DINO = "dino"
+75
View File
@@ -0,0 +1,75 @@
import typing
from dataclasses import dataclass, field
from typing import Literal, Type
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from nerfstudio.configs import base_config as cfg
from nerfstudio.models.base_model import ModelConfig
from nerfstudio.pipelines.base_pipeline import (
VanillaPipeline,
VanillaPipelineConfig,
)
from lerf.data.lerf_datamanager import (
LERFDataManager,
LERFDataManagerConfig,
)
from lerf.lerf import LERFModel, LERFModelConfig
from lerf.encoders.image_encoder import BaseImageEncoderConfig, BaseImageEncoder
@dataclass
class LERFPipelineConfig(VanillaPipelineConfig):
"""Configuration for pipeline instantiation"""
_target: Type = field(default_factory=lambda: LERFPipeline)
"""target class to instantiate"""
datamanager: LERFDataManagerConfig = LERFDataManagerConfig()
"""specifies the datamanager config"""
model: ModelConfig = LERFModelConfig()
"""specifies the model config"""
network: BaseImageEncoderConfig = BaseImageEncoderConfig()
"""specifies the vision-language network config"""
class LERFPipeline(VanillaPipeline):
def __init__(
self,
config: LERFPipelineConfig,
device: str,
test_mode: Literal["test", "val", "inference"] = "val",
world_size: int = 1,
local_rank: int = 0,
):
super(VanillaPipeline, self).__init__()
self.config = config
self.test_mode = test_mode
self.image_encoder: BaseImageEncoder = config.network.setup()
self.datamanager: LERFDataManager = config.datamanager.setup(
device=device,
test_mode=test_mode,
world_size=world_size,
local_rank=local_rank,
image_encoder=self.image_encoder,
)
self.datamanager.to(device)
# TODO(ethan): get rid of scene_bounds from the model
assert self.datamanager.train_dataset is not None, "Missing input dataset"
self._model = config.model.setup(
scene_box=self.datamanager.train_dataset.scene_box,
num_train_data=len(self.datamanager.train_dataset),
metadata=self.datamanager.train_dataset.metadata,
image_encoder=self.image_encoder,
)
self.model.to(device)
self.world_size = world_size
if world_size > 1:
self._model = typing.cast(LERFModel, DDP(self._model, device_ids=[local_rank], find_unused_parameters=True))
dist.barrier(device_ids=[local_rank])
+31
View File
@@ -0,0 +1,31 @@
import torch
from torch import nn
from torchtyping import TensorType
class CLIPRenderer(nn.Module):
"""Calculate CLIP embeddings along ray."""
@classmethod
def forward(
cls,
embeds: TensorType["bs":..., "num_samples", "num_classes"],
weights: TensorType["bs":..., "num_samples", 1],
) -> TensorType["bs":..., "num_classes"]:
"""Calculate semantics along the ray."""
output = torch.sum(weights * embeds, dim=-2)
output = output / torch.linalg.norm(output, dim=-1, keepdim=True)
return output
class MeanRenderer(nn.Module):
"""Calculate average of embeddings along ray."""
@classmethod
def forward(
cls,
embeds: TensorType["bs":..., "num_samples", "num_classes"],
weights: TensorType["bs":..., "num_samples", 1],
) -> TensorType["bs":..., "num_classes"]:
"""Calculate semantics along the ray."""
output = torch.sum(weights * embeds, dim=-2)
return output
+8
View File
@@ -0,0 +1,8 @@
[project]
name = "lerf"
version = "0.1.0"
[project.entry-points.'nerfstudio.method_configs']
lerf = 'lerf.lerf_config:lerf_method'
lerf_big = 'lerf.lerf_config:lerf_method_big'
lerf_lite = 'lerf.lerf_config:lerf_method_lite'