Consolidate lerf to diff proj, pip-installable

This commit is contained in:
Chung Min Kim committed 2023-03-31 21:38:43 +00:00
1 parent 6c12432b82
commit a5c6139994
14 files changed
+73 -1167

No files matched your search

+186
View File
@@ -0,0 +1,186 @@
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 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 (
CLIPRenderer,
DepthRenderer,
MeanRenderer,
)
from nerfstudio.models.nerfacto import NerfactoModel, NerfactoModelConfig
from lerf.lerf_encoders import ImageEncoder
from lerf.lerf_field import LERFField
@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"""
specify_scale: bool = False
num_lerf_samples: int = 12
class LERFModel(NerfactoModel):
config: LERFModelConfig
def populate_modules(self):
super().populate_modules()
self.renderer_clip = CLIPRenderer()
self.renderer_mean = MeanRenderer()
self.image_encoder: ImageEncoder = self.kwargs["image_encoder"]
self.lerf_field = LERFField(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 self.config.specify_scale:
assert 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 s, 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] = s
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)
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[FieldHeadNames.CLIP], weights=lerf_weights.detach()
)
outputs["dino"] = self.renderer_mean(
embeds=lerf_field_outputs[FieldHeadNames.DINO], weights=lerf_weights.detach()
)
if not self.training:
max_across, best_scales = self.get_max_across(
lerf_samples, lerf_weights, lerf_field_outputs[FieldHeadNames.HASHGRID], clip_scales.shape
)
multiphrase = max_across[0]
# normalization for sanity check TODO(cmk) remove
multiphrase[multiphrase < 0.5] = 0.5
multiphrase -= 0.5
multiphrase = multiphrase / multiphrase.max()
outputs[f"multiphrase"] = multiphrase
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)
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)
for output_name, output in outputs.items(): # type: ignore
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
+59
View File
@@ -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"
)
+121
View File
@@ -0,0 +1,121 @@
import typing
from abc import abstractmethod, abstractproperty
from dataclasses import dataclass, field
from typing import List, Literal, Tuple, Type
import torchvision
from nerfstudio.configs import base_config as cfg
try:
import open_clip
except ImportError:
assert False, "open_clip is not installed, install it with `pip install open-clip-torch`"
import torch
@dataclass
class OpenCLIPNetworkConfig(cfg.InstantiateConfig):
"""Configuration for network instantiation"""
_target: Type = field(default_factory=lambda: OpenCLIPNetwork)
"""target class to instantiate"""
clip_model_type: str = "ViT-B-16"
clip_model_pretrained: str = "laion2b_s34b_b88k"
clip_n_dims: int = 512
# clip_model_type: str = "ViT-L-14"
# clip_model_pretrained: str = "laion2b_s32b_b82k"
# clip_n_dims: int = 768
negatives: Tuple[str] = ("object", "things", "stuff", "texture")
class ImageEncoder:
@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
"""
# ambivalent about this being here, it's still technically rendering but I want to keep it with the OpenCLIPNetworkConfig
class OpenCLIPNetwork(ImageEncoder):
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 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)
+108
View File
@@ -0,0 +1,108 @@
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
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, clip_n_dims: int, spatial_distortion: SpatialDistortion = SceneContraction()):
super().__init__()
self.spatial_distortion = spatial_distortion
self.clip_encs = torch.nn.ModuleList(
[
# LERFField._get_encoding(16, 512, 16, indim=3)
LERFField._get_encoding(16, 128, 12, indim=3),
LERFField._get_encoding(128, 512, 12, indim=3),
]
)
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):
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": 19,
"base_resolution": start_res,
"per_level_scale": growth,
},
)
return enc
def get_outputs(self, ray_samples: RaySamples, clip_scales):
# 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[FieldHeadNames.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[FieldHeadNames.CLIP] = clip_pass / clip_pass.norm(dim=-1, keepdim=True)
dino_pass = self.dino_net(x).view(*ray_samples.frustums.shape, -1)
outputs[FieldHeadNames.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
+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.lerf_encoders import OpenCLIPNetwork, OpenCLIPNetworkConfig
@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: OpenCLIPNetworkConfig = OpenCLIPNetworkConfig()
"""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: OpenCLIPNetwork = 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])
+6
View File
@@ -0,0 +1,6 @@
[project]
name = "lerf"
version = "0.1.0"
[project.entry-points.'nerfstudio.method_configs']
lerf = 'lerf.lerf_config:lerf_method'