mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-03 22:38:48 +08:00
Fixed testing and added graph abstractions (#64)
* abstracted some test logic and actually using test images now * moved logging from trainer to graph * fixing dataset path * refactored instant ngp code to use inheritance * fixed my run_train * fixed data path * fixed data dir
This commit is contained in:
1 parent
e83ce4f61b
commit
5fb3d14304
26 files changed
+8526
-270
No files matched your search
@@ -166,6 +166,7 @@ outputs/
|
|||||||
# Data
|
# Data
|
||||||
data/
|
data/
|
||||||
!configs/data
|
!configs/data
|
||||||
|
data_shared/
|
||||||
|
|
||||||
# Misc
|
# Misc
|
||||||
old/
|
old/
|
||||||
|
|||||||
Vendored
+3
@@ -17,6 +17,9 @@
|
|||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/run_train.py",
|
"program": "scripts/run_train.py",
|
||||||
|
// "env": {
|
||||||
|
// "CUDA_VISIBLE_DEVICES": "8"
|
||||||
|
// },
|
||||||
"console": "integratedTerminal"
|
"console": "integratedTerminal"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ python scripts/run_train.py
|
|||||||
|
|
||||||
# Run with config changes
|
# Run with config changes
|
||||||
python scripts/run_train.py machine_config.num_gpus=1
|
python scripts/run_train.py machine_config.num_gpus=1
|
||||||
|
python scripts/run_train.py data.dataset.downscale_factor=1
|
||||||
|
|
||||||
# Run with different datasets
|
# Run with different datasets
|
||||||
python scripts/run_train.py data/dataset=blender_lego
|
python scripts/run_train.py data/dataset=blender_lego
|
||||||
@@ -82,11 +83,13 @@ direnv allow .
|
|||||||
```
|
```
|
||||||
|
|
||||||
2. To run local **github actions**, you can run:
|
2. To run local **github actions**, you can run:
|
||||||
|
|
||||||
```
|
```
|
||||||
python scripts/debugging/run_actions.py
|
python scripts/debugging/run_actions.py
|
||||||
```
|
```
|
||||||
|
|
||||||
3. To run local **profiling** to get a flame graph, make sure [pyspy](https://github.com/benfred/py-spy) is installed and you can run:
|
3. To run local **profiling** to get a flame graph, make sure [pyspy](https://github.com/benfred/py-spy) is installed and you can run:
|
||||||
|
|
||||||
```
|
```
|
||||||
pip install py-spy
|
pip install py-spy
|
||||||
|
|
||||||
@@ -95,4 +98,10 @@ pip install py-spy
|
|||||||
|
|
||||||
## for live view of functions
|
## for live view of functions
|
||||||
./scripts/debugging/profile.sh -t top -p scripts/run_train.py data/dataset=blender_lego
|
./scripts/debugging/profile.sh -t top -p scripts/run_train.py data/dataset=blender_lego
|
||||||
```
|
```
|
||||||
|
|
||||||
|
4. For debugging with a debugger.
|
||||||
|
|
||||||
|
```
|
||||||
|
ipython --pdb scripts/run_train.py
|
||||||
|
```
|
||||||
@@ -17,6 +17,10 @@ network:
|
|||||||
num_coarse_samples: 64
|
num_coarse_samples: 64
|
||||||
num_importance_samples: 128
|
num_importance_samples: 128
|
||||||
|
|
||||||
|
loss_coefficients: # loss coefficients
|
||||||
|
rgb_loss_coarse: 1.0
|
||||||
|
rgb_loss_fine: 1.0
|
||||||
|
|
||||||
# optimizer options for network
|
# optimizer options for network
|
||||||
param_groups:
|
param_groups:
|
||||||
fields:
|
fields:
|
||||||
|
|||||||
@@ -1,21 +1,9 @@
|
|||||||
# saving model specifications
|
defaults:
|
||||||
model_dir: /tmp/mattport_models/
|
- default_graph.yaml
|
||||||
steps_per_save: null
|
- _self_
|
||||||
steps_per_test: 100
|
|
||||||
max_num_iterations: 1000000
|
|
||||||
|
|
||||||
# pretrained loading options
|
|
||||||
resume_train:
|
|
||||||
load_dir: # pretrained model directory
|
|
||||||
load_step: # pretrained model's step number
|
|
||||||
|
|
||||||
# NOTE(ethan): currently setting to nothing b/c we're still designing the config format...
|
|
||||||
network:
|
network:
|
||||||
_target_: mattport.nerf.graph.instant_ngp.NGPGraph
|
_target_: mattport.nerf.graph.instant_ngp.NGPGraph
|
||||||
near_plane: 1.0
|
|
||||||
far_plane: 6.0
|
|
||||||
num_coarse_samples: 64
|
|
||||||
num_importance_samples: 64
|
|
||||||
|
|
||||||
# optimizer options for network
|
# optimizer options for network
|
||||||
param_groups:
|
param_groups:
|
||||||
@@ -23,7 +11,3 @@ param_groups:
|
|||||||
optimizer:
|
optimizer:
|
||||||
type: Adam
|
type: Adam
|
||||||
lr: 1e-2
|
lr: 1e-2
|
||||||
scheduler:
|
|
||||||
type: StepLR
|
|
||||||
step_size: 30 # Period of learning rate decay.
|
|
||||||
gamma: 0.1 # Multiplicative factor of learning rate decay. Default: 0.1.
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
defaults:
|
||||||
|
- default_graph.yaml
|
||||||
|
- _self_
|
||||||
|
|
||||||
|
network:
|
||||||
|
_target_: mattport.nerf.graph.nerfw.NerfWGraph
|
||||||
@@ -1,23 +1,5 @@
|
|||||||
defaults:
|
defaults:
|
||||||
# This makes the logging module logs colorful
|
- default
|
||||||
- data: default_data.yaml
|
- override graph: instant_ngp_graph
|
||||||
- graph: instant_ngp_graph.yaml
|
- _self_
|
||||||
- logging: default_logging.yaml
|
|
||||||
- override hydra/job_logging: colorlog
|
|
||||||
- override hydra/hydra_logging: colorlog
|
|
||||||
|
|
||||||
hydra:
|
|
||||||
run:
|
|
||||||
# Configure output dir of each experiment programmatically from the arguments
|
|
||||||
# Example "outputs/mnist/classifier/baseline/2021-03-10-141516"
|
|
||||||
dir: outputs/${experiment_name}/${method_name}/${now:%Y-%m-%d_%H%M%S}
|
|
||||||
|
|
||||||
experiment_name: blender_lego
|
|
||||||
method_name: instant_ngp
|
method_name: instant_ngp
|
||||||
|
|
||||||
# machine options
|
|
||||||
machine_config:
|
|
||||||
num_gpus: 1
|
|
||||||
num_machines: 1
|
|
||||||
machine_rank: 0
|
|
||||||
dist_url: auto
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
defaults:
|
defaults:
|
||||||
- default
|
- default
|
||||||
|
|
||||||
dry_run: true
|
dry_run: true
|
||||||
|
|
||||||
@@ -8,7 +8,8 @@ machine_config:
|
|||||||
|
|
||||||
data:
|
data:
|
||||||
dataset:
|
dataset:
|
||||||
data_directory: data/blender/lego_test
|
dataset_type: blender
|
||||||
|
data_directory: tests/data/lego_test
|
||||||
downscale_factor: 8
|
downscale_factor: 8
|
||||||
validation_image_indices: [0]
|
validation_image_indices: [0]
|
||||||
dataloader:
|
dataloader:
|
||||||
@@ -20,4 +21,4 @@ graph:
|
|||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
searchpath:
|
searchpath:
|
||||||
- file://configs
|
- file://configs
|
||||||
@@ -42,12 +42,15 @@ def get_dataset_inputs_dict(
|
|||||||
dataset_inputs = load_blender_data(
|
dataset_inputs = load_blender_data(
|
||||||
get_absolute_path(data_directory),
|
get_absolute_path(data_directory),
|
||||||
downscale_factor=downscale_factor,
|
downscale_factor=downscale_factor,
|
||||||
|
split=split,
|
||||||
alpha_color=alpha_color,
|
alpha_color=alpha_color,
|
||||||
)
|
)
|
||||||
dataset_inputs_dict[split] = dataset_inputs
|
dataset_inputs_dict[split] = dataset_inputs
|
||||||
elif dataset_type == "friends":
|
elif dataset_type == "friends":
|
||||||
for split in splits:
|
for split in splits:
|
||||||
dataset_inputs = load_friends_data(get_absolute_path(data_directory), downscale_factor=downscale_factor)
|
dataset_inputs = load_friends_data(
|
||||||
|
get_absolute_path(data_directory), downscale_factor=downscale_factor, split=split
|
||||||
|
)
|
||||||
dataset_inputs_dict[split] = dataset_inputs
|
dataset_inputs_dict[split] = dataset_inputs
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError(f"{dataset_type} is not a valid dataset type")
|
raise NotImplementedError(f"{dataset_type} is not a valid dataset type")
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ class RayGenerator(nn.Module):
|
|||||||
camera_index = 0
|
camera_index = 0
|
||||||
camera_class = get_camera_model(self.num_intrinsics_params)
|
camera_class = get_camera_model(self.num_intrinsics_params)
|
||||||
camera = camera_class(*self.intrinsics[camera_index].tolist())
|
camera = camera_class(*self.intrinsics[camera_index].tolist())
|
||||||
image_coords = camera.get_image_coords().to(ray_indices.device)
|
image_coords = camera.get_image_coords().to(ray_indices.device) # NOTE(ethan): I can actually avoid this step
|
||||||
coords = image_coords[y, x]
|
coords = image_coords[y, x]
|
||||||
|
|
||||||
ray_bundle = camera_class.generate_rays(intrinsics=intrinsics, camera_to_world=camera_to_world, coords=coords)
|
ray_bundle = camera_class.generate_rays(intrinsics=intrinsics, camera_to_world=camera_to_world, coords=coords)
|
||||||
|
|||||||
@@ -2,13 +2,20 @@
|
|||||||
The Graph module contains all trainable parameters.
|
The Graph module contains all trainable parameters.
|
||||||
"""
|
"""
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
|
from collections import defaultdict
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Optional, Union
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from omegaconf import DictConfig
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torch.nn import Parameter
|
from torch.nn import Parameter
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
|
|
||||||
|
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
||||||
|
from mattport.structures.cameras import get_camera_model
|
||||||
|
from mattport.structures.rays import RayBundle
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class GraphInputs:
|
class GraphInputs:
|
||||||
@@ -34,12 +41,22 @@ class Node:
|
|||||||
class Graph(nn.Module):
|
class Graph(nn.Module):
|
||||||
"""_summary_"""
|
"""_summary_"""
|
||||||
|
|
||||||
def __init__(self, intrinsics=None, camera_to_world=None) -> None:
|
def __init__(self, intrinsics=None, camera_to_world=None, loss_coefficients: DictConfig = None, **kwargs) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.intrinsics = intrinsics
|
self.intrinsics = intrinsics
|
||||||
self.camera_to_world = camera_to_world
|
self.camera_to_world = camera_to_world
|
||||||
|
self.loss_coefficients = loss_coefficients
|
||||||
|
self.kwargs = kwargs
|
||||||
|
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
||||||
self.populate_modules() # populate the modules
|
self.populate_modules() # populate the modules
|
||||||
|
|
||||||
|
# to keep track of which device the nn.Module is on
|
||||||
|
self.device_indicator_param = nn.Parameter(torch.empty(0))
|
||||||
|
|
||||||
|
def get_device(self):
|
||||||
|
"""Returns the device that the torch parameters are on."""
|
||||||
|
return self.device_indicator_param.device
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def populate_modules(self):
|
def populate_modules(self):
|
||||||
"""Initializes the modules that are part of the network."""
|
"""Initializes the modules that are part of the network."""
|
||||||
@@ -67,9 +84,59 @@ class Graph(nn.Module):
|
|||||||
self.get_in_dim(child_node)
|
self.get_in_dim(child_node)
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def forward(self, ray_indices: TensorType["num_rays", 3]):
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
|
"""Takes in a Ray Bundle and returns a dictionary of outputs."""
|
||||||
|
|
||||||
|
def forward(self, ray_indices: TensorType["num_rays", 3], batch: Union[str, Dict[str, torch.tensor]] = None):
|
||||||
"""Forward function that needs to be overridden."""
|
"""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
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_losses(self, batch, graph_outputs):
|
def get_loss_dict(self, outputs, batch) -> Dict[str, torch.tensor]:
|
||||||
"""Computes and returns the losses."""
|
"""Computes and returns the losses."""
|
||||||
|
|
||||||
|
def get_aggregated_loss_from_loss_dict(self, loss_dict):
|
||||||
|
"""Computes the aggregated loss from the loss_dict and the coefficients specified."""
|
||||||
|
aggregated_loss = 0.0
|
||||||
|
for loss_name, loss_value in loss_dict.items():
|
||||||
|
assert loss_name in self.loss_coefficients, f"{loss_name} no in self.loss_coefficients"
|
||||||
|
loss_coefficient = self.loss_coefficients[loss_name]
|
||||||
|
aggregated_loss += loss_coefficient * loss_value
|
||||||
|
return aggregated_loss
|
||||||
|
|
||||||
|
@torch.no_grad()
|
||||||
|
def get_outputs_for_camera(self, intrinsics, camera_to_world, chunk_size=1024):
|
||||||
|
"""Takes in camera parameters and computes the output of the graph."""
|
||||||
|
assert len(intrinsics.shape) == 1
|
||||||
|
num_intrinsics_params = len(intrinsics)
|
||||||
|
camera_class = get_camera_model(num_intrinsics_params)
|
||||||
|
camera = camera_class(*intrinsics.tolist(), camera_to_world=camera_to_world)
|
||||||
|
camera_ray_bundle = camera.generate_camera_rays()
|
||||||
|
image_height, image_width = camera_ray_bundle.origins.shape[:2]
|
||||||
|
|
||||||
|
device = self.get_device()
|
||||||
|
num_rays = camera_ray_bundle.get_num_rays()
|
||||||
|
|
||||||
|
outputs = {}
|
||||||
|
outputs_lists = defaultdict(list)
|
||||||
|
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)
|
||||||
|
for output_name, output in outputs.items():
|
||||||
|
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)
|
||||||
|
return outputs
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def log_test_image_outputs(self, image_idx, step, image, outputs):
|
||||||
|
"""Writes the test image outputs."""
|
||||||
@@ -2,22 +2,13 @@
|
|||||||
Implementation of Instant NGP.
|
Implementation of Instant NGP.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from typing import Dict, List
|
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torch.nn import Parameter
|
|
||||||
from torchtyping import TensorType
|
|
||||||
|
|
||||||
from mattport.nerf.field_modules.encoding import HashEncoding, NeRFEncoding
|
from mattport.nerf.field_modules.encoding import HashEncoding, NeRFEncoding
|
||||||
from mattport.nerf.field_modules.field_heads import DensityFieldHead, FieldHeadNames, RGBFieldHead
|
from mattport.nerf.field_modules.field_heads import DensityFieldHead, RGBFieldHead
|
||||||
from mattport.nerf.field_modules.mlp import MLP
|
from mattport.nerf.field_modules.mlp import MLP
|
||||||
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
from mattport.nerf.graph.vanilla_nerf import NeRFGraph
|
||||||
from mattport.nerf.graph.base import Graph
|
|
||||||
from mattport.nerf.loss import MSELoss
|
|
||||||
from mattport.nerf.renderers import RGBRenderer
|
|
||||||
from mattport.nerf.sampler import PDFSampler, UniformSampler # pylint: disable=unused-import
|
|
||||||
from mattport.structures.rays import RaySamples
|
from mattport.structures.rays import RaySamples
|
||||||
|
|
||||||
|
|
||||||
@@ -72,90 +63,13 @@ class NGPField(nn.Module):
|
|||||||
return field_outputs
|
return field_outputs
|
||||||
|
|
||||||
|
|
||||||
class NGPGraph(Graph):
|
class NGPGraph(NeRFGraph):
|
||||||
"""Vanilla NeRF graph"""
|
"""NeRF-W graph"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, intrinsics=None, camera_to_world=None, **kwargs) -> None:
|
||||||
self,
|
|
||||||
intrinsics=None,
|
|
||||||
camera_to_world=None,
|
|
||||||
near_plane=1.0,
|
|
||||||
far_plane=6.0,
|
|
||||||
num_coarse_samples=64,
|
|
||||||
num_importance_samples=128,
|
|
||||||
**kwargs
|
|
||||||
) -> None:
|
|
||||||
self.near_plane = near_plane
|
|
||||||
self.far_plane = far_plane
|
|
||||||
self.num_coarse_samples = num_coarse_samples
|
|
||||||
self.num_importance_samples = num_importance_samples
|
|
||||||
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
|
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
|
||||||
|
|
||||||
def populate_modules(self):
|
def populate_fields(self):
|
||||||
# ray generator
|
"""Set the fields."""
|
||||||
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
|
||||||
|
|
||||||
# samplers
|
|
||||||
self.sampler_uniform = UniformSampler(
|
|
||||||
near_plane=self.near_plane, far_plane=self.far_plane, num_samples=self.num_coarse_samples
|
|
||||||
)
|
|
||||||
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
|
|
||||||
|
|
||||||
# field
|
|
||||||
self.field_coarse = NGPField()
|
self.field_coarse = NGPField()
|
||||||
self.field_fine = NGPField()
|
self.field_fine = NGPField()
|
||||||
|
|
||||||
# renderers
|
|
||||||
self.renderer_rgb = RGBRenderer()
|
|
||||||
|
|
||||||
# losses
|
|
||||||
self.rgb_loss = MSELoss()
|
|
||||||
|
|
||||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
|
||||||
"""Obtain the parameter groups for the optimizers
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Dict[str, List[Parameter]]: Mapping of different parameter groups
|
|
||||||
"""
|
|
||||||
param_groups = {}
|
|
||||||
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
|
|
||||||
return param_groups
|
|
||||||
|
|
||||||
def forward(self, ray_indices: TensorType["num_rays", 3]):
|
|
||||||
"""Takes in the ray indices and renders out values."""
|
|
||||||
# get the rays:
|
|
||||||
ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
|
|
||||||
# coarse network:
|
|
||||||
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
|
||||||
|
|
||||||
# time coarse network # xyz -> asd
|
|
||||||
coarse_field_outputs = self.field_coarse(uniform_ray_samples) # FieldOutputs
|
|
||||||
# time end coarse network
|
|
||||||
|
|
||||||
coarse_weights = uniform_ray_samples.get_weights(coarse_field_outputs[FieldHeadNames.DENSITY])
|
|
||||||
|
|
||||||
coarse_renderer_outputs = self.renderer_rgb(
|
|
||||||
rgb=coarse_field_outputs[FieldHeadNames.RGB],
|
|
||||||
weights=coarse_weights,
|
|
||||||
) # RendererOutputs
|
|
||||||
# fine network:
|
|
||||||
pdf_ray_samples = self.sampler_pdf(uniform_ray_samples, coarse_weights) # RaySamples
|
|
||||||
fine_field_outputs = self.field_fine(pdf_ray_samples) # FieldOutputs
|
|
||||||
|
|
||||||
fine_weights = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.DENSITY])
|
|
||||||
|
|
||||||
fine_renderer_outputs = self.renderer_rgb(
|
|
||||||
rgb=fine_field_outputs[FieldHeadNames.RGB],
|
|
||||||
weights=fine_weights,
|
|
||||||
) # RendererOutputs
|
|
||||||
# outputs:
|
|
||||||
outputs = {"rgb_coarse": coarse_renderer_outputs.rgb, "rgb_fine": fine_renderer_outputs.rgb}
|
|
||||||
return outputs
|
|
||||||
|
|
||||||
def get_losses(self, batch, graph_outputs):
|
|
||||||
# batch.pixels # (num_rays, 3)
|
|
||||||
losses = {}
|
|
||||||
rgb_loss_coarse = self.rgb_loss(batch["pixels"], graph_outputs["rgb_coarse"])
|
|
||||||
rgb_loss_fine = self.rgb_loss(batch["pixels"], graph_outputs["rgb_fine"])
|
|
||||||
losses = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
|
|
||||||
return losses
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"""
|
||||||
|
NeRF-W (NeRF in the wild) implementation.
|
||||||
|
TODO:
|
||||||
|
"""
|
||||||
|
|
||||||
|
from mattport.nerf.graph.vanilla_nerf import NeRFGraph
|
||||||
|
from mattport.structures.rays import RayBundle
|
||||||
|
|
||||||
|
|
||||||
|
class NerfWGraph(NeRFGraph):
|
||||||
|
"""NeRF-W graph"""
|
||||||
|
|
||||||
|
def __init__(self, intrinsics=None, camera_to_world=None, **kwargs) -> None:
|
||||||
|
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
|
||||||
|
|
||||||
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def get_loss_dict(self, outputs, batch):
|
||||||
|
raise NotImplementedError
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Semantic NeRF implementation.
|
||||||
|
TODO:
|
||||||
|
"""
|
||||||
@@ -8,19 +8,18 @@ from typing import Dict, List, Tuple
|
|||||||
import torch
|
import torch
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torch.nn import Parameter
|
from torch.nn import Parameter
|
||||||
from torchtyping import TensorType
|
|
||||||
|
|
||||||
from mattport.nerf.field_modules.encoding import NeRFEncoding
|
from mattport.nerf.field_modules.encoding import NeRFEncoding
|
||||||
from mattport.nerf.field_modules.field_heads import DensityFieldHead, FieldHeadNames, RGBFieldHead
|
from mattport.nerf.field_modules.field_heads import DensityFieldHead, FieldHeadNames, RGBFieldHead
|
||||||
from mattport.nerf.field_modules.mlp import MLP
|
from mattport.nerf.field_modules.mlp import MLP
|
||||||
from mattport.nerf.field_modules.ray_generator import RayGenerator
|
|
||||||
from mattport.nerf.graph.base import Graph
|
from mattport.nerf.graph.base import Graph
|
||||||
from mattport.nerf.loss import MSELoss
|
from mattport.nerf.loss import MSELoss
|
||||||
|
from mattport.nerf.metrics import get_psnr
|
||||||
from mattport.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
|
from mattport.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
|
||||||
from mattport.nerf.sampler import PDFSampler, UniformSampler
|
from mattport.nerf.sampler import PDFSampler, UniformSampler
|
||||||
from mattport.structures import colors
|
from mattport.structures import colors
|
||||||
from mattport.structures.rays import RaySamples
|
from mattport.structures.rays import RayBundle, RaySamples
|
||||||
from mattport.utils import visualization
|
from mattport.utils import stats_tracker, visualization, writer
|
||||||
|
|
||||||
|
|
||||||
class NeRFField(nn.Module):
|
class NeRFField(nn.Module):
|
||||||
@@ -89,17 +88,22 @@ class NeRFGraph(Graph):
|
|||||||
far_plane=6.0,
|
far_plane=6.0,
|
||||||
num_coarse_samples=64,
|
num_coarse_samples=64,
|
||||||
num_importance_samples=128,
|
num_importance_samples=128,
|
||||||
**kwargs
|
**kwargs,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.near_plane = near_plane
|
self.near_plane = near_plane
|
||||||
self.far_plane = far_plane
|
self.far_plane = far_plane
|
||||||
self.num_coarse_samples = num_coarse_samples
|
self.num_coarse_samples = num_coarse_samples
|
||||||
self.num_importance_samples = num_importance_samples
|
self.num_importance_samples = num_importance_samples
|
||||||
|
self.field_coarse = None
|
||||||
|
self.field_fine = None
|
||||||
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
|
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
|
||||||
|
|
||||||
|
def populate_fields(self):
|
||||||
|
"""Set the fields."""
|
||||||
|
self.field_coarse = NeRFField()
|
||||||
|
self.field_fine = NeRFField()
|
||||||
|
|
||||||
def populate_modules(self):
|
def populate_modules(self):
|
||||||
# ray generator
|
|
||||||
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
|
|
||||||
|
|
||||||
# samplers
|
# samplers
|
||||||
self.sampler_uniform = UniformSampler(
|
self.sampler_uniform = UniformSampler(
|
||||||
@@ -108,8 +112,7 @@ class NeRFGraph(Graph):
|
|||||||
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
|
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
|
||||||
|
|
||||||
# field
|
# field
|
||||||
self.field_coarse = NeRFField()
|
self.populate_fields()
|
||||||
self.field_fine = NeRFField()
|
|
||||||
|
|
||||||
# renderers
|
# renderers
|
||||||
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
|
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
|
||||||
@@ -130,10 +133,7 @@ class NeRFGraph(Graph):
|
|||||||
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
|
param_groups["fields"] = list(self.field_coarse.parameters()) + list(self.field_fine.parameters())
|
||||||
return param_groups
|
return param_groups
|
||||||
|
|
||||||
def forward(self, ray_indices: TensorType["num_rays", 3]):
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
"""Takes in the ray indices and renders out values."""
|
|
||||||
# get the rays:
|
|
||||||
ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
|
|
||||||
# coarse network:
|
# coarse network:
|
||||||
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
|
||||||
|
|
||||||
@@ -190,10 +190,45 @@ class NeRFGraph(Graph):
|
|||||||
}
|
}
|
||||||
return outputs
|
return outputs
|
||||||
|
|
||||||
def get_losses(self, batch, graph_outputs):
|
def get_loss_dict(self, outputs, batch):
|
||||||
# batch.pixels # (num_rays, 3)
|
device = outputs["rgb_coarse"].device
|
||||||
losses = {}
|
pixels = batch["pixels"].to(device)
|
||||||
rgb_loss_coarse = self.rgb_loss(batch["pixels"], graph_outputs["rgb_coarse"])
|
rgb_loss_coarse = self.rgb_loss(pixels, outputs["rgb_coarse"])
|
||||||
rgb_loss_fine = self.rgb_loss(batch["pixels"], graph_outputs["rgb_fine"])
|
rgb_loss_fine = self.rgb_loss(pixels, outputs["rgb_fine"])
|
||||||
losses = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
|
loss_dict = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
|
||||||
return losses
|
loss_dict["aggregated_loss"] = self.get_aggregated_loss_from_loss_dict(loss_dict)
|
||||||
|
return loss_dict
|
||||||
|
|
||||||
|
def log_test_image_outputs(self, image_idx, step, image, outputs):
|
||||||
|
rgb_coarse = outputs["rgb_coarse"]
|
||||||
|
rgb_fine = outputs["rgb_fine"]
|
||||||
|
accumulation_coarse = outputs["accumulation_coarse"]
|
||||||
|
accumulation_fine = outputs["accumulation_fine"]
|
||||||
|
depth_coarse = outputs["depth_coarse"]
|
||||||
|
depth_fine = outputs["depth_fine"]
|
||||||
|
|
||||||
|
combined_image = torch.cat([image, rgb_coarse, rgb_fine], dim=1)
|
||||||
|
writer.write_event(
|
||||||
|
{"name": f"image_idx_{image_idx}-rgb_coarse_fine", "x": combined_image, "step": step, "group": "val_img"}
|
||||||
|
)
|
||||||
|
|
||||||
|
combined_image = torch.cat([accumulation_coarse, accumulation_fine], dim=1)
|
||||||
|
writer.write_event(
|
||||||
|
{"name": f"image_idx_{image_idx}", "x": combined_image, "step": step, "group": "val_accumulation"}
|
||||||
|
)
|
||||||
|
|
||||||
|
combined_image = torch.cat([depth_coarse, depth_fine], dim=1)
|
||||||
|
writer.write_event({"name": f"image_idx_{image_idx}", "x": combined_image, "step": step, "group": "val_depth"})
|
||||||
|
|
||||||
|
coarse_psnr = get_psnr(image, rgb_coarse)
|
||||||
|
writer.write_event(
|
||||||
|
{"name": f"image_idx_{image_idx}", "scalar": float(coarse_psnr), "step": step, "group": "val"}
|
||||||
|
)
|
||||||
|
|
||||||
|
fine_psnr = get_psnr(image, rgb_fine)
|
||||||
|
stats_tracker.update_stats(
|
||||||
|
{"name": stats_tracker.Stats.CURR_TEST_PSNR, "value": float(fine_psnr), "step": step}
|
||||||
|
)
|
||||||
|
writer.write_event(
|
||||||
|
{"name": f"image_idx_{image_idx}-fine_psnr", "scalar": float(fine_psnr), "step": step, "group": "val"}
|
||||||
|
)
|
||||||
@@ -51,6 +51,7 @@ class RGBRenderer(nn.Module):
|
|||||||
rgb = rgb + self.background_color.to(weights.device)[None, ...] * (
|
rgb = rgb + self.background_color.to(weights.device)[None, ...] * (
|
||||||
1.0 - torch.sum(weights, dim=-1)[..., None]
|
1.0 - torch.sum(weights, dim=-1)[..., None]
|
||||||
)
|
)
|
||||||
|
torch.clamp_(rgb, min=0.0, max=1.0)
|
||||||
|
|
||||||
assert torch.max(rgb) <= 1.0
|
assert torch.max(rgb) <= 1.0
|
||||||
assert torch.min(rgb) >= 0.0
|
assert torch.min(rgb) >= 0.0
|
||||||
|
|||||||
+18
-75
@@ -16,7 +16,6 @@ from torch.utils.data import DataLoader
|
|||||||
from mattport.nerf.dataset.collate import CollateIterDataset, collate_batch_size_one
|
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.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_dict
|
||||||
from mattport.nerf.metrics import get_psnr
|
|
||||||
from mattport.nerf.optimizers import Optimizers
|
from mattport.nerf.optimizers import Optimizers
|
||||||
from mattport.utils import profiler, stats_tracker, writer
|
from mattport.utils import profiler, stats_tracker, writer
|
||||||
from mattport.utils.decorators import check_main_thread
|
from mattport.utils.decorators import check_main_thread
|
||||||
@@ -44,6 +43,8 @@ class Trainer:
|
|||||||
self.train_dataset = None
|
self.train_dataset = None
|
||||||
self.train_dataloader = None
|
self.train_dataloader = None
|
||||||
self.val_image_dataset = None
|
self.val_image_dataset = None
|
||||||
|
self.val_image_intrinsics = None
|
||||||
|
self.val_image_camera_to_world = None
|
||||||
# model variables
|
# model variables
|
||||||
self.graph = None
|
self.graph = None
|
||||||
self.optimizers = None
|
self.optimizers = None
|
||||||
@@ -94,6 +95,8 @@ class Trainer:
|
|||||||
downscale_factor=dataset_inputs_dict["val"].downscale_factor,
|
downscale_factor=dataset_inputs_dict["val"].downscale_factor,
|
||||||
alpha_color=dataset_inputs_dict["val"].alpha_color,
|
alpha_color=dataset_inputs_dict["val"].alpha_color,
|
||||||
)
|
)
|
||||||
|
self.val_image_intrinsics = dataset_inputs_dict["val"].intrinsics
|
||||||
|
self.val_image_camera_to_world = dataset_inputs_dict["val"].camera_to_world
|
||||||
|
|
||||||
@profiler.time_function
|
@profiler.time_function
|
||||||
def setup_graph(self, dataset_inputs: DatasetInputs):
|
def setup_graph(self, dataset_inputs: DatasetInputs):
|
||||||
@@ -162,20 +165,20 @@ class Trainer:
|
|||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_aggregated_loss(cls, losses: Dict[str, torch.tensor]):
|
def get_aggregated_loss(cls, loss_dict: Dict[str, torch.tensor]):
|
||||||
"""Returns the aggregated losses and the scalar for calling .backwards() on.
|
"""Returns the aggregated losses and the scalar for calling .backwards() on.
|
||||||
# TODO: move this out to another file/class/etc.
|
# TODO: move this out to another file/class/etc.
|
||||||
"""
|
"""
|
||||||
loss_sum = 0.0
|
loss_sum = 0.0
|
||||||
loss_dict = {}
|
for loss_name in loss_dict.keys():
|
||||||
for loss_name in losses.keys():
|
|
||||||
# TODO(ethan): add loss weightings here from a config
|
# TODO(ethan): add loss weightings here from a config
|
||||||
loss_sum += losses[loss_name]
|
loss_sum += loss_dict[loss_name]
|
||||||
loss_dict[loss_name] = float(losses[loss_name])
|
return loss_sum
|
||||||
return loss_sum, loss_dict
|
|
||||||
|
|
||||||
def train(self) -> None:
|
def train(self) -> None:
|
||||||
"""_summary_"""
|
"""_summary_"""
|
||||||
|
# self.graph.train()
|
||||||
|
# assert self.graph.training, "Graph is not in train mode!"
|
||||||
train_start = time()
|
train_start = time()
|
||||||
num_iterations = self.config.graph.max_num_iterations
|
num_iterations = self.config.graph.max_num_iterations
|
||||||
iter_dataset = iter(self.train_dataloader)
|
iter_dataset = iter(self.train_dataloader)
|
||||||
@@ -226,18 +229,10 @@ class Trainer:
|
|||||||
"""Run one iteration with a batch of inputs."""
|
"""Run one iteration with a batch of inputs."""
|
||||||
# move batch to correct device
|
# move batch to correct device
|
||||||
ray_indices = batch["indices"].to(self.device)
|
ray_indices = batch["indices"].to(self.device)
|
||||||
graph_outputs = self.graph(ray_indices)
|
_, loss_dict = self.graph(ray_indices, batch=batch)
|
||||||
batch["pixels"] = batch["pixels"].to(self.device)
|
loss = loss_dict["aggregated_loss"]
|
||||||
losses = (
|
|
||||||
self.graph.module.get_losses(batch, graph_outputs)
|
|
||||||
if hasattr(self.graph, "module")
|
|
||||||
else self.graph.get_losses(batch, graph_outputs)
|
|
||||||
)
|
|
||||||
loss_sum, loss_dict = self.get_aggregated_loss(
|
|
||||||
losses
|
|
||||||
) # TODO(ethan): move this into the graph itself. not in trainer
|
|
||||||
self.optimizers.zero_grad_all()
|
self.optimizers.zero_grad_all()
|
||||||
loss_sum.backward()
|
loss.backward()
|
||||||
self.optimizers.scheduler_step_all(step) # NOTE(ethan): I think the scheduler needs to know what step we are on
|
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.optimizer_step_all()
|
||||||
return loss_dict
|
return loss_dict
|
||||||
@@ -245,60 +240,8 @@ class Trainer:
|
|||||||
@profiler.time_function
|
@profiler.time_function
|
||||||
def test_image(self, image_idx, step):
|
def test_image(self, image_idx, step):
|
||||||
"""Test a specific image."""
|
"""Test a specific image."""
|
||||||
image = self.val_image_dataset[image_idx]["image"] # ground truth
|
intrinsics = self.val_image_intrinsics[image_idx]
|
||||||
image_height, image_width, _ = image.shape
|
camera_to_world = self.val_image_camera_to_world[image_idx]
|
||||||
pixel_coords = torch.meshgrid(torch.arange(image_height), torch.arange(image_width), indexing="ij")
|
outputs = self.graph.get_outputs_for_camera(intrinsics, camera_to_world)
|
||||||
pixel_coords = torch.stack(pixel_coords, dim=-1).long()
|
image = self.val_image_dataset[image_idx]["image"].to(self.device)
|
||||||
all_ray_indices = torch.cat([torch.ones_like(pixel_coords[..., :1]) * image_idx, pixel_coords], dim=-1).view(
|
self.graph.log_test_image_outputs(image_idx, step, image, outputs)
|
||||||
-1, 3
|
|
||||||
) # NOTE(ethan): this is ugly... clean up...
|
|
||||||
with torch.no_grad():
|
|
||||||
num_rays = all_ray_indices.shape[0]
|
|
||||||
chunk_size = 1024
|
|
||||||
rgb_coarse = []
|
|
||||||
rgb_fine = []
|
|
||||||
accumulation_coarse = []
|
|
||||||
accumulation_fine = []
|
|
||||||
depth_coarse = []
|
|
||||||
depth_fine = []
|
|
||||||
for i in range(0, num_rays, chunk_size):
|
|
||||||
ray_indices = all_ray_indices[i : i + chunk_size].to(self.device)
|
|
||||||
graph_outputs = self.graph(ray_indices)
|
|
||||||
rgb_coarse.append(graph_outputs["rgb_coarse"])
|
|
||||||
rgb_fine.append(graph_outputs["rgb_fine"])
|
|
||||||
accumulation_coarse.append(graph_outputs["accumulation_coarse"])
|
|
||||||
accumulation_fine.append(graph_outputs["accumulation_fine"])
|
|
||||||
depth_coarse.append(graph_outputs["depth_coarse"])
|
|
||||||
depth_fine.append(graph_outputs["depth_fine"])
|
|
||||||
rgb_coarse = torch.cat(rgb_coarse).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
rgb_fine = torch.cat(rgb_fine).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
accumulation_coarse = torch.cat(accumulation_coarse).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
accumulation_fine = torch.cat(accumulation_fine).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
depth_coarse = torch.cat(depth_coarse).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
depth_fine = torch.cat(depth_fine).view(image_height, image_width, 3).detach().cpu()
|
|
||||||
|
|
||||||
combined_image = torch.cat([image, rgb_coarse, rgb_fine], dim=1)
|
|
||||||
writer.write_event(
|
|
||||||
{"name": f"image_idx_{image_idx}-rgb_coarse_fine", "x": combined_image, "step": step, "group": "val_img"}
|
|
||||||
)
|
|
||||||
|
|
||||||
combined_image = torch.cat([accumulation_coarse, accumulation_fine], dim=1)
|
|
||||||
writer.write_event(
|
|
||||||
{"name": f"image_idx_{image_idx}", "x": combined_image, "step": step, "group": "val_accumulation"}
|
|
||||||
)
|
|
||||||
|
|
||||||
combined_image = torch.cat([depth_coarse, depth_fine], dim=1)
|
|
||||||
writer.write_event({"name": f"image_idx_{image_idx}", "x": combined_image, "step": step, "group": "val_depth"})
|
|
||||||
|
|
||||||
coarse_psnr = get_psnr(image, rgb_coarse)
|
|
||||||
writer.write_event(
|
|
||||||
{"name": f"image_idx_{image_idx}", "scalar": float(coarse_psnr), "step": step, "group": "val"}
|
|
||||||
)
|
|
||||||
|
|
||||||
fine_psnr = get_psnr(image, rgb_fine)
|
|
||||||
stats_tracker.update_stats(
|
|
||||||
{"name": stats_tracker.Stats.CURR_TEST_PSNR, "value": float(fine_psnr), "step": step}
|
|
||||||
)
|
|
||||||
writer.write_event(
|
|
||||||
{"name": f"image_idx_{image_idx}-fine_psnr", "scalar": float(fine_psnr), "step": step, "group": "val"}
|
|
||||||
)
|
|
||||||
@@ -37,6 +37,13 @@ class RayBundle:
|
|||||||
)
|
)
|
||||||
return camera_ray_bundle
|
return camera_ray_bundle
|
||||||
|
|
||||||
|
def move_to_device(self, device):
|
||||||
|
"""Move to a device."""
|
||||||
|
self.origins = self.origins.to(device)
|
||||||
|
self.directions = self.directions.to(device)
|
||||||
|
if not isinstance(self.camera_indices, type(None)):
|
||||||
|
self.camera_indices = self.camera_indices.to(device)
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
num_rays = self.origins.shape[0]
|
num_rays = self.origins.shape[0]
|
||||||
return num_rays
|
return num_rays
|
||||||
@@ -65,8 +72,40 @@ class CameraRayBundle:
|
|||||||
|
|
||||||
origins: TensorType["image_height", "image_width", 3]
|
origins: TensorType["image_height", "image_width", 3]
|
||||||
directions: TensorType["image_height", "image_width", 3]
|
directions: TensorType["image_height", "image_width", 3]
|
||||||
|
camera_indices: Optional[TensorType["image_height", "image_width", 3]] = None
|
||||||
camera_index: int = None
|
camera_index: int = None
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if not isinstance(self.camera_index, type(None)):
|
||||||
|
self.camera_indices = torch.ones_like(self.origins[:, :]) * self.camera_index
|
||||||
|
|
||||||
|
def get_num_rays(self):
|
||||||
|
"""Return the number of rays in this bundle."""
|
||||||
|
image_height, image_width = self.origins.shape[:2]
|
||||||
|
num_rays = image_height * image_width
|
||||||
|
return num_rays
|
||||||
|
|
||||||
|
def to_ray_bundle(self) -> RayBundle:
|
||||||
|
"""_summary_
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RayBundle: _description_
|
||||||
|
"""
|
||||||
|
# TODO(ethan): handle camera_index
|
||||||
|
ray_bundle = RayBundle(origins=self.origins.view(-1, 3), directions=self.directions.view(-1, 3))
|
||||||
|
return ray_bundle
|
||||||
|
|
||||||
|
def get_row_major_sliced_ray_bundle(self, start_idx, end_idx):
|
||||||
|
"""Return a RayBundle"""
|
||||||
|
camera_indices = (
|
||||||
|
self.camera_indices.view(-1)[start_idx:end_idx] if not isinstance(self.camera_index, type(None)) else None
|
||||||
|
)
|
||||||
|
return RayBundle(
|
||||||
|
origins=self.origins.view(-1, 3)[start_idx:end_idx],
|
||||||
|
directions=self.directions.view(-1, 3)[start_idx:end_idx],
|
||||||
|
camera_indices=camera_indices,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class RaySamples:
|
class RaySamples:
|
||||||
"""_summary_"""
|
"""_summary_"""
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
Miscellaneous helper code.
|
Miscellaneous helper code.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
class DotDict(dict):
|
class DotDict(dict):
|
||||||
"""
|
"""
|
||||||
@@ -13,3 +15,25 @@ class DotDict(dict):
|
|||||||
|
|
||||||
__setattr__ = dict.__setitem__
|
__setattr__ = dict.__setitem__
|
||||||
__delattr__ = dict.__delitem__
|
__delattr__ = dict.__delitem__
|
||||||
|
|
||||||
|
|
||||||
|
def get_dict_to_torch(stuff, device="cpu"):
|
||||||
|
"""Set everything in the dict to the specified torch device."""
|
||||||
|
if isinstance(stuff, dict):
|
||||||
|
for k, v in stuff.items():
|
||||||
|
stuff[k] = get_dict_to_torch(v, device)
|
||||||
|
return stuff
|
||||||
|
if isinstance(stuff, torch.Tensor):
|
||||||
|
return stuff.to(device)
|
||||||
|
return stuff
|
||||||
|
|
||||||
|
|
||||||
|
def get_dict_to_cpu(stuff):
|
||||||
|
"""Set everything in the dict to CPU."""
|
||||||
|
if isinstance(stuff, dict):
|
||||||
|
for k, v in stuff.items():
|
||||||
|
stuff[k] = get_dict_to_cpu(v)
|
||||||
|
return stuff
|
||||||
|
if isinstance(stuff, torch.Tensor):
|
||||||
|
return stuff.detach().cpu()
|
||||||
|
return stuff
|
||||||
@@ -44,8 +44,8 @@ class Stats(enum.Enum):
|
|||||||
enum (_type_): _description_
|
enum (_type_): _description_
|
||||||
"""
|
"""
|
||||||
|
|
||||||
ITER_LOAD_TIME = "Data Load (time)"
|
ITER_LOAD_TIME = "Data Load (ms)"
|
||||||
ITER_TRAIN_TIME = "Train Iter (time)"
|
ITER_TRAIN_TIME = "Train Iter (ms)"
|
||||||
TOTAL_TRAIN_TIME = "Train Total (time)"
|
TOTAL_TRAIN_TIME = "Train Total (time)"
|
||||||
RAYS_PER_SEC = "Rays Per Sec (1/s)"
|
RAYS_PER_SEC = "Rays Per Sec (1/s)"
|
||||||
CURR_TEST_PSNR = "Test PSNR"
|
CURR_TEST_PSNR = "Test PSNR"
|
||||||
@@ -145,6 +145,9 @@ class StatsTracker:
|
|||||||
for k, v in self.stats_dict.items():
|
for k, v in self.stats_dict.items():
|
||||||
if "(time)" in k.value:
|
if "(time)" in k.value:
|
||||||
v = str(datetime.timedelta(seconds=v))
|
v = str(datetime.timedelta(seconds=v))
|
||||||
|
elif "(ms)" in k.value:
|
||||||
|
ms = v * 1e3
|
||||||
|
v = f"{ms:0.4f}"
|
||||||
else:
|
else:
|
||||||
v = f"{v:0.4f}"
|
v = f"{v:0.4f}"
|
||||||
curr_mssg += f"{v:<20} "
|
curr_mssg += f"{v:<20} "
|
||||||
|
|||||||
+8241
-28
File diff suppressed because it is too large.
Load diff
File renamed without changes.
|
Before Width: | Height: | Size: 293 KiB After Width: | Height: | Size: 293 KiB |
File renamed without changes.
File renamed without changes.
File renamed without changes.
|
Before Width: | Height: | Size: 439 KiB After Width: | Height: | Size: 439 KiB |
@@ -33,7 +33,7 @@ def visualize_batch(batch):
|
|||||||
def test_dataloader(visualize=False):
|
def test_dataloader(visualize=False):
|
||||||
"""Testing for the dataloader from input dataset parameters to rays."""
|
"""Testing for the dataloader from input dataset parameters to rays."""
|
||||||
|
|
||||||
data_directory = "data/blender/lego_test"
|
data_directory = "tests/data/lego_test"
|
||||||
dataset_type = "blender"
|
dataset_type = "blender"
|
||||||
downscale_factor = 1
|
downscale_factor = 1
|
||||||
num_images_to_sample_from = 1
|
num_images_to_sample_from = 1
|
||||||
|
|||||||
Reference in new issue
Block a user