mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-01 05:20:32 +08:00
1 parent
9b0cf2ab16
commit
f910836b8c
13 files changed
+99
-95
No files matched your search
@@ -19,7 +19,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from abc import abstractmethod
|
||||
from typing import Dict, List, Tuple, Union
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
@@ -27,10 +27,11 @@ from torch.nn import Parameter
|
||||
|
||||
from nerfactory.cameras.rays import RayBundle
|
||||
from nerfactory.configs import base as cfg
|
||||
from nerfactory.dataloaders.eval import FixedIndicesEvalDataloader
|
||||
from nerfactory.dataloaders.eval import EvalDataloader, 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.callbacks import TrainingCallback, TrainingCallbackAttributes
|
||||
from nerfactory.utils.misc import IterableWrapper
|
||||
@@ -71,20 +72,28 @@ class Dataloader(nn.Module):
|
||||
get_eval_iterable: utility that gets a clean pythonic iterator for your eval data
|
||||
|
||||
Args:
|
||||
use_train (bool): whether this dataloader is being used for training
|
||||
use_eval (bool): whether this dataloader is being used for evaluation
|
||||
use_train: whether this dataloader is being used for training
|
||||
use_eval: whether this dataloader is being used for evaluation
|
||||
|
||||
Attributes:
|
||||
use_train (bool): whether or not we are using train
|
||||
use_eval (bool): whether or not we are using eval
|
||||
train_count (int): the step number of our train iteration, needs to be incremented manually
|
||||
eval_count (int): the step number of our eval iteration, needs to be incremented manually
|
||||
train_datasetinputs (DatasetInputs): the inputs for the train dataset
|
||||
eval_datasetinputs (DatasetInputs): the inputs for the eval dataset
|
||||
train_image_dataset (ImageDataset): the image dataset for the train dataset
|
||||
|
||||
Additional attributes specific to each subclass are defined in the setuo_train and setup_eval
|
||||
Additional attributes specific to each subclass are defined in the setup_train and setup_eval
|
||||
functions.
|
||||
|
||||
"""
|
||||
|
||||
train_datasetinputs: Optional[DatasetInputs] = None
|
||||
eval_datasetinputs: Optional[DatasetInputs] = None
|
||||
train_image_dataset: Optional[ImageDataset] = None
|
||||
eval_dataloader: Optional[EvalDataloader] = None
|
||||
|
||||
def __init__(self, use_train: bool, use_eval: bool):
|
||||
"""Constructor for the Dataloader class.
|
||||
|
||||
@@ -223,18 +232,21 @@ class VanillaDataloader(Dataloader): # pylint: disable=abstract-method
|
||||
else:
|
||||
logging.info("No eval dataset specified so using train dataset for eval.")
|
||||
dataset_eval = dataset_train
|
||||
self.config.eval_datasetinputs = dataset_eval.get_dataset_inputs(split="val" if not test_mode else "test")
|
||||
self.eval_cameras = self.config.eval_datasetinputs.cameras.to(device)
|
||||
self.eval_datasetinputs = dataset_eval.get_dataset_inputs(split="val" if not test_mode else "test")
|
||||
self.eval_cameras = self.eval_datasetinputs.cameras.to(device)
|
||||
use_train = self.train_datasetinputs is not None
|
||||
use_eval = self.config.eval_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"""
|
||||
assert self.train_datasetinputs is not None
|
||||
if self.config.image_dataset_type == "rgb":
|
||||
self.train_image_dataset = ImageDataset(**self.train_datasetinputs.as_dict())
|
||||
elif self.config.image_dataset_type == "panoptic":
|
||||
self.train_image_dataset = PanopticImageDataset(**self.train_datasetinputs.as_dict())
|
||||
else:
|
||||
raise ValueError(f"Unknown image dataset type {self.config.image_dataset_type}")
|
||||
self.train_image_sampler = CacheImageSampler(
|
||||
self.train_image_dataset,
|
||||
num_images_to_sample_from=self.config.train_num_images_to_sample_from,
|
||||
@@ -246,10 +258,11 @@ class VanillaDataloader(Dataloader): # pylint: disable=abstract-method
|
||||
|
||||
def setup_eval(self):
|
||||
"""Sets up the dataloader for evaluation"""
|
||||
assert self.eval_datasetinputs is not None
|
||||
if self.config.image_dataset_type == "rgb":
|
||||
self.eval_image_dataset = ImageDataset(**self.config.eval_datasetinputs.as_dict())
|
||||
self.eval_image_dataset = ImageDataset(**self.eval_datasetinputs.as_dict())
|
||||
elif self.config.image_dataset_type == "panoptic":
|
||||
self.eval_image_dataset = PanopticImageDataset(**self.config.eval_datasetinputs.as_dict())
|
||||
self.eval_image_dataset = PanopticImageDataset(**self.eval_datasetinputs.as_dict())
|
||||
self.eval_dataloader = FixedIndicesEvalDataloader(
|
||||
image_dataset=self.eval_image_dataset,
|
||||
cameras=self.eval_cameras,
|
||||
@@ -272,5 +285,6 @@ class VanillaDataloader(Dataloader): # pylint: disable=abstract-method
|
||||
"""Returns the next batch of data from the eval dataloader.
|
||||
The RayBundle should be shaped like an image."""
|
||||
self.eval_count += 1
|
||||
assert self.eval_dataloader is not None, "Must setup eval dataloader before calling next_eval"
|
||||
camera_ray_bundle, batch = next(self.eval_dataloader)
|
||||
return camera_ray_bundle, batch
|
||||
@@ -28,13 +28,20 @@ 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"""
|
||||
class EvalDataloader:
|
||||
"""Evaluation dataloader base class
|
||||
|
||||
Args:
|
||||
image_dataset: ImageDataset to load data from
|
||||
cameras: Cameras to use for generating rays
|
||||
num_rays_per_chunk: Number of camera rays to generate per chunk
|
||||
device: Device to load data to
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
image_dataset: ImageDataset,
|
||||
cameras,
|
||||
cameras: Cameras,
|
||||
num_rays_per_chunk: int,
|
||||
device: Union[torch.device, str] = "cpu",
|
||||
**kwargs,
|
||||
@@ -55,15 +62,23 @@ class EvalDataloader: # pylint: disable=too-few-public-methods
|
||||
def __next__(self) -> Tuple[RayBundle, Dict]:
|
||||
"""Returns the next batch of data"""
|
||||
|
||||
def get_camera(self, image_idx) -> Cameras:
|
||||
"""Get camera for the given image index"""
|
||||
def get_camera(self, image_idx: int = 0) -> Cameras:
|
||||
"""Get camera for the given image index
|
||||
|
||||
Args:
|
||||
image_idx: Camera image index
|
||||
"""
|
||||
distortion_params = None
|
||||
if self.cameras.distortion_params is not None:
|
||||
distortion_params = self.cameras.distortion_params[image_idx]
|
||||
|
||||
camera = Cameras(
|
||||
fx=self.cameras.fx[image_idx],
|
||||
fy=self.cameras.fy[image_idx],
|
||||
cx=self.cameras.cx,
|
||||
cy=self.cameras.cy,
|
||||
camera_to_worlds=self.cameras.camera_to_worlds[image_idx],
|
||||
distortion_params=self.cameras.distortion_params[image_idx],
|
||||
distortion_params=distortion_params,
|
||||
camera_type=self.cameras.camera_type,
|
||||
)
|
||||
return camera
|
||||
@@ -93,7 +108,10 @@ class FixedIndicesEvalDataloader(EvalDataloader):
|
||||
"""
|
||||
Args:
|
||||
image_dataset: ImageDataset to load data from
|
||||
cameras: Cameras to use for generating rays
|
||||
num_rays_per_chunk: Number of camera rays to generate per chunk
|
||||
image_indices: List of image indices to load data from. If None, then use all images.
|
||||
device: Device to load data to
|
||||
"""
|
||||
super().__init__(image_dataset, cameras, num_rays_per_chunk, device, **kwargs)
|
||||
if image_indices is None:
|
||||
@@ -118,7 +136,14 @@ class FixedIndicesEvalDataloader(EvalDataloader):
|
||||
|
||||
|
||||
class RandIndicesEvalDataloader(EvalDataloader):
|
||||
"""Dataloader that returns random images."""
|
||||
"""Dataloader that returns random images.
|
||||
|
||||
Args:
|
||||
image_dataset: ImageDataset to load data from
|
||||
cameras: Cameras to use for generating rays
|
||||
num_rays_per_chunk: Number of camera rays to generate per chunk
|
||||
device: Device to load data to
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -24,7 +24,6 @@ import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
from nerfactory.cameras.cameras import Cameras
|
||||
from nerfactory.cameras.rays import RayBundle
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -133,42 +132,3 @@ class DatasetInputs:
|
||||
def as_dict(self) -> dict:
|
||||
"""Returns the dataclass as a dictionary."""
|
||||
return vars(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
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
|
||||
data.
|
||||
|
||||
Args:
|
||||
rays (RayBundle): The rays for the image.
|
||||
ground_truth_pixels (TensorType["num_pixels", 3]): The ground truth pixels for the image.
|
||||
"""
|
||||
|
||||
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
|
||||
@@ -120,6 +120,9 @@ class Trainer:
|
||||
|
||||
def train(self) -> None:
|
||||
"""Train the model."""
|
||||
assert self.pipeline.dataloader.train_datasetinputs is not None, "Missing DatasetInputs"
|
||||
assert self.pipeline.dataloader.train_image_dataset is not None, "Missing ImageDataset"
|
||||
|
||||
self.visualizer_state.init_scene(
|
||||
image_dataset=self.pipeline.dataloader.train_image_dataset,
|
||||
dataset_inputs=self.pipeline.dataloader.train_datasetinputs,
|
||||
|
||||
@@ -50,6 +50,8 @@ class NGPModel(Model):
|
||||
kwargs: additional params to pass up to the parent class model
|
||||
"""
|
||||
|
||||
config: cfg.InstantNGPModelConfig
|
||||
|
||||
def __init__(self, config: cfg.InstantNGPModelConfig, **kwargs) -> None:
|
||||
assert config.field_implementation in field_implementation_to_class
|
||||
self.field = None
|
||||
|
||||
@@ -45,6 +45,8 @@ from nerfactory.utils import colors, misc, visualization, writer
|
||||
class NerfWModel(Model):
|
||||
"""NeRF-W model"""
|
||||
|
||||
config: cfg.NerfWModelConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: cfg.NerfWModelConfig,
|
||||
|
||||
@@ -76,6 +76,7 @@ class Pipeline(nn.Module):
|
||||
self.dataloader: Dataloader = config.dataloader.setup(device=device, test_mode=test_mode)
|
||||
self.dataloader.to(device)
|
||||
# TODO(ethan): get rid of scene_bounds from the model
|
||||
assert self.dataloader.train_datasetinputs is not None, "Missing DatasetInputs"
|
||||
self.model: Model = config.model.setup(scene_bounds=self.dataloader.train_datasetinputs.scene_bounds)
|
||||
self.model.to(device)
|
||||
|
||||
@@ -101,7 +102,9 @@ class Pipeline(nn.Module):
|
||||
from the dataloader and feed it to the model's forward function"""
|
||||
self.eval()
|
||||
# NOTE(ethan): next_eval() is not being used right now
|
||||
assert self.dataloader.eval_dataloader is not None
|
||||
for camera_ray_bundle, batch in self.dataloader.eval_dataloader:
|
||||
assert camera_ray_bundle.camera_indices is not None
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user