mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-07 00:09:14 +08:00
Setting near and far with scene bounds collider. Also LR schedules. (#74)
* some initial cuda code as I learn. using git to save progress. * first cuda kernel for ray sampling that mostly works * cleaning up code. working on lr. structs for scene bounds aabb * added scene bounds collider code * updated setup * setup * setup * black * including some files * exporting env variable * new file * git workflows * github actions * github actions * github actions * removing env var
This commit is contained in:
1 parent
752df417ce
commit
676beebb14
45 files changed
+803
-8354
No files matched your search
Whitespace-only changes.
@@ -10,7 +10,7 @@ import numpy as np
|
||||
import torch
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.dataset.structs import DatasetInputs
|
||||
from mattport.nerf.dataset.structs import DatasetInputs, SceneBounds
|
||||
from mattport.utils.io import load_from_json
|
||||
|
||||
|
||||
@@ -53,12 +53,15 @@ def load_blender_data(
|
||||
intrinsics = torch.ones((num_cameras, num_intrinsics_params), dtype=torch.float32)
|
||||
intrinsics *= torch.tensor([cx, cy, focal_length])
|
||||
|
||||
scene_bounds = SceneBounds(aabb=torch.tensor([[-1, -1, -1], [1, 1, 1]], dtype=torch.float32))
|
||||
|
||||
dataset_inputs = DatasetInputs(
|
||||
image_filenames=image_filenames,
|
||||
downscale_factor=downscale_factor,
|
||||
alpha_color=alpha_color,
|
||||
intrinsics=intrinsics * 1.0 / downscale_factor, # downscaling the intrinsics here
|
||||
camera_to_world=camera_to_world,
|
||||
scene_bounds=scene_bounds,
|
||||
)
|
||||
|
||||
return dataset_inputs
|
||||
File renamed without changes.
@@ -0,0 +1,4 @@
|
||||
"""
|
||||
Code for loading instant-ngp dataset formats.
|
||||
# TODO
|
||||
"""
|
||||
File renamed without changes.
@@ -27,6 +27,17 @@ class Semantics:
|
||||
thing_filenames: List[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class SceneBounds:
|
||||
"""Data to represent the scene bounds.
|
||||
|
||||
aabb: axis-aligned bounding box
|
||||
aabb[0] is the minimum (x,y,z) point. aabb[1] is the maximum (x,y,z) point.
|
||||
"""
|
||||
|
||||
aabb: TensorType[2, 3] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatasetInputs:
|
||||
"""Dataset inputs for the image dataset and the ray generator.
|
||||
@@ -40,9 +51,9 @@ class DatasetInputs:
|
||||
downscale_factor: int = 1
|
||||
intrinsics: torch.tensor = None
|
||||
camera_to_world: torch.tensor = None
|
||||
bounding_box: torch.tensor = None
|
||||
mask_filenames: List[str] = None
|
||||
depth_filenames: List[str] = None
|
||||
scene_bounds: SceneBounds = SceneBounds()
|
||||
semantics: Semantics = Semantics()
|
||||
point_cloud: PointCloud = PointCloud()
|
||||
alpha_color: Optional[TensorType[3]] = None
|
||||
|
||||
@@ -2,38 +2,37 @@
|
||||
For loading the blender dataset format.
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional, Tuple, Union
|
||||
from typing import Optional, Union
|
||||
|
||||
from omegaconf import ListConfig
|
||||
|
||||
from mattport.nerf.dataset.blender import load_blender_data
|
||||
from mattport.nerf.dataset.friends import load_friends_data
|
||||
from mattport.nerf.dataset.format.blender import load_blender_data
|
||||
from mattport.nerf.dataset.format.friends import load_friends_data
|
||||
from mattport.nerf.dataset.structs import DatasetInputs
|
||||
from mattport.structures.colors import get_color
|
||||
from mattport.utils.io import get_absolute_path
|
||||
|
||||
|
||||
def get_dataset_inputs_dict(
|
||||
def get_dataset_inputs(
|
||||
data_directory: str,
|
||||
dataset_type: str,
|
||||
dataset_format: str,
|
||||
split: str,
|
||||
downscale_factor: int = 1,
|
||||
alpha_color: Optional[Union[str, list, ListConfig]] = None,
|
||||
splits: Tuple[str] = ("train", "val"),
|
||||
load_dataset_inputs_from_cache: bool = False,
|
||||
) -> Dict[str, DatasetInputs]:
|
||||
) -> DatasetInputs:
|
||||
"""Returns the dataset inputs, which will be used with an ImageDataset and RayGenerator.
|
||||
# TODO: implement the `test` split, which will have depths and normals, etc.
|
||||
|
||||
Args:
|
||||
data_directory (str): Location of data
|
||||
dataset_type (str): Name of dataset type
|
||||
dataset_format (str): Name of dataset type
|
||||
downscale_factor (int, optional): How much to downscale images. Defaults to 1.0.
|
||||
alpha_color (str, list, optional): Sets transparent regions to specified color, otherwise black.
|
||||
load_from_cache (bool)
|
||||
Returns:
|
||||
Dict[str, DatasetInputs]: The inputs needed for generating rays.
|
||||
DatasetInputs: The inputs needed for generating rays.
|
||||
"""
|
||||
dataset_inputs_dict = {}
|
||||
|
||||
if load_dataset_inputs_from_cache:
|
||||
print("Loading from cache.")
|
||||
@@ -42,16 +41,14 @@ def get_dataset_inputs_dict(
|
||||
if alpha_color is not None:
|
||||
alpha_color = get_color(alpha_color)
|
||||
|
||||
if dataset_type == "blender":
|
||||
for split in splits:
|
||||
dataset_inputs = load_blender_data(
|
||||
get_absolute_path(data_directory),
|
||||
downscale_factor=downscale_factor,
|
||||
split=split,
|
||||
alpha_color=alpha_color,
|
||||
)
|
||||
dataset_inputs_dict[split] = dataset_inputs
|
||||
elif dataset_type == "friends":
|
||||
if dataset_format == "blender":
|
||||
dataset_inputs = load_blender_data(
|
||||
get_absolute_path(data_directory),
|
||||
downscale_factor=downscale_factor,
|
||||
split=split,
|
||||
alpha_color=alpha_color,
|
||||
)
|
||||
elif dataset_format == "friends":
|
||||
# TODO(ethan): change this hack, and do proper splits for the friends dataset
|
||||
# currently we assume that there is only the training set of images
|
||||
dataset_inputs = load_friends_data(
|
||||
@@ -60,15 +57,7 @@ def get_dataset_inputs_dict(
|
||||
split="train",
|
||||
include_point_cloud=False,
|
||||
)
|
||||
for split in splits:
|
||||
dataset_inputs_dict[split] = dataset_inputs
|
||||
else:
|
||||
raise NotImplementedError(f"{dataset_type} is not a valid dataset type")
|
||||
raise NotImplementedError(f"{dataset_format} is not a valid dataset type")
|
||||
|
||||
for split in splits:
|
||||
# save the dataset inputs to cache
|
||||
# TODO:
|
||||
# dataset_inputs_dict[splits].save_to_folder_name()
|
||||
pass
|
||||
|
||||
return dataset_inputs_dict
|
||||
return dataset_inputs
|
||||
@@ -9,7 +9,9 @@ from mattport.nerf.field_modules.base import FieldModule
|
||||
|
||||
|
||||
class Embedding(FieldModule):
|
||||
"""Index into embeddings."""
|
||||
"""Index into embeddings.
|
||||
# TODO: add different types of initializations
|
||||
"""
|
||||
|
||||
def __init__(self, in_dim: int, out_dim: int) -> None:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
Ray generator.
|
||||
"""
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchtyping import TensorType
|
||||
from mattport.nerf.dataset.structs import SceneBounds
|
||||
from mattport.structures.rays import RayBundle
|
||||
|
||||
|
||||
class SceneBoundsCollider(nn.Module):
|
||||
"""Module for setting near and far values for rays."""
|
||||
|
||||
def forward(self, ray_bundle: RayBundle) -> RayBundle:
|
||||
"""To be implemented."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class AABBBoxCollider(SceneBoundsCollider):
|
||||
"""Module for colliding rays with the scene bounds to compute near and far values."""
|
||||
|
||||
def __init__(self, scene_bounds: SceneBounds) -> None:
|
||||
super().__init__()
|
||||
self.scene_bounds = scene_bounds
|
||||
|
||||
@classmethod
|
||||
def intersect_with_aabb(
|
||||
cls, rays_o: TensorType["num_rays", 3], rays_d: TensorType["num_rays", 3], aabb: TensorType[2, 3]
|
||||
):
|
||||
"""_summary_
|
||||
|
||||
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)]
|
||||
"""
|
||||
# avoid divide by zero
|
||||
dir_fraction = 1.0 / (rays_d + 1e-6)
|
||||
|
||||
# x
|
||||
t1 = (aabb[0, 0] - rays_o[:, 0:1]) * dir_fraction[:, 0:1]
|
||||
t2 = (aabb[1, 0] - rays_o[:, 0:1]) * dir_fraction[:, 0:1]
|
||||
# y
|
||||
t3 = (aabb[0, 1] - rays_o[:, 1:2]) * dir_fraction[:, 1:2]
|
||||
t4 = (aabb[1, 1] - rays_o[:, 1:2]) * dir_fraction[:, 1:2]
|
||||
# z
|
||||
t5 = (aabb[0, 2] - rays_o[:, 2:3]) * dir_fraction[:, 2:3]
|
||||
t6 = (aabb[1, 2] - rays_o[:, 2:3]) * dir_fraction[:, 2:3]
|
||||
|
||||
nears = torch.max(
|
||||
torch.cat([torch.minimum(t1, t2), torch.minimum(t3, t4), torch.minimum(t5, t6)], dim=1), dim=1
|
||||
).values
|
||||
fars = torch.min(
|
||||
torch.cat([torch.maximum(t1, t2), torch.maximum(t3, t4), torch.maximum(t5, t6)], dim=1), dim=1
|
||||
).values
|
||||
|
||||
# fars < 0: means the ray is behind the camera
|
||||
# nears > fars: means no intersection
|
||||
valid_mask = ((fars > nears).float() * (fars > 0).float()).bool()
|
||||
nears[nears < 0.0] = 0.0
|
||||
nears[~valid_mask] = 0.0
|
||||
fars[~valid_mask] = 0.0
|
||||
return nears, fars, valid_mask
|
||||
|
||||
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.
|
||||
"""
|
||||
aabb = self.scene_bounds.aabb
|
||||
nears, fars, valid_mask = self.intersect_with_aabb(ray_bundle.origins, ray_bundle.directions, aabb)
|
||||
ray_bundle.nears = nears
|
||||
ray_bundle.fars = fars
|
||||
ray_bundle.valid_mask = valid_mask
|
||||
return ray_bundle
|
||||
|
||||
|
||||
class NearFarCollider(SceneBoundsCollider):
|
||||
"""Sets the nears and fars with fixed values."""
|
||||
|
||||
def __init__(self, near_plane, far_plane) -> None:
|
||||
self.near_plane = near_plane
|
||||
self.far_plane = far_plane
|
||||
super().__init__()
|
||||
|
||||
def forward(self, ray_bundle: RayBundle) -> RayBundle:
|
||||
ones = torch.ones_like(ray_bundle.origins[:, 0])
|
||||
ray_bundle.nears = ones * self.near_plane
|
||||
ray_bundle.fars = ones * self.far_plane
|
||||
ray_bundle.valid_mask = ones.bool()
|
||||
return ray_bundle
|
||||
+39
-11
@@ -12,9 +12,12 @@ from torch import nn
|
||||
from torch.nn import Parameter
|
||||
from torchtyping import TensorType
|
||||
|
||||
from mattport.nerf.dataset.structs import SceneBounds
|
||||
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
||||
from mattport.nerf.field_modules.scene_bounds_collider import AABBBoxCollider
|
||||
from mattport.structures.cameras import get_camera_model
|
||||
from mattport.structures.rays import RayBundle
|
||||
from mattport.utils.misc import get_masked_dict
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -41,13 +44,24 @@ class Node:
|
||||
class Graph(nn.Module):
|
||||
"""_summary_"""
|
||||
|
||||
def __init__(self, intrinsics=None, camera_to_world=None, loss_coefficients: DictConfig = None, **kwargs) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
intrinsics=None,
|
||||
camera_to_world=None,
|
||||
loss_coefficients: DictConfig = None,
|
||||
scene_bounds: SceneBounds = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.intrinsics = intrinsics
|
||||
self.camera_to_world = camera_to_world
|
||||
self.scene_bounds = scene_bounds
|
||||
self.loss_coefficients = loss_coefficients
|
||||
# assert self.scene_bounds is not None
|
||||
self.kwargs = kwargs
|
||||
self.scene_bounds_collider = None
|
||||
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
||||
self.populate_collider()
|
||||
self.populate_modules() # populate the modules
|
||||
|
||||
# to keep track of which device the nn.Module is on
|
||||
@@ -57,6 +71,10 @@ class Graph(nn.Module):
|
||||
"""Returns the device that the torch parameters are on."""
|
||||
return self.device_indicator_param.device
|
||||
|
||||
def populate_collider(self):
|
||||
"""Set the scene bounds collider to use."""
|
||||
self.scene_bounds_collider = AABBBoxCollider(self.scene_bounds)
|
||||
|
||||
@abstractmethod
|
||||
def populate_modules(self):
|
||||
"""Initializes the modules that are part of the network."""
|
||||
@@ -89,13 +107,22 @@ class Graph(nn.Module):
|
||||
|
||||
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
|
||||
"""Forward function that needs to be overridden."""
|
||||
# get the rays:
|
||||
ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
|
||||
outputs = self.get_outputs(ray_bundle)
|
||||
if not isinstance(batch, type(None)):
|
||||
loss_dict = self.get_loss_dict(outputs=outputs, batch=batch)
|
||||
return outputs, loss_dict
|
||||
return outputs
|
||||
# get the rays
|
||||
original_ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
|
||||
intersected_ray_bundle = self.scene_bounds_collider(original_ray_bundle)
|
||||
|
||||
if isinstance(batch, type(None)):
|
||||
# during inference, keep all rays
|
||||
outputs = self.get_outputs(intersected_ray_bundle)
|
||||
return outputs
|
||||
|
||||
# during training, keep only the rays that intersect the scene. discard the rest
|
||||
valid_mask = intersected_ray_bundle.valid_mask
|
||||
masked_intersected_ray_bundle = intersected_ray_bundle.get_masked_ray_bundle(valid_mask)
|
||||
masked_batch = get_masked_dict(batch, valid_mask)
|
||||
outputs = self.get_outputs(masked_intersected_ray_bundle)
|
||||
loss_dict = self.get_loss_dict(outputs=outputs, batch=masked_batch)
|
||||
return outputs, loss_dict
|
||||
|
||||
@abstractmethod
|
||||
def get_loss_dict(self, outputs, batch) -> Dict[str, torch.tensor]:
|
||||
@@ -130,9 +157,10 @@ class Graph(nn.Module):
|
||||
for i in range(0, num_rays, chunk_size):
|
||||
start_idx = i
|
||||
end_idx = i + chunk_size
|
||||
ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
|
||||
ray_bundle.move_to_device(device)
|
||||
outputs = self.get_outputs(ray_bundle)
|
||||
original_ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
|
||||
original_ray_bundle.move_to_device(device)
|
||||
intersected_ray_bundle = self.scene_bounds_collider(original_ray_bundle)
|
||||
outputs = self.get_outputs(intersected_ray_bundle)
|
||||
for output_name, output in outputs.items():
|
||||
outputs_lists[output_name].append(output)
|
||||
for output_name, outputs_list in outputs_lists.items():
|
||||
|
||||
@@ -20,6 +20,7 @@ from mattport.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRend
|
||||
from mattport.nerf.sampler import PDFSampler, UniformSampler
|
||||
from mattport.structures import colors
|
||||
from mattport.structures.rays import RayBundle, RaySamples
|
||||
from mattport.nerf.field_modules.scene_bounds_collider import NearFarCollider
|
||||
from mattport.utils import stats_tracker, visualization, writer
|
||||
|
||||
|
||||
@@ -116,12 +117,13 @@ class NeRFGraph(Graph):
|
||||
self.field_coarse = NeRFField()
|
||||
self.field_fine = NeRFField()
|
||||
|
||||
def populate_collider(self):
|
||||
self.scene_bounds_collider = NearFarCollider(self.near_plane, self.far_plane)
|
||||
|
||||
def populate_modules(self):
|
||||
|
||||
# samplers
|
||||
self.sampler_uniform = UniformSampler(
|
||||
near_plane=self.near_plane, far_plane=self.far_plane, num_samples=self.num_coarse_samples
|
||||
)
|
||||
self.sampler_uniform = UniformSampler(num_samples=self.num_coarse_samples)
|
||||
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
|
||||
|
||||
# field
|
||||
@@ -147,11 +149,13 @@ class NeRFGraph(Graph):
|
||||
Dict[str, List[Parameter]]: Mapping of different parameter groups
|
||||
"""
|
||||
param_groups = {}
|
||||
# param_groups["cameras"] = list(self.ray_generator.parameters())
|
||||
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
|
||||
return param_groups
|
||||
|
||||
def get_outputs(self, ray_bundle: RayBundle):
|
||||
|
||||
# TODO: set the new rays...
|
||||
|
||||
# coarse network:
|
||||
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
||||
|
||||
|
||||
+40
-19
@@ -3,9 +3,29 @@ Optimizers class.
|
||||
"""
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
import numpy as np
|
||||
from hydra.utils import instantiate
|
||||
from omegaconf import DictConfig
|
||||
import torch
|
||||
from torch.nn import Parameter
|
||||
from torch.optim.lr_scheduler import LambdaLR
|
||||
|
||||
from mattport.utils import writer
|
||||
|
||||
|
||||
class ExponentialDecaySchedule(LambdaLR):
|
||||
"""Exponential learning rate decay function."""
|
||||
|
||||
def __init__(self, optimizer, lr_init, lr_final, max_steps) -> None:
|
||||
def func(step):
|
||||
t = np.clip(step / max_steps, 0, 1)
|
||||
log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)
|
||||
multiplier = (
|
||||
log_lerp / lr_init
|
||||
) # divided by lr_init because the multiplier is with the initial learning rate
|
||||
return multiplier
|
||||
|
||||
super().__init__(optimizer, lr_lambda=func)
|
||||
|
||||
|
||||
class Optimizers:
|
||||
@@ -21,33 +41,30 @@ class Optimizers:
|
||||
self.config = config
|
||||
self.optimizers = {}
|
||||
self.schedulers = {}
|
||||
for param_name, params in param_groups.items():
|
||||
optimizer_config = config[param_name].optimizer
|
||||
optimizer = getattr(torch.optim, optimizer_config.type)
|
||||
kwargs = {k: v for k, v in optimizer_config.items() if k != "type"}
|
||||
self.optimizers[param_name] = optimizer(params, **kwargs)
|
||||
if config[param_name].scheduler:
|
||||
scheduler_config = config[param_name].scheduler
|
||||
scheduler = getattr(torch.optim.lr_scheduler, scheduler_config.type)
|
||||
kwargs = {k: v for k, v in scheduler_config.items() if k != "type"}
|
||||
self.schedulers[param_name] = scheduler(self.optimizers[param_name], **kwargs)
|
||||
for param_group_name, params in param_groups.items():
|
||||
lr_init = config[param_group_name].optimizer.lr
|
||||
self.optimizers[param_group_name] = instantiate(config[param_group_name].optimizer, params=params)
|
||||
if config[param_group_name].scheduler:
|
||||
self.schedulers[param_group_name] = instantiate(
|
||||
config[param_group_name].scheduler, optimizer=self.optimizers[param_group_name], lr_init=lr_init
|
||||
)
|
||||
|
||||
def optimizer_step(self, param_name: str) -> None:
|
||||
def optimizer_step(self, param_group_name: str) -> None:
|
||||
"""fetch and step corresponding optimizer
|
||||
|
||||
Args:
|
||||
param_name (str): name of optimizer to step forward
|
||||
param_group_name (str): name of optimizer to step forward
|
||||
"""
|
||||
self.optimizers[param_name].step()
|
||||
self.optimizers[param_group_name].step()
|
||||
|
||||
def scheduler_step(self, param_name: str) -> None:
|
||||
def scheduler_step(self, param_group_name: str) -> None:
|
||||
"""fetch and step corresponding scheduler
|
||||
|
||||
Args:
|
||||
param_name (str): name of scheduler to step forward
|
||||
param_group_name (str): name of scheduler to step forward
|
||||
"""
|
||||
if self.config.param_name.scheduler:
|
||||
self.schedulers[param_name].step()
|
||||
if self.config.param_group_name.scheduler:
|
||||
self.schedulers[param_group_name].step()
|
||||
|
||||
def zero_grad_all(self):
|
||||
"""zero the gradients for all optimizer parameters"""
|
||||
@@ -62,4 +79,8 @@ class Optimizers:
|
||||
|
||||
def scheduler_step_all(self, step):
|
||||
"""Run step for all schedulers."""
|
||||
# TODO: this needs to be implemented
|
||||
for param_group_name, scheduler in self.schedulers.items():
|
||||
scheduler.step()
|
||||
# TODO(ethan): clean this up. why is there indexing into a list?
|
||||
lr = scheduler.get_last_lr()[0]
|
||||
writer.write_event({"name": f"{param_group_name}", "scalar": lr, "step": step, "group": "learning_rate"})
|
||||
+10
-15
@@ -13,7 +13,7 @@ from mattport.structures.rays import RayBundle, RaySamples
|
||||
class UniformSampler(nn.Module):
|
||||
"""Sample uniformly along a ray"""
|
||||
|
||||
def __init__(self, near_plane: float, far_plane: float, num_samples: int, train_stratified=True) -> None:
|
||||
def __init__(self, num_samples: int, train_stratified=True) -> None:
|
||||
"""
|
||||
Args:
|
||||
near_plane (float): Minimum distance along ray to sample
|
||||
@@ -23,8 +23,6 @@ class UniformSampler(nn.Module):
|
||||
"""
|
||||
super().__init__()
|
||||
|
||||
self.near_plane = near_plane
|
||||
self.far_plane = far_plane
|
||||
self.num_samples = num_samples
|
||||
self.train_stratified = train_stratified
|
||||
|
||||
@@ -32,36 +30,33 @@ class UniformSampler(nn.Module):
|
||||
def forward(
|
||||
self,
|
||||
ray_bundle: RayBundle,
|
||||
near_plane: Optional[float] = None,
|
||||
far_plane: Optional[float] = None,
|
||||
num_samples: Optional[int] = None,
|
||||
) -> RaySamples:
|
||||
"""Generates position samples uniformly.
|
||||
|
||||
Args:
|
||||
ray_bundle (RayBundle): Rays to generate samples for
|
||||
TensorType[..., "output_dim"]: A encoded input tensor
|
||||
near_plane (Optional[float]): Minimum distance along ray to sample
|
||||
far_plane (Optional[float]): Maximum distance along ray to sample
|
||||
num_samples (Optional[int]): Number of samples per ray
|
||||
|
||||
Returns:
|
||||
RaySamples: Positions and deltas for samples along a ray
|
||||
"""
|
||||
near_plane = near_plane or self.near_plane
|
||||
far_plane = far_plane or self.far_plane
|
||||
num_samples = num_samples or self.num_samples
|
||||
assert ray_bundle.nears is not None
|
||||
assert ray_bundle.fars is not None
|
||||
|
||||
num_samples = num_samples or self.num_samples
|
||||
num_rays = ray_bundle.origins.shape[0]
|
||||
|
||||
bins = torch.linspace(near_plane, far_plane, num_samples + 1).to(ray_bundle.origins.device) # (num_samples+1)
|
||||
bins = torch.linspace(0.0, 1.0, num_samples + 1).to(ray_bundle.origins.device) # shape (num_samples+1,)
|
||||
bins = ray_bundle.nears[:, None] + bins[None, :] * (
|
||||
ray_bundle.fars[:, None] - ray_bundle.nears[:, None]
|
||||
) # shape (num_rays, num_samples+1)
|
||||
|
||||
if self.train_stratified and self.training:
|
||||
t_rand = torch.rand((num_rays, num_samples), dtype=bins.dtype, device=bins.device)
|
||||
ts = bins[None, :-1] + t_rand * (bins[None, 1:] - bins[None, :-1]) # (num_rays, num_samples)
|
||||
ts = bins[:, :-1] + t_rand * (bins[:, 1:] - bins[:, :-1]) # shape (num_rays, num_samples)
|
||||
else:
|
||||
ts = (bins[1:] + bins[:-1]) / 2
|
||||
ts = ts.unsqueeze(0).repeat(num_rays, 1) # (num_rays, num_samples)
|
||||
ts = (bins[:, 1:] + bins[:, :-1]) / 2
|
||||
|
||||
ray_samples = RaySamples(
|
||||
ts=ts,
|
||||
|
||||
+51
-42
@@ -1,21 +1,22 @@
|
||||
"""
|
||||
Code to train model.
|
||||
"""
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
from pydoc import locate
|
||||
from time import time
|
||||
from typing import Dict
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from hydra.utils import instantiate
|
||||
from omegaconf import DictConfig
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
from mattport.nerf.dataset.collate import CollateIterDataset, collate_batch_size_one
|
||||
from mattport.nerf.dataset.image_dataset import ImageDataset, collate_batch
|
||||
from mattport.nerf.dataset.utils import DatasetInputs, get_dataset_inputs_dict
|
||||
from mattport.nerf.dataset.utils import DatasetInputs, get_dataset_inputs
|
||||
from mattport.nerf.optimizers import Optimizers
|
||||
from mattport.utils import profiler, stats_tracker, writer
|
||||
from mattport.utils.decorators import check_main_thread
|
||||
@@ -55,12 +56,18 @@ class Trainer:
|
||||
profiler.setup_profiler(config.logging)
|
||||
self.device = "cpu" if self.world_size == 0 else f"cuda:{self.local_rank}"
|
||||
|
||||
@profiler.time_function
|
||||
def setup(self, test_mode=False):
|
||||
"""Setup the Trainer by calling other setup functions."""
|
||||
dataset_inputs_dict = get_dataset_inputs_dict(**self.config.data.dataset)
|
||||
self.setup_datasets(dataset_inputs_dict, test_mode=test_mode)
|
||||
self.setup_graph(dataset_inputs_dict["train"])
|
||||
dataset_inputs_train = get_dataset_inputs(**self.config.data.dataset, split="train")
|
||||
if test_mode:
|
||||
dataset_inputs_eval = get_dataset_inputs(**self.config.data.dataset, split="test")
|
||||
else:
|
||||
config_data_dataset_val = copy.deepcopy(self.config.data.dataset)
|
||||
config_data_dataset_val.downscale_factor = self.config.data.val_downscale_factor
|
||||
dataset_inputs_eval = get_dataset_inputs(**config_data_dataset_val, split="val")
|
||||
self.setup_dataset_train(dataset_inputs_train)
|
||||
self.setup_dataset_eval(dataset_inputs_eval)
|
||||
self.setup_graph(dataset_inputs_train)
|
||||
|
||||
def collate_fn(self, batch_list):
|
||||
"""TODO(ethan): I need to replace this.
|
||||
@@ -68,43 +75,39 @@ class Trainer:
|
||||
"""
|
||||
return collate_batch(batch_list, self.config.data.dataloader.num_rays_per_batch, keep_full_image=False)
|
||||
|
||||
def load_test_dataset(self, dataset_inputs_dict, mode):
|
||||
@profiler.time_function
|
||||
def setup_dataset_eval(self, dataset_inputs: DatasetInputs):
|
||||
"""Helper method to load test or val dataset based on test/train mode"""
|
||||
self.val_image_dataset = ImageDataset(
|
||||
image_filenames=dataset_inputs_dict[mode].image_filenames,
|
||||
downscale_factor=dataset_inputs_dict[mode].downscale_factor,
|
||||
alpha_color=dataset_inputs_dict[mode].alpha_color,
|
||||
image_filenames=dataset_inputs.image_filenames,
|
||||
downscale_factor=dataset_inputs.downscale_factor,
|
||||
alpha_color=dataset_inputs.alpha_color,
|
||||
)
|
||||
self.val_image_intrinsics = dataset_inputs_dict[mode].intrinsics
|
||||
self.val_image_camera_to_world = dataset_inputs_dict[mode].camera_to_world
|
||||
self.val_image_intrinsics = dataset_inputs.intrinsics
|
||||
self.val_image_camera_to_world = dataset_inputs.camera_to_world
|
||||
|
||||
@profiler.time_function
|
||||
def setup_datasets(self, dataset_inputs_dict: Dict[str, DatasetInputs], test_mode: bool):
|
||||
def setup_dataset_train(self, dataset_inputs: DatasetInputs):
|
||||
"""_summary_"""
|
||||
if test_mode:
|
||||
# TODO(change "val" to "test")
|
||||
self.load_test_dataset(dataset_inputs_dict, "val")
|
||||
else:
|
||||
self.train_image_dataset = ImageDataset(
|
||||
image_filenames=dataset_inputs_dict["train"].image_filenames,
|
||||
downscale_factor=dataset_inputs_dict["train"].downscale_factor,
|
||||
semantics=dataset_inputs_dict["train"].semantics,
|
||||
alpha_color=dataset_inputs_dict["train"].alpha_color,
|
||||
)
|
||||
self.train_dataset = CollateIterDataset(
|
||||
self.train_image_dataset,
|
||||
collate_fn=self.collate_fn,
|
||||
num_samples_to_collate=self.config.data.dataloader.num_images_to_sample_from,
|
||||
num_times_to_repeat=self.config.data.dataloader.num_times_to_repeat_images,
|
||||
)
|
||||
self.train_dataloader = DataLoader(
|
||||
self.train_dataset,
|
||||
batch_size=1,
|
||||
num_workers=self.config.data.dataloader.num_workers,
|
||||
collate_fn=collate_batch_size_one,
|
||||
pin_memory=True,
|
||||
)
|
||||
self.load_test_dataset(dataset_inputs_dict, "val")
|
||||
self.train_image_dataset = ImageDataset(
|
||||
image_filenames=dataset_inputs.image_filenames,
|
||||
downscale_factor=dataset_inputs.downscale_factor,
|
||||
semantics=dataset_inputs.semantics,
|
||||
alpha_color=dataset_inputs.alpha_color,
|
||||
)
|
||||
self.train_dataset = CollateIterDataset(
|
||||
self.train_image_dataset,
|
||||
collate_fn=self.collate_fn,
|
||||
num_samples_to_collate=self.config.data.dataloader.num_images_to_sample_from,
|
||||
num_times_to_repeat=self.config.data.dataloader.num_times_to_repeat_images,
|
||||
)
|
||||
self.train_dataloader = DataLoader(
|
||||
self.train_dataset,
|
||||
batch_size=1,
|
||||
num_workers=self.config.data.dataloader.num_workers,
|
||||
collate_fn=collate_batch_size_one,
|
||||
pin_memory=True,
|
||||
)
|
||||
|
||||
@profiler.time_function
|
||||
def setup_graph(self, dataset_inputs: DatasetInputs):
|
||||
@@ -113,12 +116,18 @@ class Trainer:
|
||||
Args:
|
||||
dataset_inputs (DatasetInputs): The inputs which will be used to define the camera parameters.
|
||||
"""
|
||||
self.graph = instantiate(
|
||||
self.config.graph.network,
|
||||
# hydra instantiate fails because of scene_bounds, so we are doing the following instead
|
||||
kwargs = {k: v for k, v in self.config.graph.network.items() if k != "_target_"}
|
||||
graph_class = locate(self.config.graph.network._target_) # pylint: disable=protected-access
|
||||
self.graph = graph_class(
|
||||
**kwargs,
|
||||
intrinsics=dataset_inputs.intrinsics,
|
||||
camera_to_world=dataset_inputs.camera_to_world,
|
||||
scene_bounds=dataset_inputs.scene_bounds,
|
||||
stuff_classes=dataset_inputs.semantics.stuff_classes,
|
||||
).to(self.device)
|
||||
)
|
||||
self.graph.to(self.device)
|
||||
|
||||
self.setup_optimizers() # NOTE(ethan): can this be before DDP?
|
||||
|
||||
if self.config.graph.resume_train.load_dir:
|
||||
@@ -223,7 +232,7 @@ class Trainer:
|
||||
if step != 0 and self.config.graph.steps_per_save and step % self.config.graph.steps_per_save == 0:
|
||||
self.save_checkpoint(self.config.graph.model_dir, step)
|
||||
if step % self.config.graph.steps_per_test == 0: # NOTE(ethan): we should still run this in dry-run mode!
|
||||
for image_idx in self.config.data.validation_image_indices:
|
||||
for image_idx in self.config.data.val_image_indices:
|
||||
_ = self.test_image(image_idx=image_idx, step=step)
|
||||
stats_tracker.print_stats(i / num_iterations)
|
||||
|
||||
@@ -241,8 +250,8 @@ class Trainer:
|
||||
loss = loss_dict["aggregated_loss"]
|
||||
self.optimizers.zero_grad_all()
|
||||
loss.backward()
|
||||
self.optimizers.scheduler_step_all(step) # NOTE(ethan): I think the scheduler needs to know what step we are on
|
||||
self.optimizers.optimizer_step_all()
|
||||
self.optimizers.scheduler_step_all(step)
|
||||
return loss_dict
|
||||
|
||||
@profiler.time_function
|
||||
|
||||
Reference in new issue
Block a user