Typecheck workspace (#231)

This commit is contained in:
Matthew Tancik authored and GitHub committed 2022-07-30 15:38:08 -07:00
1 parent db9d83093a
commit 6c45f72c57
19 files changed
+151 -90

No files matched your search

+27 -16
View File
@@ -17,7 +17,7 @@ The Graph module contains all trainable parameters.
"""
from abc import abstractmethod
from collections import defaultdict
from typing import Any, Dict, List, Union
from typing import Any, Dict, List, Optional, Union
import torch
from omegaconf import DictConfig
@@ -53,7 +53,9 @@ class AbstractGraph(nn.Module):
return self.device_indicator_param.device
@abstractmethod
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
def forward(
self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Optional[Dict[str, torch.Tensor]]] = None
):
"""Process starting with ray indices. Turns them into rays, then performs volume rendering."""
@@ -75,14 +77,14 @@ class Graph(AbstractGraph):
def __init__(
self,
intrinsics: torch.Tensor = None,
camera_to_world: torch.Tensor = None,
loss_coefficients: DictConfig = None,
scene_bounds: SceneBounds = None,
intrinsics: torch.Tensor,
camera_to_world: torch.Tensor,
loss_coefficients: DictConfig,
scene_bounds: Optional[SceneBounds] = None,
enable_collider: bool = True,
collider_config: DictConfig = None,
collider_config: Optional[DictConfig] = None,
enable_density_field: bool = False,
density_field_config: DictConfig = None,
density_field_config: Optional[DictConfig] = None,
**kwargs,
) -> None:
super().__init__()
@@ -122,6 +124,10 @@ class Graph(AbstractGraph):
if self.enable_collider:
self.collider = instantiate_from_dict_config(self.collider_config, scene_bounds=self.scene_bounds)
@abstractmethod
def populate_fields(self):
"""Set the fields."""
@abstractmethod
def populate_misc_modules(self):
"""Initializes any additional modules that are part of the network."""
@@ -135,7 +141,7 @@ class Graph(AbstractGraph):
"""
@abstractmethod
def get_outputs(self, ray_bundle: RayBundle) -> dict:
def get_outputs(self, ray_bundle: RayBundle) -> Dict[str, torch.Tensor]:
"""Takes in a Ray Bundle and returns a dictionary of outputs.
Args:
@@ -153,7 +159,9 @@ class Graph(AbstractGraph):
v = torch.tile(v, (1, 1, 3))
outputs[k] = v
def forward_after_ray_generator(self, ray_bundle: RayBundle, batch: Union[str, Dict[str, torch.tensor]] = None):
def forward_after_ray_generator(
self, ray_bundle: RayBundle, batch: Optional[Union[str, Dict[str, torch.Tensor]]] = None
):
"""Run forward starting with a ray bundle."""
if self.collider is not None:
intersected_ray_bundle = self.collider(ray_bundle)
@@ -185,19 +193,21 @@ class Graph(AbstractGraph):
loss_dict[loss_name] *= self.loss_coefficients[loss_name]
return outputs, loss_dict, metrics_dict
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
def forward(
self, ray_indices: TensorType["num_rays", 3], batch: Optional[Union[str, Dict[str, torch.Tensor]]] = None
):
"""Run the forward starting with ray indices."""
ray_bundle = self.ray_generator.forward(ray_indices)
return self.forward_after_ray_generator(ray_bundle, batch=batch)
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.tensor]:
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
"""Compute and returns metrics."""
# 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]:
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.Tensor]:
"""Computes and returns the losses dict."""
@torch.no_grad()
@@ -213,10 +223,10 @@ class Graph(AbstractGraph):
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)
for output_name, output in outputs.items():
for output_name, output in outputs.items(): # type: ignore
outputs_lists[output_name].append(output)
for output_name, outputs_list in outputs_lists.items():
outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1)
outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore
return outputs
def get_outputs_for_camera(self, camera: Camera):
@@ -230,7 +240,8 @@ class Graph(AbstractGraph):
def load_graph(self, loaded_state: Dict[str, Any]) -> None:
"""Load the checkpoint from the given path"""
self.load_state_dict({key.replace("module.", ""): value for key, value in loaded_state["model"].items()})
state = {key.replace("module.", ""): value for key, value in loaded_state["model"].items()}
self.load_state_dict(state) # type: ignore
@profiler.time_function
+8 -2
View File
@@ -55,13 +55,15 @@ class NGPGraph(Graph):
Callback(
update_every_num_iters=self.density_field.update_every_num_iters,
func=self.density_field.update_density_grid,
density_eval_func=self.field.density_fn,
density_eval_func=self.field.density_fn, # type: ignore
)
]
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):
@@ -78,6 +80,8 @@ class NGPGraph(Graph):
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
if self.field is None:
raise ValueError("populate_fields() must be called before get_param_groups")
param_groups["fields"] = list(self.field.parameters())
return param_groups
@@ -89,6 +93,8 @@ class NGPGraph(Graph):
num_rays = len(ray_bundle)
device = ray_bundle.origins.device
if self.field is None:
raise ValueError("populate_fields() must be called before get_outputs")
ray_samples, packed_info, t_min, t_max = self.sampler(ray_bundle, self.field.aabb)
field_outputs = self.field.forward(ray_samples)
@@ -170,7 +176,7 @@ class NGPGraph(Graph):
lpips = self.lpips(image, rgb)
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(psnr), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(ssim), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(ssim), step=step) # type: ignore
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(lpips), step=step)
writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(psnr), step=step)
+7 -1
View File
@@ -94,10 +94,16 @@ class MipNerfGraph(Graph):
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
if self.field is None:
raise ValueError("populate_fields() must be called before get_param_groups")
param_groups["fields"] = list(self.field.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
if self.field is None:
raise ValueError("populate_fields() must be called before get_outputs")
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
@@ -183,7 +189,7 @@ class MipNerfGraph(Graph):
writer.put_scalar(name=f"psnr/val_{image_idx}-coarse", scalar=float(coarse_psnr), step=step)
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(fine_psnr), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step) # type: ignore
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(fine_lpips), step=step)
writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(fine_psnr), step=step)
+8 -2
View File
@@ -99,10 +99,16 @@ class MipNerf360Graph(Graph):
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
if self.field is None:
raise ValueError("populate_fields() must be called before get_param_groups")
param_groups["fields"] = list(self.field.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
if self.field is None:
raise ValueError("populate_fields() must be called before get_outputs")
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
@@ -143,7 +149,7 @@ class MipNerf360Graph(Graph):
}
return outputs
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.tensor]:
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.Tensor]:
image = batch["image"]
rgb_loss_coarse = self.rgb_loss(image, outputs["rgb_coarse"])
rgb_loss_fine = self.rgb_loss(image, outputs["rgb_fine"])
@@ -195,7 +201,7 @@ class MipNerf360Graph(Graph):
writer.put_scalar(name=f"psnr/val_{image_idx}-coarse", scalar=float(coarse_psnr), step=step)
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(fine_psnr), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step) # type: ignore
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(fine_lpips), step=step)
writer.put_scalar(
name=f"ray_loss_coarse/val_{image_idx}", scalar=float(torch.mean(outputs["ray_loss_coarse"])), step=step
+14 -6
View File
@@ -84,7 +84,7 @@ class SpacedSampler(Sampler):
@torch.no_grad()
def generate_ray_samples(
self,
ray_bundle: RayBundle = None,
ray_bundle: Optional[RayBundle] = None,
num_samples: Optional[int] = None,
) -> RaySamples:
"""Generates position samples accoring to spacing function.
@@ -236,7 +236,7 @@ class PDFSampler(Sampler):
num_samples: int,
train_stratified: bool = True,
include_original: bool = True,
density_field: DensityGrid = None,
density_field: Optional[DensityGrid] = None,
weight_threshold: float = 1e-2,
histogram_padding: float = 0.01,
) -> None:
@@ -257,8 +257,8 @@ class PDFSampler(Sampler):
@torch.no_grad()
def generate_ray_samples(
self,
ray_bundle: RayBundle = None,
ray_samples: RaySamples = None,
ray_bundle: Optional[RayBundle] = None,
ray_samples: Optional[RaySamples] = None,
weights: TensorType[..., "num_samples", 1] = None,
num_samples: Optional[int] = None,
eps: float = 1e-5,
@@ -275,6 +275,10 @@ class PDFSampler(Sampler):
Returns:
Positions and deltas for samples along a ray
"""
if ray_samples is None or ray_bundle is None:
raise ValueError("ray_samples and ray_bundle must be provided")
num_samples = num_samples or self.num_samples
num_bins = num_samples + 1
@@ -370,6 +374,10 @@ class NGPSpacedSampler(Sampler):
Second return contains all the information to recover packed samples into unpacked mode for rendering.
The last two returns are t_min and t_max from ray-aabb test.
"""
if self.density_field is None:
raise ValueError("density_field must be set to use NGPSpacedSampler")
num_samples = num_samples or self.num_samples
aabb = aabb.flatten()
@@ -380,8 +388,8 @@ class NGPSpacedSampler(Sampler):
if t_min is None or t_max is None:
# TODO(ruilongli): this clipping here is stupid. Try to avoid that.
t_min, t_max = nerfactory_cuda.ray_aabb_intersect(rays_o, rays_d, aabb)
t_min = torch.clamp(t_min, max=1e10)
t_max = torch.clamp(t_max, max=1e10)
t_min = torch.clamp(t_min, max=1e10) # type: ignore
t_max = torch.clamp(t_max, max=1e10) # type: ignore
marching_steps = -1 # disable marching mode for now
# TODO(ruilongli): * 16 is for original impl for training. Need to run
+6
View File
@@ -113,10 +113,16 @@ class NerfWGraph(Graph):
def get_param_groups(self):
param_groups = {}
if self.field_coarse is None or self.field_fine is None:
raise ValueError("populate_fields() must be called before get_param_groups")
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
if self.field_coarse is None or self.field_fine is None:
raise ValueError("populate_fields() must be called before get_outputs")
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
+3 -3
View File
@@ -90,7 +90,7 @@ class SemanticNerfField(Field):
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))
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)
@@ -103,7 +103,7 @@ class SemanticNerfField(Field):
class SemanticNerfGraph(NeRFGraph):
"""Semantic-NeRF graph"""
def __init__(self, intrinsics=None, camera_to_world=None, semantics: Semantics = None, **kwargs) -> None:
def __init__(self, intrinsics, camera_to_world, 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)
@@ -185,7 +185,7 @@ class SemanticNerfGraph(NeRFGraph):
def log_test_image_outputs(self, image_idx, step, batch, outputs):
super().log_test_image_outputs(image_idx, step, batch, outputs)
semantic_logits = outputs["semantic_fine"]
semantic_labels = torch.argmax(torch.nn.functional.softmax(semantic_logits, dim=-1), dim=-1)
semantic_labels = torch.argmax(torch.nn.functional.softmax(semantic_logits, dim=-1), dim=-1) # type: ignore
semantic_labels_image = self.stuff_colors[semantic_labels]
writer.put_image(name=f"semantics/image_idx_{image_idx}", image=semantic_labels_image, step=step)
+15 -6
View File
@@ -17,7 +17,7 @@ Implementation of vanilla nerf.
"""
from typing import Dict, List
from typing import Dict, List, Optional
import torch
from omegaconf import DictConfig
@@ -58,14 +58,14 @@ class NeRFGraph(Graph):
def __init__(
self,
intrinsics: torch.Tensor = None,
camera_to_world: torch.Tensor = None,
intrinsics: torch.Tensor,
camera_to_world: torch.Tensor,
near_plane: float = 2.0,
far_plane: float = 6.0,
num_coarse_samples: int = 64,
num_importance_samples: int = 128,
enable_density_field: bool = False,
density_field_config: DictConfig = None,
density_field_config: Optional[DictConfig] = None,
**kwargs,
) -> None:
self.near_plane = near_plane
@@ -83,6 +83,9 @@ class NeRFGraph(Graph):
)
def get_training_callbacks(self) -> List[Callback]:
if self.field_coarse is None:
raise ValueError("populate fields must be called before get_training_callbacks.")
callbacks = []
if self.density_field is not None:
callbacks = [
@@ -127,10 +130,16 @@ class NeRFGraph(Graph):
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
if self.field_coarse is None or self.field_fine is None:
raise ValueError("populate_fields() must be called before get_param_groups")
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
if self.field_coarse is None or self.field_fine is None:
raise ValueError("populate_fields() must be called before get_outputs")
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
@@ -167,7 +176,7 @@ class NeRFGraph(Graph):
}
return outputs
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.tensor]:
def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients) -> Dict[str, torch.Tensor]:
# Scaling metrics by coefficients to create the losses.
device = outputs["rgb_coarse"].device
image = batch["image"].to(device)
@@ -218,7 +227,7 @@ class NeRFGraph(Graph):
writer.put_scalar(name=f"psnr/val_{image_idx}-coarse", scalar=float(coarse_psnr), step=step)
writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(fine_psnr), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step)
writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(fine_ssim), step=step) # type: ignore
writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(fine_lpips), step=step)
writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(fine_psnr), step=step)