update docstrings and random cleanups (#387)

* fixing docstrings and small nits; up to fileds

* finished adding and fixing docstrings
This commit is contained in:
evonneng authored and GitHub committed 2022-09-10 23:09:44 -07:00
1 parent bd5967461d
commit d50c71ac43
52 files changed
+846 -646

No files matched your search

+32 -19
View File
@@ -40,15 +40,9 @@ class Model(nn.Module):
Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be
subclassed for custom NeRF model.
TODO:
Args:
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.
density_field_config: Configuration of density field.
config: configuration for instantiating model
scene_bounds: dataset scene bounds
"""
config: cfg.ModelConfig
@@ -134,14 +128,13 @@ class Model(nn.Module):
) -> Union[
Dict[str, torch.Tensor], Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]
]:
"""Run forward starting with a ray bundle.
"""Run forward starting with a ray bundle. This outputs different things depending on the configuration
of the model and whether or not the batch is provided (whether or not we are training basically)
This takes in raybundles (containing all the information needed to render that ray...
latents included) and the batch (containing all the auxilury things needed to train
like masks and ground truth pixels).
This outputs different things depending on the configuration of the model and whether or not
the batch is provided (whether or not we are training basically)."""
Args:
ray_bundle: containing all the information needed to render that ray latents included
batch: containing all the auxilury things needed to train like masks and ground truth pixels.
"""
if self.collider is not None:
intersected_ray_bundle = self.collider(ray_bundle) # pylint: disable=not-callable
@@ -169,18 +162,34 @@ class Model(nn.Module):
return outputs, loss_dict, metrics_dict
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
"""Compute and returns metrics."""
"""Compute and returns metrics.
Args:
outputs: the output to compute loss dict to
batch: ground truth batch corresponding to outputs
"""
# pylint: disable=unused-argument
# pylint: disable=no-self-use
return {}
@abstractmethod
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.Tensor]:
"""Computes and returns the losses dict."""
"""Computes and returns the losses dict.
Args:
outputs: the output to compute loss dict to
batch: ground truth batch corresponding to outputs
metrics_dict: collection of metrics to compute
loss_coefficients: list of loss coefficients/weightings to apply
"""
@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."""
"""Takes in camera parameters and computes the output of the model.
Args:
camera_ray_bundle: ray bundle to calculate outputs over
"""
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)
@@ -213,6 +222,10 @@ class Model(nn.Module):
"""
def load_model(self, loaded_state: Dict[str, Any]) -> None:
"""Load the checkpoint from the given path"""
"""Load the checkpoint from the given path
Args:
loaded_state: dictionary of pre-trained model states
"""
state = {key.replace("module.", ""): value for key, value in loaded_state["model"].items()}
self.load_state_dict(state) # type: ignore
+1 -2
View File
@@ -46,8 +46,7 @@ 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 model
config: instant NGP configuration to instantiate model
"""
config: cfg.InstantNGPModelConfig
+5 -1
View File
@@ -42,7 +42,11 @@ from nerfactory.utils import colors, misc, visualization, writer
class MipNerfModel(Model):
"""mip-NeRF model"""
"""mip-NeRF model
Args:
config: MipNerf configuration to instantiate model
"""
def __init__(
self,
+5 -1
View File
@@ -45,7 +45,11 @@ from nerfactory.utils import colors, misc, visualization, writer
class MipNerf360Model(Model):
"""mip-NeRF model"""
"""mip-NeRF model
Args:
config: MipNerf360 configuration to instantiate model
"""
def __init__(
self,
+1 -2
View File
@@ -27,8 +27,7 @@ class RayGenerator(nn.Module):
This class will store the intrinsics and extrinsics parameters of the cameras.
Args:
intrinsics: The intrinsics parameters.
camera_to_world: Camera to world transformation matrix.
cameras: Camera objects containing camera info
"""
def __init__(self, cameras: Cameras) -> None:
+1 -4
View File
@@ -23,7 +23,7 @@ from nerfactory.cameras.rays import RaySamples
def distortion_loss(
ray_samples: RaySamples, densities: TensorType["bs":..., "num_samples", 1]
) -> TensorType["bs":..., 1]:
"""Ray baserd distortion loss proposed in MipNeRF-360.
"""Ray baserd distortion loss proposed in MipNeRF-360. Returns distortion Loss.
.. math::
@@ -36,9 +36,6 @@ def distortion_loss(
Args:
ray_samples: Ray samples to compute loss over
densities: Predicted sample densities
Returns:
Distortion Loss.
"""
# Compute the weight at each sample location
+58 -53
View File
@@ -29,7 +29,12 @@ from nerfactory.fields.density_fields.density_grid import DensityGrid
class Sampler(nn.Module):
"""Generate Samples"""
"""Generate Samples
Args:
num_samples: number of samples to take
density_field: density grid specifying weighting of
"""
def __init__(
self, num_samples: int, density_field: Optional[DensityGrid] = None, weight_threshold: float = 0.01
@@ -56,7 +61,16 @@ class Sampler(nn.Module):
class SpacedSampler(Sampler):
"""Sample points according to a function."""
"""Sample points according to a function.
Args:
num_samples: Number of samples per ray
spacing_fn: Function that dictates sample spacing (ie `lambda x : x` is uniform).
spacing_fn_inv: The inverse of spacing_fn.
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
def __init__(
self,
@@ -67,15 +81,6 @@ class SpacedSampler(Sampler):
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
) -> None:
"""
Args:
num_samples: Number of samples per ray
spacing_fn: Function that dictates sample spacing (ie `lambda x : x` is uniform).
spacing_fn_inv: The inverse of spacing_fn.
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
super().__init__(num_samples=num_samples, density_field=density_field, weight_threshold=weight_threshold)
self.train_stratified = train_stratified
self.spacing_fn = spacing_fn
@@ -121,7 +126,14 @@ class SpacedSampler(Sampler):
class UniformSampler(SpacedSampler):
"""Sample uniformly along a ray"""
"""Sample uniformly along a ray
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
def __init__(
self,
@@ -130,13 +142,6 @@ class UniformSampler(SpacedSampler):
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
) -> None:
"""
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
super().__init__(
num_samples=num_samples,
spacing_fn=lambda x: x,
@@ -148,7 +153,14 @@ class UniformSampler(SpacedSampler):
class LinearDisparitySampler(SpacedSampler):
"""Sample linearly in disparity along a ray"""
"""Sample linearly in disparity along a ray
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
def __init__(
self,
@@ -157,13 +169,6 @@ class LinearDisparitySampler(SpacedSampler):
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
) -> None:
"""
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
super().__init__(
num_samples=num_samples,
spacing_fn=lambda x: 1 / x,
@@ -175,7 +180,14 @@ class LinearDisparitySampler(SpacedSampler):
class SqrtSampler(SpacedSampler):
"""Square root sampler along a ray"""
"""Square root sampler along a ray
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
def __init__(
self,
@@ -184,13 +196,6 @@ class SqrtSampler(SpacedSampler):
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
) -> None:
"""
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
super().__init__(
num_samples=num_samples,
spacing_fn=torch.sqrt,
@@ -202,7 +207,14 @@ class SqrtSampler(SpacedSampler):
class LogSampler(SpacedSampler):
"""Log sampler along a ray"""
"""Log sampler along a ray
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
def __init__(
self,
@@ -211,13 +223,6 @@ class LogSampler(SpacedSampler):
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
) -> None:
"""
Args:
num_samples: Number of samples per ray
train_stratified: Use stratified sampling during training. Defults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
"""
super().__init__(
num_samples=num_samples,
spacing_fn=torch.log,
@@ -229,7 +234,16 @@ class LogSampler(SpacedSampler):
class PDFSampler(Sampler):
"""Sample based on probability distribution"""
"""Sample based on probability distribution
Args:
num_samples: Number of samples per ray
train_stratified: Randomize location within each bin during training. Defaults to True
include_original: Add original samples to ray. Defaults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
histogram_padding: Amount to weights prior to computing PDF. Defaults to 0.01.
"""
def __init__(
self,
@@ -240,15 +254,6 @@ class PDFSampler(Sampler):
weight_threshold: float = 1e-2,
histogram_padding: float = 0.01,
) -> None:
"""
Args:
num_samples: Number of samples per ray
train_stratified: Randomize location within each bin during training. Defaults to True
include_original: Add original samples to ray. Defaults to True
density_field: Density grid. If provides, samples below weight_threshold as set as invalid.
weight_threshold: Removes samples below threshold weight. Only used if density field is provided.
histogram_padding: Amount to weights prior to computing PDF. Defaults to 0.01.
"""
super().__init__(num_samples=num_samples, density_field=density_field, weight_threshold=weight_threshold)
self.train_stratified = train_stratified
self.include_original = include_original
+19 -6
View File
@@ -39,7 +39,11 @@ class SceneBoundsCollider(nn.Module):
class AABBBoxCollider(SceneBoundsCollider):
"""Module for colliding rays with the scene bounds to compute near and far values."""
"""Module for colliding rays with the scene bounds to compute near and far values.
Args:
scene_bounds: scene bounds to apply to dataset
"""
def __init__(self, scene_bounds: SceneBounds, **kwargs) -> None:
super().__init__(**kwargs)
@@ -49,12 +53,13 @@ class AABBBoxCollider(SceneBoundsCollider):
def intersect_with_aabb(
cls, rays_o: TensorType["num_rays", 3], rays_d: TensorType["num_rays", 3], aabb: TensorType[2, 3]
):
"""_summary_
"""Returns collection of valid rays within a specified near/far bounding box along with a mask
specifying which rays are valid
Args:
rays_o (torch.tensor): (num_rays, 3)
rays_d (torch.tensor): (num_rays, 3)
aabb (torch.tensor): (2, 3) This is [min point (x,y,z), max point (x,y,z)]
rays_o: (num_rays, 3) ray origins
rays_d: (num_rays, 3) ray directions
aabb: (2, 3) This is [min point (x,y,z), max point (x,y,z)]
"""
# avoid divide by zero
dir_fraction = 1.0 / (rays_d + 1e-6)
@@ -87,6 +92,9 @@ class AABBBoxCollider(SceneBoundsCollider):
def forward(self, ray_bundle: RayBundle) -> RayBundle:
"""Intersects the rays with the scene bounds and updates the near and far values.
Populates nears and fars fields and returns the ray_bundle.
Args:
ray_bundle: specified ray bundle to operate on
"""
aabb = self.scene_bounds.aabb
nears, fars, valid_mask = self.intersect_with_aabb(ray_bundle.origins, ray_bundle.directions, aabb)
@@ -97,7 +105,12 @@ class AABBBoxCollider(SceneBoundsCollider):
class NearFarCollider(SceneBoundsCollider):
"""Sets the nears and fars with fixed values."""
"""Sets the nears and fars with fixed values.
Args:
near_plane: distance to near plane
far_plane: distance to far plane
"""
def __init__(self, near_plane: float, far_plane: float, **kwargs) -> None:
self.near_plane = near_plane
+5 -1
View File
@@ -43,7 +43,11 @@ from nerfactory.utils import colors, misc, visualization, writer
class NerfWModel(Model):
"""NeRF-W model"""
"""NeRF-W model
Args:
config: NerfW configuration to instantiate model
"""
config: cfg.NerfWModelConfig
+6 -1
View File
@@ -34,7 +34,12 @@ from nerfactory.utils import misc, writer
class SemanticNerfModel(NeRFModel):
"""Semantic-NeRF model"""
"""Semantic-NeRF model
Args:
config: SemanticNeRF configuration to instantiate model
semantics: additional semantics data info
"""
def __init__(self, config: cfg.ModelConfig, semantics: Semantics, **kwargs) -> None:
self.stuff_classes = semantics.stuff_classes
+4 -2
View File
@@ -50,8 +50,10 @@ from nerfactory.utils.callbacks import (
class TensoRFModel(Model):
"""
TensoRF Model
"""TensoRF Model
Args:
config: TensoRF configuration to instantiate model
"""
def __init__(
+1 -6
View File
@@ -51,12 +51,7 @@ class NeRFModel(Model):
"""Vanilla NeRF model
Args:
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.
config: Basic NeRF configuration to instantiate model
"""
def __init__(