Pipeline v2 (#258)

* Model class done, pipeline class still needs more visualization stuffs

* Renaming the BaseDataContainer to DataloaderOutputs and adding documentation

* Pushing more documentation, removing some trivial functions

* Updating dict typing

* Removing config dicts for collider

* Passing tests

* Pushing shell new dataloader

* Saving work, need to fix NGP model's get_loss_dict and Pipeline

* V1 of the ngp pipeline should be done. Need train script and debugging

* Updating with latest instant-ngp code

* Syntax updates from latest ngp graph code

* Linter, removing unneeded code in new NGP graph code

* Style

* Should be good now. Linter is happy and the code is verbatum current instant-ngp

* Everything done except novel view testing code

* Fixing some nitpicks

* Debugging dataloader

* merged master

* WOP. integrating pipeline with configs and notebook demo

* removing model folder

* a lot of name changing from Graph to Model

* in progress... changing trainer to use pipeline... broken right now

* pipeline code runs

* switched to val dataset

* makes run_eval.py work

* updated configs for pipeline change

* fixing test_run_train script

* fixing black and linting

* fix docs

* small updates to trainer

Co-authored-by: Jake Austin <jake-austin@berkeley.edu>
This commit is contained in:
Ethan WeberandJake Austin authored and GitHub committed 2022-08-10 14:59:45 -07:00
1 parent 670c2a01db
commit 0b042be956
55 files changed
+8595 -8263

No files matched your search

-344
View File
@@ -1,344 +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.
"""
Data loader.
"""
import random
from abc import abstractmethod
from typing import Dict, List, Optional, Tuple, Union
import torch
from omegaconf import ListConfig
from torch import nn
from torchtyping import TensorType
from nerfactory.cameras.cameras import Camera, get_camera
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.image_dataset import ImageDataset
from nerfactory.data.image_sampler import ImageSampler
from nerfactory.data.pixel_sampler import PixelSampler
from nerfactory.data.structs import BaseDataContainer, DatasetInputs
from nerfactory.graphs.modules.ray_generator import RayGenerator
from nerfactory.utils import profiler
from nerfactory.utils.config import DataConfig
from nerfactory.utils.misc import (
IterableWrapper,
get_dict_to_torch,
instantiate_from_dict_config,
)
@profiler.time_function
def setup_dataset_train(config: DataConfig, device: str) -> Tuple[DatasetInputs, "TrainDataloader"]:
"""Helper method to load train dataset
Args:
config (DataConfig): Configuration of training dataset.
device (str): device to load the dataset to
Returns:
Tuple[DatasetInputs, "TrainDataloader"]: returns both the dataset input information and associated dataloader
"""
dataset_train = instantiate_from_dict_config(config.dataset_inputs_train)
dataset_inputs_train = dataset_train.get_dataset_inputs(
split="train", use_preprocessing_cache=config.use_preprocessing_cache
)
# ImageDataset
image_dataset_train = instantiate_from_dict_config(config.image_dataset_train, **dataset_inputs_train.as_dict())
# ImageSampler
image_sampler_train = instantiate_from_dict_config(
config.dataloader_train.image_sampler, dataset=image_dataset_train, device=device # type: ignore
)
# PixelSampler
pixel_sampler_train = instantiate_from_dict_config(config.dataloader_train.pixel_sampler) # type: ignore
# Dataloader
dataloader_train = TrainDataloader(image_sampler_train, pixel_sampler_train)
return dataset_inputs_train, dataloader_train
@profiler.time_function
def setup_dataset_eval(config: DataConfig, test_mode: bool, device: str) -> Tuple[DatasetInputs, "EvalDataloader"]:
"""Helper method to load test or val dataset based on test/train mode
Args:
config (DataConfig): Configuration of training dataset.
test_mode (bool): specifies whether you are training/testing mode, to load validation/test data
device (str): device to load the dataset to
Returns:
Tuple[DatasetInputs, "TrainDataloader"]: returns both the dataset input information and associated dataloader
"""
eval_split = "test" if test_mode else "val"
dataset_eval = instantiate_from_dict_config(config.dataset_inputs_eval)
dataset_inputs_eval = dataset_eval.get_dataset_inputs(
split=eval_split, use_preprocessing_cache=config.use_preprocessing_cache
)
image_dataset_eval = instantiate_from_dict_config(config.image_dataset_eval, **dataset_inputs_eval.as_dict())
dataloader_eval = instantiate_from_dict_config(
config.dataloader_eval,
image_dataset=image_dataset_eval,
device=device,
**dataset_inputs_eval.as_dict(),
)
return dataset_inputs_eval, dataloader_eval
class AbstractDataloader(nn.Module):
"""Second version of the dataloader class (V2)
This version of the dataloader is designed to subsume both the train and eval dataloaders,
especially since this may contain learnable parameters which need to be shared across the train
and test dataloaders. The idea is that we have setup methods for train and eval separatley and
this can be a combined train/eval if you want.
The default should be for the train and eval dataloaders to be the same, but this can be
overridden. This is needed when there are learned parameters either in your data itself or in
the way some of the data (that we will pass to the renderer / Field) was generated. In these
cases, we want these parameters to be accessible by both the train and eval dataloaders, hence
why you would want them to be in the same dataloader.
An instance where you may want to have only the eval dataloader is if you are doing evaluation
and don't have the dataset used to train the model.
Train Methods:
setup_train: sets up for being used as train
iter_train: returns an iterator of the train dataloader
next_train: will be called on __next__() for the training iterator
Eval Methods:
setup_eval: sets up for being used as eval
iter_eval: returns an iterator of the eval dataloader
next_eval: will be called on __next__() for the eval iterator
Args:
image_sampler (ImageSampler): image sampler
pixel_sampler (PixelSampler): pixel sampler
ray_generator (RayGenerator): ray generator
use_train (bool): whether this is being used for training
use_eval (bool): whether this is being used for evaluation
Attributes:
image_sampler (ImageSampler): image sampler
pixel_sampler (PixelSampler): pixel sampler
ray_generator (RayGenerator): ray generator
train_count (int): number of times train has been called
eval_count (int): number of times eval has been called
"""
def __init__(
self,
image_sampler: ImageSampler,
pixel_sampler: PixelSampler,
ray_generator: RayGenerator,
use_train: bool,
use_eval: bool,
):
super().__init__()
self.image_sampler = image_sampler
self.pixel_sampler = pixel_sampler
self.iter_image_sampler = iter(self.image_sampler)
self.ray_generator = ray_generator
self.use_train = use_train
self.use_eval = use_eval
self.train_count = 0
self.eval_count = 0
assert use_train or use_eval
if use_train:
self.setup_train()
if use_eval:
self.setup_eval()
def iter_train(self) -> IterableWrapper:
"""Returns an iterator that executes the self.next_train function"""
self.train_count = 0
return IterableWrapper(self, self.next_train)
def iter_eval(self) -> IterableWrapper:
"""Returns an iterator that executes the self.next_eval function"""
self.eval_count = 0
return IterableWrapper(self, self.next_eval)
@abstractmethod
def setup_train(self):
"""Sets up the dataloader for training"""
@abstractmethod
def setup_eval(self):
"""Sets up the dataloader for evaluation"""
@abstractmethod
def next_train(self) -> BaseDataContainer:
"""Returns the next batch of data from the train dataloader"""
@abstractmethod
def next_eval(self) -> BaseDataContainer:
"""Returns the next batch of data from the eval dataloader"""
class AbstractStoredDataloader(AbstractDataloader):
"""Subclass of the new V2 dataloader that is used for when things fit in memory,
and will be stored in the dataloader itself.
Attributes:
camera_to_world (torch.Tensor): camera to world transformation
intrinsics (torch.Tensor): intrinsics matrix
"""
camera_to_world: torch.Tensor
intrinsics: torch.Tensor
# These abstract methods are only copied over to appease the linter
@abstractmethod
def setup_train(self):
"""Sets up the dataloader for training"""
@abstractmethod
def setup_eval(self):
"""Sets up the dataloader for evaluation"""
@abstractmethod
def next_train(self) -> BaseDataContainer:
"""Returns the next batch of data from the train dataloader"""
@abstractmethod
def next_eval(self) -> BaseDataContainer:
"""Returns the next batch of data from the eval dataloader"""
class TrainDataloader:
"""Training dataloader base class."""
def __init__(self, image_sampler: ImageSampler, pixel_sampler: PixelSampler):
self.image_sampler = image_sampler
self.pixel_sampler = pixel_sampler
self.iter_image_sampler = iter(self.image_sampler)
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self) -> Tuple[TensorType["num_rays", 3], Dict]:
self.count += 1
image_batch = next(self.iter_image_sampler)
batch = self.pixel_sampler.sample(image_batch)
ray_indices = batch["indices"]
return ray_indices, batch
class EvalDataloader: # pylint: disable=too-few-public-methods
"""Evaluation dataloader base class"""
def __init__(
self, image_dataset: ImageDataset, intrinsics, camera_to_world, num_rays_per_chunk: int, device="cpu", **kwargs
):
super().__init__()
self.image_dataset = image_dataset
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
self.num_rays_per_chunk = num_rays_per_chunk
self.device = device
self.kwargs = kwargs
@abstractmethod
def __iter__(self):
"""Iterates over the dataset"""
return self
@abstractmethod
def __next__(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data"""
def get_camera(self, image_idx) -> Camera:
"""Get camera for the given image index"""
intrinsics = self.intrinsics[image_idx].to(self.device)
camera_to_world = self.camera_to_world[image_idx].to(self.device)
camera = get_camera(intrinsics, camera_to_world, camera_index=image_idx)
return camera
def get_data_from_image_idx(self, image_idx) -> Tuple[RayBundle, Dict]:
"""Returns the data for a specific image index."""
camera = self.get_camera(image_idx)
ray_bundle = camera.get_camera_ray_bundle(device=self.device)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
batch = self.image_dataset[image_idx]
batch = get_dict_to_torch(batch, device=self.device)
return ray_bundle, batch
class FixedIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns a fixed set of indices."""
def __init__(
self,
image_dataset: ImageDataset,
intrinsics,
camera_to_world,
num_rays_per_chunk: int,
image_indices: Optional[Union[List[int], ListConfig]] = None,
device="cpu",
**kwargs,
):
"""
Args:
image_dataset: ImageDataset to load data from
image_indices: List of image indices to load data from. If None, then use all images.
"""
super().__init__(image_dataset, intrinsics, camera_to_world, num_rays_per_chunk, device, **kwargs)
if image_indices is None:
self.image_indices = list(range(len(image_dataset)))
else:
self.image_indices = image_indices
self.num_rays_per_chunk = num_rays_per_chunk
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < len(self.image_indices):
image_idx = self.image_indices[self.count]
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
self.count += 1
return ray_bundle, batch
raise StopIteration
class RandIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns random images."""
def __init__(
self, image_dataset: ImageDataset, intrinsics, camera_to_world, num_rays_per_chunk: int, device="cpu", **kwargs
):
super().__init__(image_dataset, intrinsics, camera_to_world, num_rays_per_chunk, device, **kwargs)
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < 1:
image_indices = range(len(self.camera_to_world))
image_idx = random.choice(image_indices)
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
self.count += 1
return ray_bundle, batch
raise StopIteration
File renamed without changes.
+237
View File
@@ -0,0 +1,237 @@
# 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.
"""
Data loader.
"""
from abc import abstractmethod
from typing import Dict, List, Tuple, Union
import torch
from omegaconf import DictConfig, ListConfig
from torch import nn
from torch.nn import Parameter
from nerfactory.cameras.rays import RayBundle
from nerfactory.dataloaders.eval import FixedIndicesEvalDataloader
from nerfactory.dataloaders.image_dataset import ImageDataset, PanopticImageDataset
from nerfactory.dataloaders.image_sampler import CacheImageSampler
from nerfactory.dataloaders.pixel_sampler import PixelSampler
from nerfactory.dataloaders.structs import DatasetInputs
from nerfactory.models.modules.ray_generator import RayGenerator
from nerfactory.utils import profiler
from nerfactory.utils.config import DataloaderConfig
from nerfactory.utils.misc import IterableWrapper, instantiate_from_dict_config
class Dataloader(nn.Module):
"""Second version of the dataloader class (V2)
This version of the dataloader is designed to subsume both the train and eval dataloaders,
especially since this may contain learnable parameters which need to be shared across the train
and test dataloaders. The idea is that we have setup methods for train and eval separatley and
this can be a combined train/eval if you want.
The default should be for the train and eval dataloaders to be the same, but this can be
overridden. This is needed when there are learned parameters either in your data itself or in
the way some of the data (that we will pass to the renderer / Field) was generated. In these
cases, we want these parameters to be accessible by both the train and eval dataloaders, hence
why you would want them to be in the same dataloader.
An instance where you may want to have only the eval dataloader is if you are doing evaluation
and don't have the dataset used to train the model.
Train Methods:
setup_train: sets up for being used as train
iter_train: returns an iterator of the train dataloader
next_train: will be called on __next__() for the training iterator
Eval Methods:
setup_eval: sets up for being used as eval
iter_eval: returns an iterator of the eval dataloader
next_eval: will be called on __next__() for the eval iterator
Args:
image_sampler (ImageSampler): image sampler
pixel_sampler (PixelSampler): pixel sampler
ray_generator (RayGenerator): ray generator
use_train (bool): whether this is being used for training
use_eval (bool): whether this is being used for evaluation
Attributes:
image_sampler (ImageSampler): image sampler
pixel_sampler (PixelSampler): pixel sampler
train_count (int): number of times train has been called
eval_count (int): number of times eval has been called
"""
def __init__(
self,
use_train: bool,
use_eval: bool,
):
super().__init__()
self.use_train = use_train
self.use_eval = use_eval
self.train_count = 0
self.eval_count = 0
assert use_train or use_eval
if use_train:
self.setup_train()
if use_eval:
self.setup_eval()
def forward(self):
"""Dummy forward method"""
raise NotImplementedError
def iter_train(self) -> IterableWrapper:
"""Returns an iterator that executes the self.next_train function"""
self.train_count = 0
return IterableWrapper(self, self.next_train)
def iter_eval(self) -> IterableWrapper:
"""Returns an iterator that executes the self.next_eval function"""
self.eval_count = 0
return IterableWrapper(self, self.next_eval)
@abstractmethod
def setup_train(self):
"""Sets up the dataloader for training"""
raise NotImplementedError
@abstractmethod
def setup_eval(self):
"""Sets up the dataloader for evaluation"""
raise NotImplementedError
@abstractmethod
def next_train(self) -> Tuple:
"""Returns the next batch of data from the train dataloader.
This will be a tuple of all the information that this dataloader outputs.
"""
raise NotImplementedError
@abstractmethod
def next_eval(self) -> Tuple:
"""Returns the next batch of data from the eval dataloader.
This will be a tuple of all the information that this dataloader outputs.
"""
raise NotImplementedError
def get_param_groups(self) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use
"""Get the param groups for the dataloader.
Returns:
A list of dictionaries containing the dataloader's param groups.
"""
return {}
class VanillaDataloader(Dataloader): # pylint: disable=abstract-method
"""Basic stored dataloader implementation for instant-ngp test run"""
def __init__(
self,
image_dataset_type: str,
train_datasetinputs: DatasetInputs,
train_num_rays_per_batch: int,
train_num_images_to_sample_from: int,
eval_datasetinputs: DatasetInputs,
eval_image_indices: Union[List[int], ListConfig], # TODO(ethan): get rid of this hydra ListConfig nonsense
eval_num_rays_per_chunk: int,
device: Union[torch.device, str] = "cpu",
**kwargs # pylint: disable=unused-argument
):
self.image_dataset_type = image_dataset_type
self.train_datasetinputs = train_datasetinputs
self.train_num_rays_per_batch = train_num_rays_per_batch
self.train_num_images_to_sample_from = train_num_images_to_sample_from
self.eval_datasetinputs = eval_datasetinputs
self.eval_image_indices = eval_image_indices
self.eval_num_rays_per_chunk = eval_num_rays_per_chunk
self.device = device
use_train = self.train_datasetinputs is not None
use_eval = self.eval_datasetinputs is not None
super().__init__(use_train, use_eval)
def setup_train(self):
"""Sets up the dataloader for training"""
if self.image_dataset_type == "rgb":
self.train_image_dataset = ImageDataset(**self.train_datasetinputs.as_dict())
elif self.image_dataset_type == "panoptic":
self.train_image_dataset = PanopticImageDataset(**self.train_datasetinputs.as_dict())
self.train_image_sampler = CacheImageSampler(
self.train_image_dataset, num_images_to_sample_from=self.train_num_images_to_sample_from, device=self.device
) # TODO(ethan): pass this in
self.iter_train_image_sampler = iter(self.train_image_sampler)
self.train_pixel_sampler = PixelSampler(self.train_num_rays_per_batch)
self.train_ray_generator = RayGenerator(
self.train_datasetinputs.intrinsics, self.train_datasetinputs.camera_to_world
)
def setup_eval(self):
"""Sets up the dataloader for evaluation"""
if self.image_dataset_type == "rgb":
self.eval_image_dataset = ImageDataset(**self.eval_datasetinputs.as_dict())
elif self.image_dataset_type == "panoptic":
self.eval_image_dataset = PanopticImageDataset(**self.eval_datasetinputs.as_dict())
self.eval_dataloader = FixedIndicesEvalDataloader(
image_dataset=self.eval_image_dataset,
intrinsics=self.eval_datasetinputs.intrinsics,
camera_to_world=self.eval_datasetinputs.camera_to_world,
num_rays_per_chunk=self.eval_num_rays_per_chunk,
image_indices=self.eval_image_indices,
device=self.device,
)
def next_train(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data from the train dataloader.
The RayBundle can be shaped in whatever way."""
self.train_count += 1
image_batch = next(self.iter_train_image_sampler)
batch = self.train_pixel_sampler.sample(image_batch)
ray_indices = batch["indices"]
ray_bundle = self.train_ray_generator.forward(ray_indices)
return ray_bundle, batch
def next_eval(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data from the eval dataloader.
The RayBundle should be shaped like an image."""
self.eval_count += 1
camera_ray_bundle, batch = next(self.eval_dataloader)
return camera_ray_bundle, batch
@profiler.time_function
def setup_dataloader(config: DataloaderConfig, device: str, test_mode=False) -> Dataloader:
"""Setup the dataloader."""
dataset_train = instantiate_from_dict_config(config.train_dataset)
train_datasetinputs = dataset_train.get_dataset_inputs(split="train")
dataset_eval = instantiate_from_dict_config(config.eval_dataset)
eval_datasetinputs = dataset_eval.get_dataset_inputs(split="val" if not test_mode else "test")
dataloader: Dataloader = instantiate_from_dict_config(
DictConfig(config),
train_datasetinputs=train_datasetinputs,
eval_datasetinputs=eval_datasetinputs,
device=device,
)
dataloader.to(device)
return dataloader
File renamed without changes.
@@ -25,12 +25,17 @@ import imageio
import numpy as np
import torch
from nerfactory.data.colmap_utils import (
from nerfactory.dataloaders.colmap_utils import (
read_cameras_binary,
read_images_binary,
read_pointsTD_binary,
)
from nerfactory.data.structs import DatasetInputs, PointCloud, SceneBounds, Semantics
from nerfactory.dataloaders.structs import (
DatasetInputs,
PointCloud,
SceneBounds,
Semantics,
)
from nerfactory.utils.colors import get_color
from nerfactory.utils.io import (
get_absolute_path,
+131
View File
@@ -0,0 +1,131 @@
# 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.
"""
Data loader.
"""
import random
from abc import abstractmethod
from typing import Dict, List, Optional, Tuple, Union
from omegaconf import ListConfig
from nerfactory.cameras.cameras import Camera, get_camera
from nerfactory.cameras.rays import RayBundle
from nerfactory.dataloaders.image_dataset import ImageDataset
from nerfactory.utils.misc import get_dict_to_torch
class EvalDataloader: # pylint: disable=too-few-public-methods
"""Evaluation dataloader base class"""
def __init__(
self, image_dataset: ImageDataset, intrinsics, camera_to_world, num_rays_per_chunk: int, device="cpu", **kwargs
):
super().__init__()
self.image_dataset = image_dataset
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
self.num_rays_per_chunk = num_rays_per_chunk
self.device = device
self.kwargs = kwargs
@abstractmethod
def __iter__(self):
"""Iterates over the dataset"""
return self
@abstractmethod
def __next__(self) -> Tuple[RayBundle, Dict]:
"""Returns the next batch of data"""
def get_camera(self, image_idx) -> Camera:
"""Get camera for the given image index"""
intrinsics = self.intrinsics[image_idx].to(self.device)
camera_to_world = self.camera_to_world[image_idx].to(self.device)
camera = get_camera(intrinsics, camera_to_world, camera_index=image_idx)
return camera
def get_data_from_image_idx(self, image_idx) -> Tuple[RayBundle, Dict]:
"""Returns the data for a specific image index."""
camera = self.get_camera(image_idx)
ray_bundle = camera.get_camera_ray_bundle(device=self.device)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
batch = self.image_dataset[image_idx]
batch = get_dict_to_torch(batch, device=self.device)
return ray_bundle, batch
class FixedIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns a fixed set of indices."""
def __init__(
self,
image_dataset: ImageDataset,
intrinsics,
camera_to_world,
num_rays_per_chunk: int,
image_indices: Optional[Union[List[int], ListConfig]] = None,
device="cpu",
**kwargs,
):
"""
Args:
image_dataset: ImageDataset to load data from
image_indices: List of image indices to load data from. If None, then use all images.
"""
super().__init__(image_dataset, intrinsics, camera_to_world, num_rays_per_chunk, device, **kwargs)
if image_indices is None:
self.image_indices = list(range(len(image_dataset)))
else:
self.image_indices = image_indices
self.num_rays_per_chunk = num_rays_per_chunk
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < len(self.image_indices):
image_idx = self.image_indices[self.count]
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
ray_bundle.num_rays_per_chunk = self.num_rays_per_chunk
self.count += 1
return ray_bundle, batch
raise StopIteration
class RandIndicesEvalDataloader(EvalDataloader):
"""Dataloader that returns random images."""
def __init__(
self, image_dataset: ImageDataset, intrinsics, camera_to_world, num_rays_per_chunk: int, device="cpu", **kwargs
):
super().__init__(image_dataset, intrinsics, camera_to_world, num_rays_per_chunk, device, **kwargs)
self.count = 0
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count < 1:
image_indices = range(len(self.camera_to_world))
image_idx = random.choice(image_indices)
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
self.count += 1
return ray_bundle, batch
raise StopIteration
@@ -26,7 +26,7 @@ from PIL import Image
from torch.utils.data import Dataset
from torchtyping import TensorType
from nerfactory.data.structs import Semantics
from nerfactory.dataloaders.structs import Semantics
from nerfactory.utils.misc import is_not_none
@@ -23,7 +23,7 @@ from typing import Union
import torch
from torch.utils.data import IterableDataset, default_collate
from nerfactory.data.image_dataset import ImageDataset
from nerfactory.dataloaders.image_dataset import ImageDataset
from nerfactory.utils.misc import get_dict_to_torch
File renamed without changes.
@@ -139,7 +139,7 @@ class DatasetInputs:
@dataclass
class BaseDataContainer:
class DataloaderOutputs:
"""A container for data that is not specific to any dataset. It should be everything
needed by the renderer and loss calculation. Different datasets and models will probably
need to subclass from this differently, since different Field modules will require different
@@ -153,3 +153,25 @@ class BaseDataContainer:
rays: RayBundle # Raybundle and the cameras will be merged into one thing in a later PR
cameras: torch.Tensor
ground_truth_pixels: Optional[TensorType["num_pixels", 3]] = None
def check_inputs(self, expected_attr: Dict):
"""This will check to make sure that the expected attributes exist.
This will exist in any subclassed version of this"""
for attr in expected_attr:
assert hasattr(self, attr)
@dataclass
class ModelOutputs:
"""A container for outputs from the model.
This will be passed into the loss function along with the base data container. It should be
subclassed for when your model outputs different things.
Args:
rays (RayBundle): The rays for the image.
ground_truth_pixels (TensorType["num_pixels", 3]): The ground truth pixels for the image.
"""
rendered_pixels: Optional[TensorType["num_pixels", 3]] = None
+35 -89
View File
@@ -19,24 +19,16 @@ import functools
import logging
import os
import typing
from typing import Dict, List, Optional
from typing import Dict, List
import torch
import torch.distributed as dist
from torch.cuda.amp.grad_scaler import GradScaler
from torch.nn.parallel import DistributedDataParallel as DDP
from torchtyping import TensorType
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.dataloader import (
EvalDataloader,
TrainDataloader,
setup_dataset_eval,
setup_dataset_train,
)
from nerfactory.data.structs import DatasetInputs
from nerfactory.graphs.base import Graph, setup_graph
from nerfactory.dataloaders.structs import DatasetInputs
from nerfactory.optimizers.optimizers import Optimizers, setup_optimizers
from nerfactory.pipelines.base import Pipeline, setup_pipeline
from nerfactory.utils import profiler, writer
from nerfactory.utils.callbacks import Callback
from nerfactory.utils.config import Config
@@ -67,10 +59,8 @@ class Trainer:
logging.warning("Mixed precision is disabled for CPU training.")
# dataset variables
self.dataset_inputs_train: DatasetInputs
self.dataloader_train: TrainDataloader
self.dataloader_eval: EvalDataloader
# model variables
self.graph: Graph
self.pipeline: Pipeline
self.optimizers: Optimizers
self.start_step = 0
# logging variables
@@ -88,55 +78,45 @@ class Trainer:
Args:
test_mode (bool, optional): Whether to setup for testing. Defaults to False.
"""
self.dataset_inputs_train, self.dataloader_train = setup_dataset_train(self.config.data, device=self.device)
_, self.dataloader_eval = setup_dataset_eval(self.config.data, test_mode=test_mode, device=self.device)
self.graph = setup_graph(self.config.graph, self.dataset_inputs_train, device=self.device)
if not isinstance(self.graph, Graph):
raise ValueError("Graph was improperly initialized.")
self.optimizers = setup_optimizers(self.config.optimizers, self.graph.get_param_groups())
self.pipeline: Pipeline = setup_pipeline(self.config.pipeline, device=self.device, test_mode=test_mode)
self.optimizers = setup_optimizers(self.config.optimizers, self.pipeline.get_param_groups())
self._load_checkpoint()
if self.world_size > 1:
self.graph = typing.cast(Graph, DDP(self.graph, device_ids=[self.local_rank]))
self.pipeline = typing.cast(
Pipeline, typing.cast(Pipeline, DDP(self.pipeline, device_ids=[self.local_rank]))
)
dist.barrier(device_ids=[self.local_rank])
self.callbacks = self.graph.get_training_callbacks()
@classmethod
def get_aggregated_loss(cls, loss_dict: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Returns the aggregated losses and the scalar for calling .backwards() on.
# TODO: move this out to another file/class/etc.
"""
# TODO(ethan): add loss weightings here from a config
# e.g. weighted_losses = map(lambda k: some_weight_dict[k] * loss_dict[k], loss_dict.keys())
weighted_losses = loss_dict.values()
return functools.reduce(torch.add, weighted_losses)
# TODO(ethan): do this for pipeline, not pipeline.model
self.callbacks = self.pipeline.model.get_training_callbacks()
def train(self) -> None:
"""Train the model."""
self.visualizer_state.init_scene(
image_dataset=self.dataloader_train.image_sampler.dataset, dataset_inputs=self.dataset_inputs_train
image_dataset=self.pipeline.dataloader.train_image_dataset,
dataset_inputs=self.pipeline.dataloader.train_datasetinputs,
)
with TimeWriter(writer, EventName.TOTAL_TRAIN_TIME):
num_iterations = self.config.trainer.max_num_iterations
iter_dataloader_train = iter(self.dataloader_train)
for step in range(self.start_step, self.start_step + num_iterations):
with TimeWriter(writer, EventName.ITER_LOAD_TIME, step=step):
ray_indices, batch = next(iter_dataloader_train)
# with TimeWriter(writer, EventName.ITER_LOAD_TIME, step=step):
# ray_indices, batch = next(iter_dataloader_train)
with TimeWriter(writer, EventName.ITER_TRAIN_TIME, step=step) as t:
loss_metric_dict = self.train_iteration(ray_indices, batch, step)
writer.put_scalar(name=EventName.RAYS_PER_SEC, scalar=ray_indices.shape[0] / t.duration, step=step)
loss_metric_dict = self.train_iteration(step)
train_num_rays_per_batch = self.pipeline.dataloader.train_num_rays_per_batch
writer.put_scalar(name=EventName.RAYS_PER_SEC, scalar=train_num_rays_per_batch / t.duration, step=step)
if step != 0 and step % self.config.logging.steps_per_log == 0:
writer.put_dict(name="Loss/train-loss_dict", scalar_dict=loss_metric_dict, step=step)
writer.put_dict(name="Loss/train-loss_metrics_dict", scalar_dict=loss_metric_dict, step=step)
if step != 0 and self.config.trainer.steps_per_save and step % self.config.trainer.steps_per_save == 0:
self._save_checkpoint(self.config.trainer.model_dir, step)
if step % self.config.trainer.steps_per_test == 0:
self.eval_with_dataloader(self.dataloader_eval, step=step)
self.pipeline.get_eval_loss_dict(step=step)
self._write_out_storage(step)
self.visualizer_state.update_scene(step, self.graph)
self.visualizer_state.update_scene(step, self.pipeline.model)
self._write_out_storage(num_iterations)
@@ -155,17 +135,17 @@ class Trainer:
writer.write_out_storage()
def _load_checkpoint(self) -> None:
"""Helper function to load graph and optimizer from prespecified checkpoint"""
"""Helper function to load pipeline and optimizer from prespecified checkpoint"""
load_config = self.config.trainer.resume_train
if load_config.load_dir is not None and load_config.load_step is not None:
load_path = os.path.join(load_config.load_dir, f"step-{load_config.load_step:09d}.ckpt")
assert os.path.exists(load_path), f"Checkpoint {load_path} does not exist"
loaded_state = torch.load(load_path, map_location="cpu")
self.start_step = loaded_state["step"] + 1
# load the checkpoints for graph and optimizer
self.graph.load_graph(loaded_state)
self.optimizers.load_optimizers(loaded_state)
self.grad_scaler.load_state_dict(loaded_state["scaler"])
# load the checkpoints for pipeline, optimizers, and gradient scalar
self.pipeline.load_pipeline(loaded_state["pipeline"])
self.optimizers.load_optimizers(loaded_state["optimizers"])
self.grad_scaler.load_state_dict(loaded_state["scalers"])
logging.info("done loading checkpoint from %s", load_path)
else:
logging.info("No checkpoints to load, training from scratch")
@@ -181,14 +161,14 @@ class Trainer:
if not os.path.exists(output_dir):
os.makedirs(output_dir)
ckpt_path = os.path.join(output_dir, f"step-{step:09d}.ckpt")
if hasattr(self.graph, "module"):
model = self.graph.module.state_dict() # type: ignore
if hasattr(self.pipeline, "module"):
pipeline = self.pipeline.module.state_dict() # type: ignore
else:
model = self.graph.state_dict()
pipeline = self.pipeline.state_dict()
torch.save(
{
"step": step,
"model": model,
"pipeline": pipeline,
"optimizers": {k: v.state_dict() for (k, v) in self.optimizers.optimizers.items()},
"scalers": self.grad_scaler.state_dict(),
},
@@ -196,22 +176,19 @@ class Trainer:
)
@profiler.time_function
def train_iteration(
self, ray_indices: TensorType["num_rays", 3], batch: Dict[str, torch.Tensor], step: int
) -> Dict[str, torch.Tensor]:
def train_iteration(self, step: int) -> Dict[str, torch.Tensor]:
"""Run one iteration with a batch of inputs.
Args:
ray_indices: Contains camera, row, and col indicies for target rays.
batch: Batch of training data.
step: Current training step.
Returns:
Dict[str, float]: Dictionary of model losses and metrics.
Dictionary of model losses.
"""
self.optimizers.zero_grad_all()
with torch.autocast(device_type=ray_indices.device.type, enabled=self.mixed_precision):
_, loss_dict, metrics_dict = self.graph.forward(ray_indices=ray_indices, batch=batch)
cpu_or_cuda_str = self.device.split(":")[0]
with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision):
_, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step)
loss = functools.reduce(torch.add, loss_dict.values())
self.grad_scaler.scale(loss).backward() # type: ignore
self.optimizers.optimizer_scaler_step_all(self.grad_scaler)
@@ -225,34 +202,3 @@ class Trainer:
loss_dict["loss"] = loss
loss_dict.update(metrics_dict)
return loss_dict
@profiler.time_function
def test_image(self, camera_ray_bundle: RayBundle, batch: dict, step: Optional[int] = None) -> float:
"""Test a specific image.
Args:
camera_ray_bundle: Bundle of test rays.
batch: Batch of data.
step: Current training step.
Returns:
float: PSNR
"""
self.graph.eval()
if camera_ray_bundle.camera_indices is None:
raise ValueError("camera_ray_bundle.camera_indices is None during testing")
image_idx = int(camera_ray_bundle.camera_indices[0, 0])
outputs = self.graph.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
psnr = self.graph.log_test_image_outputs(image_idx, step, batch, outputs)
self.graph.train()
return psnr
def eval_with_dataloader(self, dataloader: EvalDataloader, step: Optional[int] = None) -> None:
"""Run evaluation with a given dataloader.
Args:
dataloader: Evaluation dataloader.
step: Current training iteration.
"""
for camera_ray_bundle, batch in dataloader:
self.test_image(camera_ray_bundle, batch, step=step)
+1 -1
View File
@@ -24,7 +24,7 @@ from torch.nn.parameter import Parameter
from torchtyping import TensorType
from nerfactory.cameras.rays import RaySamples
from nerfactory.data.structs import SceneBounds
from nerfactory.dataloaders.structs import SceneBounds
from nerfactory.fields.base import Field
from nerfactory.fields.modules.encoding import Encoding, HashEncoding, SHEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
+94
View File
@@ -0,0 +1,94 @@
# 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.
"""
Semantic NeRF field implementation.
"""
from typing import Dict, Optional, Tuple
import torch
from torch import nn
from torchtyping import TensorType
from nerfactory.cameras.rays import RaySamples
from nerfactory.fields.base import Field
from nerfactory.fields.modules.encoding import Encoding, Identity
from nerfactory.fields.modules.field_heads import (
DensityFieldHead,
FieldHeadNames,
RGBFieldHead,
SemanticFieldHead,
)
from nerfactory.fields.modules.mlp import MLP
class SemanticNerfField(Field):
"""Semantic-NeRF field"""
def __init__(
self,
num_semantic_classes: int,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
) -> None:
super().__init__()
self.num_semantic_classes = num_semantic_classes
self.position_encoding = position_encoding
self.direction_encoding = direction_encoding
self.mlp_base = MLP(
in_dim=self.position_encoding.get_out_dim(),
num_layers=base_mlp_num_layers,
layer_width=base_mlp_layer_width,
skip_connections=skip_connections,
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
num_layers=head_mlp_num_layers,
layer_width=head_mlp_layer_width,
)
self.mlp_semantic = MLP(
in_dim=self.mlp_head.get_out_dim(),
layer_width=self.mlp_head.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
self.field_head_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
self.field_head_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim())
self.field_head_semantic = SemanticFieldHead(
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_classes
)
def get_density(self, ray_samples: RaySamples):
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
base_mlp_out = self.mlp_base(encoded_xyz)
density = self.field_head_density(base_mlp_out)
return density, base_mlp_out
def get_outputs(
self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
) -> Dict[FieldHeadNames, TensorType]:
encoded_dir = self.direction_encoding(ray_samples.frustums.directions)
mlp_out = self.mlp_head(torch.cat([encoded_dir, density_embedding], dim=-1)) # type: ignore
outputs = {}
# rgb
outputs[self.field_head_rgb.field_head_name] = self.field_head_rgb(mlp_out)
# semantic
mlp_out_sem = self.mlp_semantic(mlp_out)
outputs[self.field_head_semantic.field_head_name] = self.field_head_semantic(mlp_out_sem)
return outputs
File renamed without changes.
@@ -13,7 +13,7 @@
# limitations under the License.
"""
The Graph module contains all trainable parameters.
Base Model implementation which takes in RayBundles
"""
from abc import abstractmethod
from collections import defaultdict
@@ -23,15 +23,13 @@ import torch
from omegaconf import DictConfig
from torch import nn
from torch.nn import Parameter
from torchtyping import TensorType
from nerfactory.cameras.cameras import Camera
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.structs import DatasetInputs, SceneBounds
from nerfactory.graphs.modules.ray_generator import RayGenerator
from nerfactory.dataloaders.structs import SceneBounds
from nerfactory.utils import profiler
from nerfactory.utils.callbacks import Callback
from nerfactory.utils.config import GraphConfig
from nerfactory.utils.config import ModelConfig
from nerfactory.utils.misc import (
get_masked_dict,
instantiate_from_dict_config,
@@ -39,16 +37,14 @@ from nerfactory.utils.misc import (
)
class Graph(nn.Module):
"""Graph class
class Model(nn.Module):
"""Model class
Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be
subclassed for custom NeRF model.
Args:
intrinsics: Camera intrinsics.
camera_to_world: Camera to world transformation.
loss_coefficients: Loss specific weights.
scene_bounds: Bounds of target scene.
loss_coefficients: Loss specific weights.
enable_collider: Whether to create a scene collider to filter rays.
collider_config: Configuration of scene collider.
enable_density_field: Whether to create a density field to filter samples.
@@ -57,10 +53,8 @@ class Graph(nn.Module):
def __init__(
self,
intrinsics: torch.Tensor,
camera_to_world: torch.Tensor,
loss_coefficients: DictConfig,
scene_bounds: Optional[SceneBounds] = None,
scene_bounds: SceneBounds,
loss_coefficients: DictConfig = DictConfig({}),
enable_collider: bool = True,
collider_config: Optional[DictConfig] = None,
enable_density_field: bool = False,
@@ -68,19 +62,15 @@ class Graph(nn.Module):
**kwargs,
) -> None:
super().__init__()
assert is_not_none(scene_bounds), "scene_bounds is needed to use the density grid"
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
self.scene_bounds = scene_bounds
self.loss_coefficients = loss_coefficients
self.enable_collider = enable_collider
self.collider_config = collider_config
self.loss_coefficients = loss_coefficients
self.enable_density_field = enable_density_field
self.density_field_config = density_field_config
self.density_field = None
self.kwargs = kwargs
self.collider = None
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
self.populate_density_field()
self.populate_collider()
self.populate_fields()
@@ -91,7 +81,7 @@ class Graph(nn.Module):
@property
def device(self):
"""Returns the device that the graph is on."""
"""Returns the device that the model is on."""
return self.device_indicator_param.device
def get_training_callbacks(self) -> List[Callback]: # pylint:disable=no-self-use
@@ -132,7 +122,7 @@ class Graph(nn.Module):
ray_bundle: Input bundle of rays.
Returns:
Outputs of graph. (ie. rendered colors)
Outputs of model. (ie. rendered colors)
"""
def process_outputs_as_images(self, outputs): # pylint:disable=no-self-use
@@ -144,16 +134,16 @@ class Graph(nn.Module):
outputs[k] = v
@overload
def forward_after_ray_generator(self, ray_bundle: RayBundle, batch: None = None) -> Dict[str, torch.Tensor]:
def forward(self, ray_bundle: RayBundle, batch: None = None) -> Dict[str, torch.Tensor]:
...
@overload
def forward_after_ray_generator(
def forward(
self, ray_bundle: RayBundle, batch: Dict[str, torch.Tensor]
) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
...
def forward_after_ray_generator(
def forward(
self, ray_bundle: RayBundle, batch: Optional[Dict[str, torch.Tensor]] = None
) -> Union[
Dict[str, torch.Tensor], Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]
@@ -189,26 +179,6 @@ class Graph(nn.Module):
loss_dict[loss_name] *= self.loss_coefficients[loss_name]
return outputs, loss_dict, metrics_dict
@overload
def forward(self, ray_indices: TensorType["num_rays", 3], batch: None = None) -> Dict[str, torch.Tensor]:
...
@overload
def forward(
self, ray_indices: TensorType["num_rays", 3], batch: Dict[str, torch.Tensor]
) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
...
def forward(
self, ray_indices: TensorType["num_rays", 3], batch: Optional[Dict[str, torch.Tensor]] = None
) -> Union[
Dict[str, torch.Tensor], Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]
]:
"""Process starting with ray indices. Turns them into rays, then performs volume rendering."""
ray_bundle = self.ray_generator.forward(ray_indices)
x = self.forward_after_ray_generator(ray_bundle, batch=batch)
return x
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
"""Compute and returns metrics."""
# pylint: disable=unused-argument
@@ -221,7 +191,7 @@ class Graph(nn.Module):
@torch.no_grad()
def get_outputs_for_camera_ray_bundle(self, camera_ray_bundle: RayBundle):
"""Takes in camera parameters and computes the output of the graph."""
"""Takes in camera parameters and computes the output of the model."""
assert is_not_none(camera_ray_bundle.num_rays_per_chunk)
image_height, image_width = camera_ray_bundle.origins.shape[:2]
num_rays = len(camera_ray_bundle)
@@ -231,7 +201,7 @@ class Graph(nn.Module):
start_idx = i
end_idx = i + camera_ray_bundle.num_rays_per_chunk
ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
outputs = self.forward_after_ray_generator(ray_bundle=ray_bundle)
outputs = self.forward(ray_bundle=ray_bundle)
for output_name, output in outputs.items(): # type: ignore
outputs_lists[output_name].append(output)
for output_name, outputs_list in outputs_lists.items():
@@ -239,7 +209,7 @@ class Graph(nn.Module):
return outputs
def get_outputs_for_camera(self, camera: Camera):
"""Get the graph outputs for a Camera."""
"""Get the model outputs for a Camera."""
camera_ray_bundle = camera.get_camera_ray_bundle(device=self.device)
return self.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
@@ -252,27 +222,25 @@ class Graph(nn.Module):
image_idx: Index of the image.
step: Current step.
batch: Batch of data.
outputs: Outputs of the graph.
outputs: Outputs of the model.
Returns:
The psnr.
"""
def load_graph(self, loaded_state: Dict[str, Any]) -> None:
def load_model(self, loaded_state: Dict[str, Any]) -> None:
"""Load the checkpoint from the given path"""
state = {key.replace("module.", ""): value for key, value in loaded_state["model"].items()}
self.load_state_dict(state) # type: ignore
@profiler.time_function
def setup_graph(config: GraphConfig, dataset_inputs: DatasetInputs, device: str) -> Graph:
"""Setup the graph. The dataset inputs should be set with the training data.
def setup_model(config: ModelConfig, scene_bounds: SceneBounds, device: str) -> Model:
"""Setup the model. The dataset inputs should be set with the training data.
Args:
dataset_inputs: The inputs which will be used to define the camera parameters.
"""
graph = instantiate_from_dict_config(DictConfig(config), **dataset_inputs.as_dict())
graph.to(device)
if not isinstance(graph, Graph):
raise TypeError(f"Unable to instantiate Graph, got {type(graph)}")
return graph
model = instantiate_from_dict_config(DictConfig(config), scene_bounds=scene_bounds, device=device)
model.to(device)
return model
@@ -28,19 +28,19 @@ import nerfactory.cuda as nerfactory_cuda
from nerfactory.cameras.rays import RayBundle
from nerfactory.fields.instant_ngp_field import field_implementation_to_class
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.graphs.base import Graph
from nerfactory.graphs.modules.ray_sampler import NGPSpacedSampler
from nerfactory.models.base import Model
from nerfactory.models.modules.ray_sampler import NGPSpacedSampler
from nerfactory.optimizers.loss import MSELoss
from nerfactory.utils import colors, misc, visualization, writer
from nerfactory.utils.callbacks import Callback
class NGPGraph(Graph):
"""Instant NGP graph
class NGPModel(Model):
"""Instant NGP model
Args:
field_implementation (str): one of "torch" or "tcnn", or other fields in 'field_implementation_to_class'
kwargs: additional params to pass up to the parent class Graph
kwargs: additional params to pass up to the parent class model
"""
def __init__(self, field_implementation="torch", **kwargs) -> None:
@@ -62,8 +62,6 @@ class NGPGraph(Graph):
def populate_fields(self):
"""Set the fields."""
# torch or tiny-cuda-nn version
if self.scene_bounds is None:
raise ValueError("scene_bounds must be set to use an NGPGraph")
self.field = field_implementation_to_class[self.field_implementation](self.scene_bounds.aabb)
def populate_misc_modules(self):
@@ -142,7 +140,7 @@ class NGPGraph(Graph):
def process_outputs_as_images(self, outputs): # pylint:disable=no-self-use
"""Do preprocessing to make images valid"""
# TODO: make log_test_image_outputs use this directly
# TODO: implement across all the different graph implementations
# TODO: implement across all the different model implementations
outputs["accumulation"] = visualization.apply_colormap(outputs["accumulation"])
outputs["depth"] = visualization.apply_depth_colormap(
outputs["depth"],
@@ -29,8 +29,8 @@ from nerfactory.cameras.rays import RayBundle
from nerfactory.fields.modules.encoding import NeRFEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.fields.nerf_field import NeRFField
from nerfactory.graphs.base import Graph
from nerfactory.graphs.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.models.base import Model
from nerfactory.models.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.optimizers.loss import MSELoss
from nerfactory.renderers.renderers import (
AccumulationRenderer,
@@ -40,13 +40,11 @@ from nerfactory.renderers.renderers import (
from nerfactory.utils import colors, misc, visualization, writer
class MipNerfGraph(Graph):
"""mip-NeRF graph"""
class MipNerfModel(Model):
"""mip-NeRF model"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
near_plane=2.0,
far_plane=6.0,
num_coarse_samples=64,
@@ -58,7 +56,7 @@ class MipNerfGraph(Graph):
self.num_coarse_samples = num_coarse_samples
self.num_importance_samples = num_importance_samples
self.field = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
super().__init__(**kwargs)
def populate_fields(self):
"""Set the fields."""
@@ -30,9 +30,9 @@ from nerfactory.fields.modules.encoding import NeRFEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.fields.modules.spatial_distortions import SceneContraction
from nerfactory.fields.nerf_field import NeRFField
from nerfactory.graphs.base import Graph
from nerfactory.graphs.modules.ray_losses import distortion_loss
from nerfactory.graphs.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.models.base import Model
from nerfactory.models.modules.ray_losses import distortion_loss
from nerfactory.models.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.optimizers.loss import MSELoss
from nerfactory.renderers.renderers import (
AccumulationRenderer,
@@ -42,13 +42,11 @@ from nerfactory.renderers.renderers import (
from nerfactory.utils import colors, misc, visualization, writer
class MipNerf360Graph(Graph):
"""mip-NeRF graph"""
class MipNerf360Model(Model):
"""mip-NeRF model"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
near_plane=2.0,
far_plane=6.0,
num_coarse_samples=64,
@@ -60,7 +58,7 @@ class MipNerf360Graph(Graph):
self.num_coarse_samples = num_coarse_samples
self.num_importance_samples = num_importance_samples
self.field = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
super().__init__(**kwargs)
def populate_fields(self):
"""Set the fields."""
File renamed without changes.
@@ -20,7 +20,7 @@ from torch import nn
from torchtyping import TensorType
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.structs import SceneBounds
from nerfactory.dataloaders.structs import SceneBounds
class SceneBoundsCollider(nn.Module):
@@ -26,8 +26,8 @@ from nerfactory.fields.modules.encoding import NeRFEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.fields.nerf_field import NeRFField
from nerfactory.fields.nerfw_field import VanillaNerfWField
from nerfactory.graphs.base import Graph
from nerfactory.graphs.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.models.base import Model
from nerfactory.models.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.optimizers.loss import MSELoss
from nerfactory.renderers.renderers import (
AccumulationRenderer,
@@ -38,13 +38,11 @@ from nerfactory.renderers.renderers import (
from nerfactory.utils import colors, misc, visualization, writer
class NerfWGraph(Graph):
"""NeRF-W graph"""
class NerfWModel(Model):
"""NeRF-W model"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
near_plane=2.0,
far_plane=6.0,
num_coarse_samples=64,
@@ -52,7 +50,7 @@ class NerfWGraph(Graph):
uncertainty_min=0.03,
**kwargs,
) -> None:
"""A NeRF-W graph.
"""A NeRF-W model.
Args:
...
@@ -68,10 +66,10 @@ class NerfWGraph(Graph):
self.uncertainty_min = uncertainty_min
self.field_coarse = None
self.field_fine = None
self.num_images = len(intrinsics)
self.num_images = 10000 # TODO(ethan): fix this
self.appearance_embedding_dim = 48
self.transient_embedding_dim = 16
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
super().__init__(**kwargs)
def populate_fields(self):
"""Set the fields."""
@@ -120,6 +118,12 @@ class NerfWGraph(Graph):
def get_outputs(self, ray_bundle: RayBundle):
if misc.is_not_none(ray_bundle.camera_indices):
# TODO(ethan): remove this check
assert (
torch.max(ray_bundle.camera_indices) < self.num_images
), "num_images must be greater than the largest camera index"
if self.field_coarse is None or self.field_fine is None:
raise ValueError("populate_fields() must be called before get_outputs")
@@ -16,97 +16,27 @@
Semantic NeRF implementation.
"""
from typing import Dict, Optional, Tuple
import torch
from torch import nn
from torchtyping import TensorType
from nerfactory.cameras.rays import RayBundle, RaySamples
from nerfactory.data.structs import Semantics
from nerfactory.fields.base import Field
from nerfactory.fields.modules.encoding import Encoding, Identity, NeRFEncoding
from nerfactory.fields.modules.field_heads import (
DensityFieldHead,
FieldHeadNames,
RGBFieldHead,
SemanticFieldHead,
)
from nerfactory.fields.modules.mlp import MLP
from nerfactory.cameras.rays import RayBundle
from nerfactory.dataloaders.structs import Semantics
from nerfactory.fields.modules.encoding import NeRFEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.fields.nerf_field import NeRFField
from nerfactory.graphs.vanilla_nerf import NeRFGraph
from nerfactory.fields.semantic_nerf_field import SemanticNerfField
from nerfactory.models.vanilla_nerf import NeRFModel
from nerfactory.renderers.renderers import SemanticRenderer
from nerfactory.utils import misc, writer
class SemanticNerfField(Field):
"""Semantic-NeRF field"""
class SemanticNerfModel(NeRFModel):
"""Semantic-NeRF model"""
def __init__(
self,
num_semantic_classes: int,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
) -> None:
super().__init__()
self.num_semantic_classes = num_semantic_classes
self.position_encoding = position_encoding
self.direction_encoding = direction_encoding
self.mlp_base = MLP(
in_dim=self.position_encoding.get_out_dim(),
num_layers=base_mlp_num_layers,
layer_width=base_mlp_layer_width,
skip_connections=skip_connections,
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
num_layers=head_mlp_num_layers,
layer_width=head_mlp_layer_width,
)
self.mlp_semantic = MLP(
in_dim=self.mlp_head.get_out_dim(),
layer_width=self.mlp_head.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
self.field_head_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
self.field_head_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim())
self.field_head_semantic = SemanticFieldHead(
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_classes
)
def get_density(self, ray_samples: RaySamples):
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
base_mlp_out = self.mlp_base(encoded_xyz)
density = self.field_head_density(base_mlp_out)
return density, base_mlp_out
def get_outputs(
self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
) -> Dict[FieldHeadNames, TensorType]:
encoded_dir = self.direction_encoding(ray_samples.frustums.directions)
mlp_out = self.mlp_head(torch.cat([encoded_dir, density_embedding], dim=-1)) # type: ignore
outputs = {}
# rgb
outputs[self.field_head_rgb.field_head_name] = self.field_head_rgb(mlp_out)
# semantic
mlp_out_sem = self.mlp_semantic(mlp_out)
outputs[self.field_head_semantic.field_head_name] = self.field_head_semantic(mlp_out_sem)
return outputs
class SemanticNerfGraph(NeRFGraph):
"""Semantic-NeRF graph"""
def __init__(self, intrinsics, camera_to_world, semantics: Semantics, **kwargs) -> None:
def __init__(self, semantics: Semantics, **kwargs) -> None:
self.stuff_classes = semantics.stuff_classes
self.stuff_colors = semantics.stuff_colors
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
super().__init__(**kwargs)
def populate_fields(self):
"""Set the fields."""
File renamed without changes.
@@ -30,8 +30,8 @@ from nerfactory.cameras.rays import RayBundle
from nerfactory.fields.modules.encoding import NeRFEncoding
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.fields.nerf_field import NeRFField
from nerfactory.graphs.base import Graph
from nerfactory.graphs.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.models.base import Model
from nerfactory.models.modules.ray_sampler import PDFSampler, UniformSampler
from nerfactory.optimizers.loss import MSELoss
from nerfactory.renderers.renderers import (
AccumulationRenderer,
@@ -42,24 +42,20 @@ from nerfactory.utils import colors, misc, visualization, writer
from nerfactory.utils.callbacks import Callback
class NeRFGraph(Graph):
"""Vanilla NeRF graph
class NeRFModel(Model):
"""Vanilla NeRF model
Args:
intrinsics (torch.Tensor): Camera intrinsics.
camera_to_world (torch.Tensor): Camera to world transformation.
near_plane (float, optional): Where to start sampling points. Defaults to a distance of 2,
far_plane (float, optional): Where to stop sampling points. Defaults to a distance of 6,
num_coarse_samples (int, optional): Number of samples in coarse field evaluation. Defaults to 64,
num_importance_samples(int, optional): Number of samples in fine field evaluation. Defaults to 64,
enable_density_field (bool): Whether to create a density field to filter samples.
density_field_config (DictConfig): Configuration of density field.
near_plane: Where to start sampling points. Defaults to 2.0.
far_plane: Where to stop sampling points. Defaults to 6.0.
num_coarse_samples: Number of samples in coarse field evaluation. Defaults to 64,
num_importance_samples: Number of samples in fine field evaluation. Defaults to 64,
enable_density_field: Whether to create a density field to filter samples. Defaults to False.
density_field_config: Configuration of density field. Defaults to None.
"""
def __init__(
self,
intrinsics: torch.Tensor,
camera_to_world: torch.Tensor,
near_plane: float = 2.0,
far_plane: float = 6.0,
num_coarse_samples: int = 64,
@@ -75,8 +71,6 @@ class NeRFGraph(Graph):
self.field_coarse = None
self.field_fine = None
super().__init__(
intrinsics=intrinsics,
camera_to_world=camera_to_world,
enable_density_field=enable_density_field,
density_field_config=density_field_config,
**kwargs,
+1 -1
View File
@@ -151,5 +151,5 @@ class Optimizers:
Args:
loaded_state: the state from the previous checkpoint
"""
for k, v in loaded_state["optimizers"].items():
for k, v in loaded_state.items():
self.optimizers[k].load_state_dict(v)
+13
View File
@@ -0,0 +1,13 @@
# 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.
+142
View File
@@ -0,0 +1,142 @@
# 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.
"""
Abstracts for the Pipeline class.
"""
from abc import abstractmethod
from pydoc import locate
from typing import Any, Dict, List, Optional
from torch import nn
from torch.nn import Parameter
from nerfactory.dataloaders.base import Dataloader, setup_dataloader
from nerfactory.models.base import Model, setup_model
from nerfactory.utils import profiler
from nerfactory.utils.config import PipelineConfig
class Pipeline(nn.Module):
"""The intent of this class is to provide a higher level interface for the Model
that will be easy to use for our Trainer class.
This class will contain high level functions for the model like getting the loss
dictionaries and visualization code. It should have ways to get the next iterations
training loss, evaluation loss, and generate whole images for visualization. Each model
class should be 1:1 with a pipeline that can act as a standardized interface and hide
differences in how each model takes in and outputs data.
This class's function is to hide the dataloader and model classes from the trainer,
worrying about:
1) Fetching data with the dataloader
2) Feeding the model the data and fetching the loss
3) (TODO) Visualization
Hopefully this provides a higher level interface for the trainer to use, and
simplifying the model classes, which each may have different forward() methods
and so on.
TODO: For visualizer functionality to be added down the line, we should make sure
that we are still abstracting away the Model from the end user. The visualizer function
should probably be done by adding a new iterator on the base dataloader that will
talk to the actual visualizer. This is probably ideal to have the visualizer be
primarily located in the dataloader (first because it makes sense as the
visualizers main job in this context is to feed in data for the model to load)
so that we can have an easier time ensuring that the visualizer is always
spitting out the same formatted data as for in train / eval.
Args:
model: The model to be used in the pipeline.
dataloader: The dataloader to be used in the pipeline.
loss_coefficients: A dictionary of loss coefficients that will be used
Attributes:
self.dataloader (Dataloader): The dataloader that will be used
self.dataloader_train_iter (Iterator): The iterator for the training dataloader
self.dataloader_eval_iter (Iterator): The iterator for the evaluation dataloader
self.model (Model): The model that will be used
"""
def __init__(self, dataloader: Dataloader, model: Model):
super().__init__()
self.dataloader: Dataloader = dataloader
self.model: Model = model
@property
def device(self):
"""Returns the device that the model is on."""
return self.model.device
@abstractmethod
@profiler.time_function
def get_train_loss_dict(self, step: Optional[int] = None):
"""This function gets your training loss dict. This will be responsible for
getting the next batch of data from the dataloader and interfacing with the
Model class, feeding the data to the model's forward function."""
ray_bundle, batch = self.dataloader.next_train()
model_outputs, loss_dict, metrics_dict = self.model(ray_bundle, batch)
return model_outputs, loss_dict, metrics_dict
@abstractmethod
@profiler.time_function
def get_eval_loss_dict(self, step: Optional[int] = None):
"""This function gets your evaluation loss dict. It needs to get the data
from the dataloader and feed it to the model's forward function"""
self.eval()
# NOTE(ethan): next_eval() is not being used right now
for camera_ray_bundle, batch in self.dataloader.eval_dataloader:
image_idx = int(camera_ray_bundle.camera_indices[0, 0])
outputs = self.model.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
psnr = self.model.log_test_image_outputs(image_idx, step, batch, outputs)
# TODO(ethan): this function should probably return something?
self.train()
@abstractmethod
def log_test_image_outputs(self) -> None:
"""Log the test image outputs"""
def load_pipeline(self, loaded_state: Dict[str, Any]) -> None:
"""Load the checkpoint from the given path"""
state = {key.replace("module.", ""): value for key, value in loaded_state.items()}
self.load_state_dict(state) # type: ignore
def get_param_groups(self) -> Dict[str, List[Parameter]]:
"""Get the param groups for the pipeline.
Returns:
A list of dictionaries containing the pipeline's param groups.
"""
dataloader_params = self.dataloader.get_param_groups()
model_params = self.model.get_param_groups()
# TODO(ethan): assert that key names don't overlap
return {**dataloader_params, **model_params}
@profiler.time_function
def setup_pipeline(config: PipelineConfig, device: str, test_mode=False) -> Pipeline:
"""Setup the pipeline. The dataset inputs should be set with the training data.
Args:
config: The pipeline config.
"""
# dataset_inputs
dataloader: Dataloader = setup_dataloader(config.dataloader, device=device, test_mode=test_mode)
# TODO(ethan): get rid of scene_bounds from the model
model: Model = setup_model(config.model, scene_bounds=dataloader.train_datasetinputs.scene_bounds, device=device)
pipeline_class = locate(config._target_) # pylint: disable=protected-access
pipeline = pipeline_class(dataloader=dataloader, model=model) # type: ignore
return pipeline
+17
View File
@@ -0,0 +1,17 @@
# 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.
"""
Pipeline for pixel nerf.
"""
+24 -25
View File
@@ -15,7 +15,7 @@
"""Structured config classes"""
from dataclasses import dataclass
from typing import Any, Dict, Optional
from typing import Any, Dict, List, Optional
from omegaconf import MISSING, DictConfig
@@ -62,29 +62,21 @@ class TrainerConfig:
@dataclass
class ImageDatasetConfig:
"""Configuration for type of dataset to instantiate"""
_target_: str = MISSING
@dataclass
class DataConfig:
class DataloaderConfig:
"""Configuration for train/eval datasets"""
dataset_inputs_train: Dict[str, Any] = MISSING
image_dataset_train: ImageDatasetConfig = MISSING
dataloader_train: Dict[str, Any] = MISSING
dataset_inputs_eval: Dict[str, Any] = MISSING
image_dataset_eval: ImageDatasetConfig = MISSING
dataloader_eval: Dict[str, Any] = MISSING
# additional optional parameters here
pixel_sampler: Optional[Dict[str, Any]] = None
use_preprocessing_cache: bool = False
_target_: str = MISSING
image_dataset_type: Optional[str] = "rgb"
train_dataset: Dict[str, Any] = MISSING
train_num_rays_per_batch: int = MISSING
train_num_images_to_sample_from: int = MISSING
eval_dataset: Dict[str, Any] = MISSING
eval_image_indices: List[int] = MISSING
eval_num_rays_per_chunk: int = MISSING
@dataclass
class GraphConfig:
class ModelConfig:
"""Configuration for graph instantiation"""
_target_: str = MISSING
@@ -99,6 +91,15 @@ class GraphConfig:
density_field_config: Dict[str, Any] = MISSING
@dataclass
class PipelineConfig:
"""Configuration for pipeline instantiation"""
_target_: str = MISSING
dataloader: DataloaderConfig = MISSING
model: ModelConfig = MISSING
@dataclass
class ViewerConfig:
"""Configuration for viewer instantiation"""
@@ -119,10 +120,9 @@ class Config:
trainer: TrainerConfig = MISSING
experiment_name: str = MISSING
method_name: str = MISSING
data: DataConfig = MISSING
graph: GraphConfig = MISSING
optimizers: Dict[str, Any] = MISSING
viewer: ViewerConfig = MISSING
pipeline: PipelineConfig = MISSING
# additional optional parameters here
hydra: Optional[Dict[str, Any]] = None
@@ -141,18 +141,17 @@ def setup_config(config: DictConfig) -> Config:
trainer = TrainerConfig(**config.trainer)
experiment_name = config.experiment_name
method_name = config.method_name
data = DataConfig(**config.data)
graph = GraphConfig(**config.graph)
pipeline = PipelineConfig(**config.pipeline)
optimizers = config.optimizers
viewer = ViewerConfig(**config.viewer)
return Config(
machine=machine,
logging=logging,
trainer=trainer,
experiment_name=experiment_name,
method_name=method_name,
data=data,
graph=graph,
pipeline=pipeline,
optimizers=optimizers,
viewer=viewer,
)
+3
View File
@@ -128,6 +128,9 @@ def make_dir(filename_or_folder: str) -> str:
Args:
filename_or_folder (str): The filename or folder to make.
Returns:
The filename_or_folder, which is the input.
"""
if filename_or_folder[-1] != "/" and filename_or_folder.find(".") < 0:
folder = os.path.dirname(filename_or_folder + "/")
+3
View File
@@ -82,6 +82,9 @@ def instantiate_from_dict_config(dict_config: Any, **kwargs):
"""
dict_config_kwargs = {k: v for k, v in dict_config.items() if k != "_target_"}
uninstantiated_class = locate(dict_config._target_) # pylint: disable=protected-access
assert (
uninstantiated_class is not None
), f"Could not find class {dict_config._target_}" # pylint: disable=protected-access
all_kwargs = dict_config_kwargs
all_kwargs.update(kwargs)
instantiated_class = uninstantiated_class(**all_kwargs) # type: ignore
@@ -1,6 +1,6 @@
import React, { createContext, useContext, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useDispatch } from 'react-redux';
import { WebSocketContext } from '../WebSocket/WebSocket';
const WebRtcContext = createContext(null);
@@ -74,12 +74,15 @@ export default function WebRtcWindow() {
pcRef.current
.createOffer()
.then((offer) => {
console.log('[webrtc] created offer');
return pcRef.current.setLocalDescription(offer);
})
.then(() => {
console.log('[webrtc] set local description');
// wait for ICE gathering to complete
return new Promise((resolve) => {
if (pcRef.current.iceGatheringState === 'complete') {
console.log('[webrtc] ICE gathering complete');
resolve();
} else {
const checkState = () => {
@@ -100,6 +103,7 @@ export default function WebRtcWindow() {
})
.then(() => {
// send the offer
console.log('[webrtc] sending offer');
const offer = pcRef.current.localDescription;
const cmd = 'offer';
const path = '';
@@ -129,6 +133,7 @@ export default function WebRtcWindow() {
websocket.addEventListener('open', () => {
// connect webrtc when the websocket is connected
pcRef.current = getRTCPeerConnection();
console.log('sending offer');
sendOffer();
});
}, []); // empty dependency array means only run once
+6 -6
View File
@@ -26,9 +26,9 @@ import torch
from nerfactory.cameras.cameras import get_camera, get_intrinsics_from_intrinsics_matrix
from nerfactory.cameras.rays import RayBundle
from nerfactory.data.image_dataset import ImageDataset
from nerfactory.data.structs import DatasetInputs
from nerfactory.graphs.base import Graph
from nerfactory.dataloaders.image_dataset import ImageDataset
from nerfactory.dataloaders.structs import DatasetInputs
from nerfactory.models.base import Model
from nerfactory.utils import profiler
from nerfactory.utils.config import ViewerConfig
from nerfactory.utils.decorators import check_visualizer_enabled, decorate_all
@@ -64,7 +64,7 @@ class RenderThread(threading.Thread):
camera_ray_bundle: input rays to pass through the graph to render out
"""
def __init__(self, state: "VisualizerState", graph: Graph, camera_ray_bundle: RayBundle):
def __init__(self, state: "VisualizerState", graph: Model, camera_ray_bundle: RayBundle):
threading.Thread.__init__(self)
self.state = state
self.graph = graph
@@ -211,7 +211,7 @@ class VisualizerState:
# K = camera.get_intrinsics_matrix()
# set_persp_intrinsics_matrix(self.vis, K.double().numpy())
def update_scene(self, step: int, graph: Graph) -> None:
def update_scene(self, step: int, graph: Model) -> None:
"""updates the scene based on the graph weights
Args:
@@ -291,7 +291,7 @@ class VisualizerState:
self.vis["renderingState/train_eta"].write("Paused")
@profiler.time_function
def _render_image_in_viewer(self, graph: Graph) -> None:
def _render_image_in_viewer(self, graph: Model) -> None:
"""
Draw an image using the current camera pose from the viewer.
The image is sent of a TCP connection and then uses WebRTC to send it to the viewer.