Change name to pyrad

This commit is contained in:
Matt Tancik committed 2022-05-31 14:15:06 -07:00
1 parent ee1dcdd197
commit 1a8ad9a763
87 files changed
+186 -187

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
/*
* Helper code.
*/
#define CUDA_NUM_BLOCKS_NEEDED(Q, CUDA_N_THREADS) ((Q - 1) / CUDA_N_THREADS + 1)
+30
View File
@@ -0,0 +1,30 @@
/*
This file uses pybind to make CUDA calls.
*/
#include <torch/extension.h>
#include <vector>
// CUDA forward declarations
std::vector<torch::Tensor> sample_uniformly_along_ray_bundle(
torch::Tensor origins,
torch::Tensor directions,
torch::Tensor nears,
torch::Tensor fars,
torch::Tensor offsets,
int max_num_samples);
// C++ interface
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) \
CHECK_CUDA(x); \
CHECK_CONTIGUOUS(x)
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("sample_uniformly_along_ray_bundle", &sample_uniformly_along_ray_bundle);
}
+133
View File
@@ -0,0 +1,133 @@
/*
Note that this file has the _kernel.cu extension because
setuptools cannot handle files with the same name but different extensions.
*/
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#define CUDA_N_BLOCKS_NEEDED(Q, CUDA_N_THREADS) ((Q - 1) / CUDA_N_THREADS + 1)
namespace
{
template <typename scalar_t>
__device__ __forceinline__ scalar_t sigmoid(scalar_t z)
{
return 1.0 / (1.0 + exp(-z));
}
template <typename scalar_t>
__device__ __forceinline__ scalar_t d_sigmoid(scalar_t z)
{
const auto s = sigmoid(z);
return (1.0 - s) * s;
}
template <typename scalar_t>
__device__ __forceinline__ scalar_t d_tanh(scalar_t z)
{
const auto t = tanh(z);
return 1 - (t * t);
}
template <typename scalar_t>
__device__ __forceinline__ scalar_t elu(scalar_t z, scalar_t alpha = 1.0)
{
return fmaxf(0.0, z) + fminf(0.0, alpha * (exp(z) - 1.0));
}
template <typename scalar_t>
__device__ __forceinline__ scalar_t d_elu(scalar_t z, scalar_t alpha = 1.0)
{
const auto e = exp(z);
const auto d_relu = z < 0.0 ? 0.0 : 1.0;
return d_relu + (((alpha * (e - 1.0)) < 0.0) ? (alpha * e) : 0.0);
}
template <typename scalar_t>
__global__ void sample_uniformly_along_ray_bundle_kernel(
const torch::PackedTensorAccessor32<scalar_t, 2, torch::RestrictPtrTraits> origins,
const torch::PackedTensorAccessor32<scalar_t, 2, torch::RestrictPtrTraits> directions,
const torch::PackedTensorAccessor32<scalar_t, 1, torch::RestrictPtrTraits> nears,
const torch::PackedTensorAccessor32<scalar_t, 1, torch::RestrictPtrTraits> fars,
const torch::PackedTensorAccessor32<scalar_t, 1, torch::RestrictPtrTraits> offsets,
torch::PackedTensorAccessor32<scalar_t, 2, torch::RestrictPtrTraits> output_time_steps,
torch::PackedTensorAccessor32<scalar_t, 3, torch::RestrictPtrTraits> output_samples,
torch::PackedTensorAccessor32<scalar_t, 2, torch::RestrictPtrTraits> output_time_steps_mask)
{
const int thread_id = blockIdx.x * blockDim.x + threadIdx.x;
const int max_num_samples = output_samples.size(1);
scalar_t t_min = nears[thread_id];
scalar_t t_max = fars[thread_id];
scalar_t offset = offsets[thread_id];
int sample_index = 0;
// #pragma unroll
for (scalar_t t = t_min; t <= t_max; t += offset)
{
// #pragma unroll
for (int i = 0; i < 3; ++i)
{
if (sample_index < max_num_samples)
{
scalar_t pos_i = origins[thread_id][i] + t * directions[thread_id][i];
output_samples[thread_id][sample_index][i] = pos_i;
}
}
if (sample_index < max_num_samples)
{
output_time_steps[thread_id][sample_index] = t;
output_time_steps_mask[thread_id][sample_index] = 1.0;
}
sample_index += 1;
}
}
} // namespace
std::vector<torch::Tensor> sample_uniformly_along_ray_bundle(
torch::Tensor origins,
torch::Tensor directions,
torch::Tensor nears,
torch::Tensor fars,
torch::Tensor offsets,
int max_num_samples)
{
std::cout << "sample_uniformly_along_ray_bundle -- start" << std::endl;
TORCH_CHECK(origins.is_floating_point()); // should be float32
TORCH_CHECK(origins.ndimension() == 2); // and check that shape is (num_rays, 3)
TORCH_CHECK(origins.size(1) == 3);
const auto num_rays = origins.size(0);
// TODO: change the number of threads based on GPU
const int threads = 1024; // number of threads in a thread block
// const int blocks = num_rays / threads;
const int blocks = CUDA_N_BLOCKS_NEEDED(num_rays, threads);
// std::cout << origins.options() << std::endl;
torch::Tensor output_time_steps = torch::zeros({num_rays, max_num_samples}, origins.options());
torch::Tensor output_samples = torch::zeros({num_rays, max_num_samples, 3}, origins.options());
torch::Tensor output_time_steps_mask = torch::zeros({num_rays, max_num_samples}, origins.options());
// The second argument is used for error messages.
// __FUNCTION__ macro == "sample_uniformly_along_ray_bundle" in this case.
AT_DISPATCH_FLOATING_TYPES(origins.type(), __FUNCTION__, [&]
{ sample_uniformly_along_ray_bundle_kernel<scalar_t><<<blocks, threads>>>(
origins.packed_accessor32<scalar_t, 2, torch::RestrictPtrTraits>(),
directions.packed_accessor32<scalar_t, 2, torch::RestrictPtrTraits>(),
nears.packed_accessor32<scalar_t, 1, torch::RestrictPtrTraits>(),
fars.packed_accessor32<scalar_t, 1, torch::RestrictPtrTraits>(),
offsets.packed_accessor32<scalar_t, 1, torch::RestrictPtrTraits>(),
output_time_steps.packed_accessor32<scalar_t, 2, torch::RestrictPtrTraits>(),
output_samples.packed_accessor32<scalar_t, 3, torch::RestrictPtrTraits>(),
output_time_steps_mask.packed_accessor32<scalar_t, 2, torch::RestrictPtrTraits>()); });
std::cout << "sample_uniformly_along_ray_bundle -- end" << std::endl;
return {output_time_steps, output_samples, output_time_steps_mask};
}
+45
View File
@@ -0,0 +1,45 @@
"""
Sampler.
"""
import math
import torch
from torch import nn
import pyrad_cuda
class LLTMFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, weights, bias, old_h, old_cell):
outputs = pyrad_cuda.forward(input, weights, bias, old_h, old_cell)
new_h, new_cell = outputs[:2]
variables = outputs[1:] + [weights]
ctx.save_for_backward(*variables)
return new_h, new_cell
@staticmethod
def backward(ctx, grad_h, grad_cell):
outputs = pyrad_cuda.backward(grad_h.contiguous(), grad_cell.contiguous(), *ctx.saved_variables)
d_old_h, d_input, d_weights, d_bias, d_old_cell, d_gates = outputs
return d_input, d_weights, d_bias, d_old_h, d_old_cell
class Sampler(nn.Module):
def __init__(self, input_features, state_size):
super().__init__()
self.input_features = input_features
self.state_size = state_size
self.weights = nn.Parameter(torch.Tensor(3 * state_size, input_features + state_size))
self.bias = nn.Parameter(torch.Tensor(1, 3 * state_size))
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.state_size)
for weight in self.parameters():
weight.data.uniform_(-stdv, +stdv)
def forward(self, input, state):
return LLTMFunction.apply(input, self.weights, self.bias, *state)
View File
Whitespace-only changes.
+90
View File
@@ -0,0 +1,90 @@
"""
Ray generator.
"""
import torch
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.dataset.structs import SceneBounds
from pyrad.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
View File
Whitespace-only changes.
+67
View File
@@ -0,0 +1,67 @@
"""
Classes to help with caching data while training.
"""
import random
from typing import Callable
import torch
from torch.utils.data import default_collate
def collate_batch_size_one(batch_list):
"""Use the default collate function but then squeze to avoid the batch dimension being added."""
assert len(batch_list) == 1
collated_batch = default_collate(batch_list)
for key in collated_batch:
assert collated_batch[key].shape[0] == 1
collated_batch[key] = collated_batch[key].squeeze(0)
return collated_batch
class CollateIterDataset(torch.utils.data.IterableDataset):
"""Collated image dataset that implements caching of images.
Args:
torch (_type_): _description_
"""
def __init__(
self,
dataset: torch.utils.data.Dataset,
collate_fn: Callable,
num_samples_to_collate: int,
num_times_to_repeat_images: int = 0,
):
super().__init__()
self.dataset = dataset
self.collate_fn = collate_fn
self.num_samples_to_collate = num_samples_to_collate
self.num_times_to_repeat_images = num_times_to_repeat_images
self.num_repeated = self.num_times_to_repeat_images # starting value
self.cached_batch_list = None
def __getitem__(self, idx):
return self.dataset.__getitem__(idx)
def get_batch_list(self):
"""Returns a list of batches from the dataset attribute."""
# sampling without replacement. TODO(ethan): don't use 'random'
indices = random.sample(range(len(self.dataset)), k=self.num_samples_to_collate)
batch_list = [self.dataset.__getitem__(idx) for idx in indices]
return batch_list
def __iter__(self):
while True:
if self.num_repeated >= self.num_times_to_repeat_images:
# trigger a reset
self.num_repeated = 0
batch_list = self.get_batch_list()
# possibly save a cached item
self.cached_batch_list = batch_list if self.num_times_to_repeat_images != 0 else None
else:
batch_list = self.cached_batch_list
self.num_repeated += 1
collated_batch = self.collate_fn(batch_list)
yield collated_batch
+513
View File
@@ -0,0 +1,513 @@
# pylint: disable-all
"""
Here we have code taken from COLMAP for parsing data in the COLMAP format.
Original file at https://github.com/colmap/colmap/blob/1a4d0bad2e90aa65ce997c9d1779518eaed998d5/scripts/python/read_write_model.py.
"""
# Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
import os
import collections
import numpy as np
import struct
import argparse
CameraModel = collections.namedtuple("CameraModel", ["model_id", "model_name", "num_params"])
Camera = collections.namedtuple("Camera", ["id", "model", "width", "height", "params"])
BaseImage = collections.namedtuple("Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
Point3D = collections.namedtuple("Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
class Image(BaseImage):
def qvec2rotmat(self):
return qvec2rotmat(self.qvec)
CAMERA_MODELS = {
CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
CameraModel(model_id=3, model_name="RADIAL", num_params=5),
CameraModel(model_id=4, model_name="OPENCV", num_params=8),
CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
CameraModel(model_id=7, model_name="FOV", num_params=5),
CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12),
}
CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model) for camera_model in CAMERA_MODELS])
CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model) for camera_model in CAMERA_MODELS])
def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
"""Read and unpack the next bytes from a binary file.
:param fid:
:param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
:param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
:param endian_character: Any of {@, =, <, >, !}
:return: Tuple of read and unpacked values.
"""
data = fid.read(num_bytes)
return struct.unpack(endian_character + format_char_sequence, data)
def write_next_bytes(fid, data, format_char_sequence, endian_character="<"):
"""pack and write to a binary file.
:param fid:
:param data: data to send, if multiple elements are sent at the same time,
they should be encapsuled either in a list or a tuple
:param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
should be the same length as the data list or tuple
:param endian_character: Any of {@, =, <, >, !}
"""
if isinstance(data, (list, tuple)):
bytes = struct.pack(endian_character + format_char_sequence, *data)
else:
bytes = struct.pack(endian_character + format_char_sequence, data)
fid.write(bytes)
def read_cameras_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasText(const std::string& path)
void Reconstruction::ReadCamerasText(const std::string& path)
"""
cameras = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
camera_id = int(elems[0])
model = elems[1]
width = int(elems[2])
height = int(elems[3])
params = np.array(tuple(map(float, elems[4:])))
cameras[camera_id] = Camera(id=camera_id, model=model, width=width, height=height, params=params)
return cameras
def read_cameras_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path)
"""
cameras = {}
with open(path_to_model_file, "rb") as fid:
num_cameras = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_cameras):
camera_properties = read_next_bytes(fid, num_bytes=24, format_char_sequence="iiQQ")
camera_id = camera_properties[0]
model_id = camera_properties[1]
model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
width = camera_properties[2]
height = camera_properties[3]
num_params = CAMERA_MODEL_IDS[model_id].num_params
params = read_next_bytes(fid, num_bytes=8 * num_params, format_char_sequence="d" * num_params)
cameras[camera_id] = Camera(
id=camera_id, model=model_name, width=width, height=height, params=np.array(params)
)
assert len(cameras) == num_cameras
return cameras
def write_cameras_text(cameras, path):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasText(const std::string& path)
void Reconstruction::ReadCamerasText(const std::string& path)
"""
HEADER = (
"# Camera list with one line of data per camera:\n"
+ "# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\n"
+ "# Number of cameras: {}\n".format(len(cameras))
)
with open(path, "w") as fid:
fid.write(HEADER)
for _, cam in cameras.items():
to_write = [cam.id, cam.model, cam.width, cam.height, *cam.params]
line = " ".join([str(elem) for elem in to_write])
fid.write(line + "\n")
def write_cameras_binary(cameras, path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::WriteCamerasBinary(const std::string& path)
void Reconstruction::ReadCamerasBinary(const std::string& path)
"""
with open(path_to_model_file, "wb") as fid:
write_next_bytes(fid, len(cameras), "Q")
for _, cam in cameras.items():
model_id = CAMERA_MODEL_NAMES[cam.model].model_id
camera_properties = [cam.id, model_id, cam.width, cam.height]
write_next_bytes(fid, camera_properties, "iiQQ")
for p in cam.params:
write_next_bytes(fid, float(p), "d")
return cameras
def read_images_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesText(const std::string& path)
void Reconstruction::WriteImagesText(const std::string& path)
"""
images = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
image_id = int(elems[0])
qvec = np.array(tuple(map(float, elems[1:5])))
tvec = np.array(tuple(map(float, elems[5:8])))
camera_id = int(elems[8])
image_name = elems[9]
elems = fid.readline().split()
xys = np.column_stack([tuple(map(float, elems[0::3])), tuple(map(float, elems[1::3]))])
point3D_ids = np.array(tuple(map(int, elems[2::3])))
images[image_id] = Image(
id=image_id,
qvec=qvec,
tvec=tvec,
camera_id=camera_id,
name=image_name,
xys=xys,
point3D_ids=point3D_ids,
)
return images
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_images = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_reg_images):
binary_image_properties = read_next_bytes(fid, num_bytes=64, format_char_sequence="idddddddi")
image_id = binary_image_properties[0]
qvec = np.array(binary_image_properties[1:5])
tvec = np.array(binary_image_properties[5:8])
camera_id = binary_image_properties[8]
image_name = ""
current_char = read_next_bytes(fid, 1, "c")[0]
while current_char != b"\x00": # look for the ASCII 0 entry
image_name += current_char.decode("utf-8")
current_char = read_next_bytes(fid, 1, "c")[0]
num_points2D = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
x_y_id_s = read_next_bytes(fid, num_bytes=24 * num_points2D, format_char_sequence="ddq" * num_points2D)
xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])), tuple(map(float, x_y_id_s[1::3]))])
point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
images[image_id] = Image(
id=image_id,
qvec=qvec,
tvec=tvec,
camera_id=camera_id,
name=image_name,
xys=xys,
point3D_ids=point3D_ids,
)
return images
def write_images_text(images, path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesText(const std::string& path)
void Reconstruction::WriteImagesText(const std::string& path)
"""
if len(images) == 0:
mean_observations = 0
else:
mean_observations = sum((len(img.point3D_ids) for _, img in images.items())) / len(images)
HEADER = (
"# Image list with two lines of data per image:\n"
+ "# IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\n"
+ "# POINTS2D[] as (X, Y, POINT3D_ID)\n"
+ "# Number of images: {}, mean observations per image: {}\n".format(len(images), mean_observations)
)
with open(path, "w") as fid:
fid.write(HEADER)
for _, img in images.items():
image_header = [img.id, *img.qvec, *img.tvec, img.camera_id, img.name]
first_line = " ".join(map(str, image_header))
fid.write(first_line + "\n")
points_strings = []
for xy, point3D_id in zip(img.xys, img.point3D_ids):
points_strings.append(" ".join(map(str, [*xy, point3D_id])))
fid.write(" ".join(points_strings) + "\n")
def write_images_binary(images, path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
with open(path_to_model_file, "wb") as fid:
write_next_bytes(fid, len(images), "Q")
for _, img in images.items():
write_next_bytes(fid, img.id, "i")
write_next_bytes(fid, img.qvec.tolist(), "dddd")
write_next_bytes(fid, img.tvec.tolist(), "ddd")
write_next_bytes(fid, img.camera_id, "i")
for char in img.name:
write_next_bytes(fid, char.encode("utf-8"), "c")
write_next_bytes(fid, b"\x00", "c")
write_next_bytes(fid, len(img.point3D_ids), "Q")
for xy, p3d_id in zip(img.xys, img.point3D_ids):
write_next_bytes(fid, [*xy, p3d_id], "ddq")
def read_pointsTD_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DText(const std::string& path)
void Reconstruction::WritePoints3DText(const std::string& path)
"""
points3D = {}
with open(path, "r") as fid:
while True:
line = fid.readline()
if not line:
break
line = line.strip()
if len(line) > 0 and line[0] != "#":
elems = line.split()
point3D_id = int(elems[0])
xyz = np.array(tuple(map(float, elems[1:4])))
rgb = np.array(tuple(map(int, elems[4:7])))
error = float(elems[7])
image_ids = np.array(tuple(map(int, elems[8::2])))
point2D_idxs = np.array(tuple(map(int, elems[9::2])))
points3D[point3D_id] = Point3D(
id=point3D_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2D_idxs=point2D_idxs
)
return points3D
def read_pointsTD_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DBinary(const std::string& path)
void Reconstruction::WritePoints3DBinary(const std::string& path)
"""
points3D = {}
with open(path_to_model_file, "rb") as fid:
num_points = read_next_bytes(fid, 8, "Q")[0]
for _ in range(num_points):
binary_point_line_properties = read_next_bytes(fid, num_bytes=43, format_char_sequence="QdddBBBd")
point3D_id = binary_point_line_properties[0]
xyz = np.array(binary_point_line_properties[1:4])
rgb = np.array(binary_point_line_properties[4:7])
error = np.array(binary_point_line_properties[7])
track_length = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
track_elems = read_next_bytes(fid, num_bytes=8 * track_length, format_char_sequence="ii" * track_length)
image_ids = np.array(tuple(map(int, track_elems[0::2])))
point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))
points3D[point3D_id] = Point3D(
id=point3D_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2D_idxs=point2D_idxs
)
return points3D
def write_pointsTD_text(points3D, path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DText(const std::string& path)
void Reconstruction::WritePoints3DText(const std::string& path)
"""
if len(points3D) == 0:
mean_track_length = 0
else:
mean_track_length = sum((len(pt.image_ids) for _, pt in points3D.items())) / len(points3D)
HEADER = (
"# 3D point list with one line of data per point:\n"
+ "# POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\n"
+ "# Number of points: {}, mean track length: {}\n".format(len(points3D), mean_track_length)
)
with open(path, "w") as fid:
fid.write(HEADER)
for _, pt in points3D.items():
point_header = [pt.id, *pt.xyz, *pt.rgb, pt.error]
fid.write(" ".join(map(str, point_header)) + " ")
track_strings = []
for image_id, point2D in zip(pt.image_ids, pt.point2D_idxs):
track_strings.append(" ".join(map(str, [image_id, point2D])))
fid.write(" ".join(track_strings) + "\n")
def write_pointsTD_binary(points3D, path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadPoints3DBinary(const std::string& path)
void Reconstruction::WritePoints3DBinary(const std::string& path)
"""
with open(path_to_model_file, "wb") as fid:
write_next_bytes(fid, len(points3D), "Q")
for _, pt in points3D.items():
write_next_bytes(fid, pt.id, "Q")
write_next_bytes(fid, pt.xyz.tolist(), "ddd")
write_next_bytes(fid, pt.rgb.tolist(), "BBB")
write_next_bytes(fid, pt.error, "d")
track_length = pt.image_ids.shape[0]
write_next_bytes(fid, track_length, "Q")
for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs):
write_next_bytes(fid, [image_id, point2D_id], "ii")
def detect_model_format(path, ext):
if (
os.path.isfile(os.path.join(path, "cameras" + ext))
and os.path.isfile(os.path.join(path, "images" + ext))
and os.path.isfile(os.path.join(path, "points3D" + ext))
):
print("Detected model format: '" + ext + "'")
return True
return False
def read_model(path, ext=""):
# try to detect the extension automatically
if ext == "":
if detect_model_format(path, ".bin"):
ext = ".bin"
elif detect_model_format(path, ".txt"):
ext = ".txt"
else:
print("Provide model format: '.bin' or '.txt'")
return
if ext == ".txt":
cameras = read_cameras_text(os.path.join(path, "cameras" + ext))
images = read_images_text(os.path.join(path, "images" + ext))
points3D = read_pointsTD_text(os.path.join(path, "points3D") + ext)
else:
cameras = read_cameras_binary(os.path.join(path, "cameras" + ext))
images = read_images_binary(os.path.join(path, "images" + ext))
points3D = read_pointsTD_binary(os.path.join(path, "points3D") + ext)
return cameras, images, points3D
def write_model(cameras, images, points3D, path, ext=".bin"):
if ext == ".txt":
write_cameras_text(cameras, os.path.join(path, "cameras" + ext))
write_images_text(images, os.path.join(path, "images" + ext))
write_pointsTD_text(points3D, os.path.join(path, "points3D") + ext)
else:
write_cameras_binary(cameras, os.path.join(path, "cameras" + ext))
write_images_binary(images, os.path.join(path, "images" + ext))
write_pointsTD_binary(points3D, os.path.join(path, "points3D") + ext)
return cameras, images, points3D
def qvec2rotmat(qvec):
return np.array(
[
[
1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],
],
[
2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],
],
[
2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,
],
]
)
def rotmat2qvec(R):
Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
K = (
np.array(
[
[Rxx - Ryy - Rzz, 0, 0, 0],
[Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
[Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
[Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz],
]
)
/ 3.0
)
eigvals, eigvecs = np.linalg.eigh(K)
qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
if qvec[0] < 0:
qvec *= -1
return qvec
def main():
parser = argparse.ArgumentParser(description="Read and write COLMAP binary and text models")
parser.add_argument("--input_model", help="path to input model folder")
parser.add_argument("--input_format", choices=[".bin", ".txt"], help="input model format", default="")
parser.add_argument("--output_model", help="path to output model folder")
parser.add_argument("--output_format", choices=[".bin", ".txt"], help="outut model format", default=".txt")
args = parser.parse_args()
cameras, images, points3D = read_model(path=args.input_model, ext=args.input_format)
print("num_cameras:", len(cameras))
print("num_images:", len(images))
print("num_points3D:", len(points3D))
if args.output_model is not None:
write_model(cameras, images, points3D, path=args.output_model, ext=args.output_format)
if __name__ == "__main__":
main()
Whitespace-only changes.
+68
View File
@@ -0,0 +1,68 @@
"""
Code to handle loading blender datasets.
"""
import os
from typing import Optional
import imageio
import numpy as np
import torch
from torchtyping import TensorType
from pyrad.nerf.dataset.structs import DatasetInputs, SceneBounds
from pyrad.utils.io import load_from_json
def load_blender_data(
basedir: str, downscale_factor: int = 1, alpha_color: Optional[TensorType[3]] = None, split: str = "train"
) -> DatasetInputs:
"""Processes the a blender dataset directory.
Some of this code comes from https://github.com/yenchenlin/nerf-pytorch/blob/master/load_blender.py#L37.
Args:
data_directory (str): Location of data
downscale_factor (int, optional): How much to downscale images. Defaults to 1.0.
alpha_color (TensorType[3], optional): Sets transparent regions to specified color, otherwise black.
split (str, optional): Which dataset split to generate.
Returns:
DatasetInputs
"""
# pylint: disable=unused-argument
# pylint: disable-msg=too-many-locals
meta = load_from_json(os.path.join(basedir, f"transforms_{split}.json"))
image_filenames = []
poses = []
for frame in meta["frames"]:
fname = os.path.join(basedir, frame["file_path"].replace("./", "") + ".png")
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
poses = np.array(poses).astype(np.float32)
img_0 = imageio.imread(image_filenames[0])
image_height, image_width = img_0.shape[:2]
camera_angle_x = float(meta["camera_angle_x"])
focal_length = 0.5 * image_width / np.tan(0.5 * camera_angle_x)
cx = image_width / 2.0
cy = image_height / 2.0
camera_to_world = torch.from_numpy(poses[:, :3]) # camera to world transform
num_cameras = len(image_filenames)
num_intrinsics_params = 3
intrinsics = torch.ones((num_cameras, num_intrinsics_params), dtype=torch.float32)
intrinsics *= torch.tensor([cx, cy, focal_length])
# in x,y,z order
scene_bounds = SceneBounds(aabb=torch.tensor([[-2, -2, -2], [2, 2, 2]], 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
+138
View File
@@ -0,0 +1,138 @@
"""
Code to handle loading friends datasets.
"""
import os
import numpy as np
import torch
from pyrad.nerf.dataset.colmap_utils import read_cameras_binary, read_images_binary, read_pointsTD_binary
from pyrad.nerf.dataset.structs import DatasetInputs, PointCloud, SceneBounds, Semantics
from pyrad.utils import profiler
from pyrad.utils.io import load_from_json
def get_aabb_and_transform(basedir):
"""Returns the aabb and pointcloud transform from the threejs.json file."""
filename = os.path.join(basedir, "threejs.json")
assert os.path.exists(filename)
data = load_from_json(filename)
# point cloud transformation
transposed_point_cloud_transform = np.array(data["object"]["children"][0]["matrix"]).reshape(4, 4).T
assert transposed_point_cloud_transform[3, 3] == 1.0
# bbox transformation
bbox_transform = np.array(data["object"]["children"][1]["matrix"]).reshape(4, 4).T
w, h, d = data["geometries"][1]["width"], data["geometries"][1]["height"], data["geometries"][1]["depth"]
temp = np.array([w, h, d]) / 2.0
bbox = np.array([-temp, temp])
bbox = np.concatenate([bbox, np.ones_like(bbox[:, 0:1])], axis=1)
bbox = (bbox_transform @ bbox.T).T[:, 0:3]
aabb = bbox # rename to aabb because it's an axis-aligned bounding box
return torch.from_numpy(aabb).float(), torch.from_numpy(transposed_point_cloud_transform).float()
@profiler.time_function
def load_friends_data(basedir, downscale_factor=1, split="train", include_semantics=True, include_point_cloud=False):
"""_summary_
Args:
basedir (_type_): _description_
downscale_factor (float, optional): _description_. Defaults to 1.0.
split (str, optional): _description_. Defaults to "train".
include_point_cloud (bool): whether or not to include the point cloud
"""
# pylint: disable=unused-argument
# --- image filenames ----
images_data = read_images_binary(os.path.join(basedir, "colmap", "images.bin"))
# `image_path` is only the end of the filename, including the extension e.g., `.jpg`
image_paths = sorted(os.listdir(os.path.join(basedir, "images")))
image_path_to_image_id = {}
image_id_to_image_path = {}
for v in images_data.values():
image_path_to_image_id[v.name] = v.id
image_id_to_image_path[v.id] = v.name
# TODO: handle the splits differently
image_filenames = [os.path.join(basedir, "images", image_path) for image_path in image_paths]
# -- set the bounding box ---
aabb, transposed_point_cloud_transform = get_aabb_and_transform(basedir)
scene_bounds = SceneBounds(aabb=aabb)
# --- intrinsics ---
cameras_data = read_cameras_binary(os.path.join(basedir, "colmap", "cameras.bin"))
intrinsics = []
for image_path in image_paths:
cam = cameras_data[image_path_to_image_id[image_path]]
assert len(cam.params) == 3
focal_length = cam.params[0] # f (fx and fy)
cx = cam.params[1] # cx
cy = cam.params[2] # cy
intrinsics.append([cx, cy, focal_length])
intrinsics = torch.tensor(intrinsics).float()
# --- camera_to_world (extrinsics) ---
camera_to_world = []
bottom_row = np.array([0, 0, 0, 1.0]).reshape(1, 4)
for image_path in image_paths:
image_data = images_data[image_path_to_image_id[image_path]]
rot = image_data.qvec2rotmat()
trans = image_data.tvec.reshape(3, 1)
c2w = np.concatenate([np.concatenate([rot, trans], 1), bottom_row], 0)
camera_to_world.append(c2w)
camera_to_world = torch.tensor(np.array(camera_to_world)).float()
camera_to_world = torch.inverse(camera_to_world)
camera_to_world[..., 1:3] *= -1
camera_to_world = transposed_point_cloud_transform @ camera_to_world
camera_to_world = camera_to_world[:, :3]
# --- masks to mask out things (e.g., people) ---
# --- semantics ---
semantics = Semantics()
if include_semantics:
thing_filenames = [
image_filename.replace("/images/", "/segmentations/thing/").replace(".jpg", ".png")
for image_filename in image_filenames
]
stuff_filenames = [
image_filename.replace("/images/", "/segmentations/stuff/").replace(".jpg", ".png")
for image_filename in image_filenames
]
panoptic_classes = load_from_json(os.path.join(basedir, "panoptic_classes.json"))
stuff_classes = panoptic_classes["stuff"]
thing_classes = panoptic_classes["thing"]
semantics = Semantics(
stuff_classes=stuff_classes,
stuff_filenames=stuff_filenames,
thing_classes=thing_classes,
thing_filenames=thing_filenames,
)
# Possibly include the sparse point cloud from COLMAP in the dataset inputs.
# NOTE(ethan): this will be common across the different splits.
point_cloud = PointCloud()
if include_point_cloud:
points_3d = read_pointsTD_binary(os.path.join(basedir, "colmap", "points3D.bin"))
xyz = torch.tensor(np.array([p_value.xyz for p_id, p_value in points_3d.items()])).float()
rgb = torch.tensor(np.array([p_value.rgb for p_id, p_value in points_3d.items()])).float()
xyz_h = torch.cat([xyz, torch.ones_like(xyz[..., :1])], -1)
xyz = (xyz_h @ transposed_point_cloud_transform.T)[..., :3]
point_cloud.xyz = xyz
point_cloud.rgb = rgb
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
downscale_factor=downscale_factor,
intrinsics=intrinsics / downscale_factor,
camera_to_world=camera_to_world,
semantics=semantics,
point_cloud=point_cloud,
scene_bounds=scene_bounds,
)
return dataset_inputs
+80
View File
@@ -0,0 +1,80 @@
"""
Code for loading instant-ngp dataset formats.
# TODO
"""
import logging
import os
import imageio
import numpy as np
import torch
from pyrad.nerf.dataset.structs import DatasetInputs, SceneBounds
from pyrad.utils.io import load_from_json
def load_instant_ngp_data(
basedir: str, downscale_factor: int = 1, split: str = "train", camera_translation_scalar=0.33
) -> DatasetInputs:
"""Processes the a blender dataset directory.
Some of this code comes from https://github.com/yenchenlin/nerf-pytorch/blob/master/load_blender.py#L37.
Args:
data_directory (str): Location of data
downscale_factor (int, optional): How much to downscale images. Defaults to 1.0.
split (str, optional): Which dataset split to generate.
Returns:
DatasetInputs
"""
# pylint: disable=unused-argument
# pylint: disable-msg=too-many-locals
meta = load_from_json(os.path.join(basedir, "transforms.json"))
image_filenames = []
poses = []
num_skipped_image_filenames = 0
for frame in meta["frames"]:
fname = os.path.join(basedir, frame["file_path"])
if not os.path.exists(fname):
num_skipped_image_filenames += 1
else:
image_filenames.append(fname)
poses.append(np.array(frame["transform_matrix"]))
if num_skipped_image_filenames >= 0:
logging.info("Skipping %s files in dataset split %s.", num_skipped_image_filenames, split)
poses = np.array(poses).astype(np.float32)
poses[:3, 3] *= camera_translation_scalar
img_0 = imageio.imread(image_filenames[0])
image_height, image_width = img_0.shape[:2]
camera_angle_x = float(meta["camera_angle_x"])
focal_length = 0.5 * image_width / np.tan(0.5 * camera_angle_x)
cx = image_width / 2.0
cy = image_height / 2.0
camera_to_world = torch.from_numpy(poses[:, :3]) # camera to world transform
num_cameras = len(image_filenames)
num_intrinsics_params = 3
intrinsics = torch.ones((num_cameras, num_intrinsics_params), dtype=torch.float32)
intrinsics *= torch.tensor([cx, cy, focal_length])
# in x,y,z order
# assumes that the scene is centered at the origin
aabb_scale = meta["aabb_scale"]
scene_bounds = SceneBounds(
aabb=torch.tensor(
[[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32
)
)
# TODO(ethan): add alpha background color
dataset_inputs = DatasetInputs(
image_filenames=image_filenames,
downscale_factor=downscale_factor,
intrinsics=intrinsics * 1.0 / downscale_factor, # downscaling the intrinsics here
camera_to_world=camera_to_world,
scene_bounds=scene_bounds,
)
return dataset_inputs
+16
View File
@@ -0,0 +1,16 @@
"""
Code for loading the LLFF data.
"""
def load_llff_data(basedir, downscale_factor=1, split="train", include_point_cloud=False):
"""_summary_
Args:
basedir (_type_): _description_
downscale_factor (float, optional): _description_. Defaults to 1.0.
split (str, optional): _description_. Defaults to "train".
include_point_cloud (bool): whether or not to include the point cloud
"""
# pylint: disable=unused-argument
raise NotImplementedError
+168
View File
@@ -0,0 +1,168 @@
"""
Some dataset code.
"""
from typing import List, Optional
import numpy as np
import numpy.typing as npt
import PIL
import torch
from PIL import Image
from torch.utils.data import default_collate
from torchtyping import TensorType
from pyrad.nerf.dataset.structs import Semantics
def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False):
"""_summary_
Args:
batch (_type_): _description_
"""
# TODO(ethan): handle sampling even when in different processes
# we don't want the same samples for all spawned processed when
# using distributed training
batch = default_collate(batch_list)
num_images, image_height, image_width, _ = batch["image"].shape
# # checking where mask is not zero
# # TODO(ethan): add this to the code with a config
# nonzero_indices = torch.nonzero(batch["mask"], as_tuple=False)
# chosen_indices = random.sample(range(len(nonzero_indices)), k=num_rays_per_batch)
# indices = nonzero_indices[chosen_indices]
indices = torch.floor(
torch.rand((num_rays_per_batch, 3)) * torch.tensor([num_images, image_height, image_width])
).long()
c, y, x = [i.flatten() for i in torch.split(indices, 1, dim=-1)]
pixels = batch["image"][c, y, x]
mask = batch["mask"][c, y, x]
if "stuff_image" in batch:
stuff_image = batch["stuff_image"][c, y, x]
assert pixels.shape == (num_rays_per_batch, 3), pixels.shape
# Needed to correct the random indices to their actual camera idx locations.
local_indices = indices.clone()
indices[:, 0] = batch["image_idx"][c]
collated_batch = {
"local_indices": local_indices, # local to the batch returned
"indices": indices, # with the abs camera indices
"pixels": pixels,
"mask": mask,
}
if "stuff_image" in batch:
collated_batch["stuff_image"] = stuff_image
if keep_full_image:
collated_batch["image"] = batch["image"]
return collated_batch
class ImageDataset(torch.utils.data.Dataset):
"""Dataset that returns images."""
def __init__(
self,
image_filenames: List[str],
downscale_factor: int = 1,
alpha_color: Optional[TensorType[3]] = None,
semantics: Semantics = Semantics(),
**kwargs,
):
"""_summary_
Args:
image_filenames (List[str]): List of image filenames
downscale_factor (int, optional): How much to downscale the image. Defaults to 1.
alpha_color (TensorType[3], optional): Sets transparent regions to specified color, otherwise black.
"""
super().__init__()
assert isinstance(downscale_factor, int)
self.image_filenames = image_filenames
self.downscale_factor = downscale_factor
self.alpha_color = alpha_color
self.semantics = semantics
self.kwargs = kwargs
def __len__(self):
return len(self.image_filenames)
def get_image(self, image_idx: int) -> npt.NDArray[np.uint8]:
"""Returns the image.
Args:
image_idx (int): The image index in the dataset.
Returns:
np.uint8: an image of shape (H, W, 3 or 4)
"""
image_filename = self.image_filenames[image_idx]
pil_image = Image.open(image_filename)
if self.downscale_factor != 1.0:
image_width, image_height = pil_image.size
if image_width % self.downscale_factor != 0:
raise ValueError(
f"Image width {image_width} is not divisible by downscale_factor {self.downscale_factor}"
)
if image_height % self.downscale_factor != 0:
raise ValueError(
f"Image height {image_height} is not divisible by downscale_factor {self.downscale_factor}"
)
pil_image = pil_image.resize(
(image_width // self.downscale_factor, image_height // self.downscale_factor), PIL.Image.BILINEAR
)
image = np.array(pil_image, dtype="uint8") # shape is (h, w, 3 or 4)
assert len(image.shape) == 3
assert image.dtype == np.uint8
assert image.shape[2] in [3, 4], f"Image shape of {image.shape} is in correct."
return image
def __getitem__(self, image_idx):
# the image might be RGB or RGBA, so we separate it
original_image = torch.from_numpy(self.get_image(image_idx).astype("float32") / 255.0)
if self.alpha_color is not None:
image = original_image[:, :, :3] * original_image[:, :, -1:] + self.alpha_color * (
1.0 - original_image[:, :, -1:]
)
else:
image = original_image[:, :, :3]
num_channels = original_image.shape[2]
if num_channels == 4:
mask = original_image[:, :, 3]
elif num_channels == 3:
mask = np.ones_like(original_image[:, :, 0])
else:
raise ValueError(f"Image shape of {image.shape} is in correct.")
data = {
"image_idx": image_idx,
"image": image, # the pixels
"mask": mask,
}
if self.semantics.stuff_filenames:
stuff_image_filename = self.semantics.stuff_filenames[image_idx]
pil_image = Image.open(stuff_image_filename)
if self.downscale_factor != 1.0:
image_width, image_height = pil_image.size
if image_width % self.downscale_factor != 0:
raise ValueError(
f"Image width {image_width} is not divisible by downscale_factor {self.downscale_factor}"
)
if image_height % self.downscale_factor != 0:
raise ValueError(
f"Image height {image_height} is not divisible by downscale_factor {self.downscale_factor}"
)
# NOTE(ethan): the use of NEAREST is important for semantic classes
pil_image = pil_image.resize(
(image_width // self.downscale_factor, image_height // self.downscale_factor), PIL.Image.NEAREST
)
stuff_image = torch.from_numpy(np.array(pil_image, dtype="int32"))[..., None]
data["stuff_image"] = stuff_image
return data
+72
View File
@@ -0,0 +1,72 @@
"""
Dataset input structures.
"""
from dataclasses import dataclass
from typing import List, Optional
import torch
from torchtyping import TensorType
@dataclass
class PointCloud:
"""_summary_"""
xyz = None
rgb = None
@dataclass
class Semantics:
"""_summary_"""
stuff_classes: List[str] = None
stuff_filenames: List[str] = None
thing_classes: List[str] = None
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.
Args:
image_filenames: Filenames for the images.
...
"""
image_filenames: List[str]
downscale_factor: int = 1
intrinsics: torch.tensor = None
camera_to_world: 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
def check_inputs(self):
"""Check the inputs to make sure everything is okay."""
assert self.intrinsics.dtype == torch.float32
assert self.camera_to_world.dtype == torch.float32
def save_to_folder_name(self, data_directory: str):
"""Save the dataset inputs."""
raise NotImplementedError
def load_from_folder_name(self, data_directory: str):
"""Load the saved dataset inputs."""
raise NotImplementedError
+70
View File
@@ -0,0 +1,70 @@
"""
For loading the blender dataset format.
"""
from typing import Optional, Union
from omegaconf import ListConfig
from pyrad.nerf.dataset.format.blender import load_blender_data
from pyrad.nerf.dataset.format.friends import load_friends_data
from pyrad.nerf.dataset.format.instant_ngp import load_instant_ngp_data
from pyrad.nerf.dataset.structs import DatasetInputs
from pyrad.structures.colors import get_color
from pyrad.utils.io import get_absolute_path
def get_dataset_inputs(
data_directory: str,
dataset_format: str,
split: str,
downscale_factor: int = 1,
alpha_color: Optional[Union[str, list, ListConfig]] = None,
load_dataset_inputs_from_cache: bool = False,
) -> 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_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:
DatasetInputs: The inputs needed for generating rays.
"""
if load_dataset_inputs_from_cache:
print("Loading from cache.")
return None
if alpha_color is not None:
alpha_color = get_color(alpha_color)
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(
get_absolute_path(data_directory),
downscale_factor=downscale_factor,
split="train",
include_point_cloud=False,
)
elif dataset_format == "instant_ngp":
dataset_inputs = load_instant_ngp_data(
get_absolute_path(data_directory),
downscale_factor=downscale_factor,
split="train",
)
else:
raise NotImplementedError(f"{dataset_format} is not a valid dataset type")
return dataset_inputs
+4
View File
@@ -0,0 +1,4 @@
"""init field modules"""
from .encoding import Encoding, ScalingAndOffset
from .mlp import MLP
from .base import FieldModule
+54
View File
@@ -0,0 +1,54 @@
"""
The field module baseclass.
"""
from abc import abstractmethod
from torch import nn
from torchtyping import TensorType
class FieldModule(nn.Module):
"""Field modules that can be combined to store and compute the fields."""
def __init__(self) -> None:
"""Default initialization of module"""
super().__init__()
self.in_dim = 0
self.out_dim = 0
def build_nn_modules(self) -> None:
"""Function instantiates any torch.nn members within the module.
If none exist, do nothing."""
def set_in_dim(self, in_dim: int) -> None:
"""Sets input dimension of encoding
Args:
in_dim (int): input dimension
"""
if in_dim <= 0:
raise ValueError("Input dimension should be greater than zero")
self.in_dim = in_dim
def get_out_dim(self) -> int:
"""Calculates output dimension of encoding.
Returns:
int: output dimension
"""
if not hasattr(self, "out_dim"):
raise ValueError("Output dimension has not been set")
if self.out_dim <= 0:
raise ValueError("Output dimension should be greater than zero")
return self.out_dim
@abstractmethod
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""
Args:
in_tensor (TensorType[..., "input_dim"]): Input tensor to process
Returns:
TensorType[..., "output_dim"]: Processed tensor
"""
raise NotImplementedError
+32
View File
@@ -0,0 +1,32 @@
"""
Code for embeddings.
"""
import torch
from torchtyping import TensorType
from pyrad.nerf.field_modules.base import FieldModule
class Embedding(FieldModule):
"""Index into embeddings.
# TODO: add different types of initializations
"""
def __init__(self, in_dim: int, out_dim: int) -> None:
"""
Args:
in_dim (int): Number of embeddings
out_dim (int): Dimension of the embedding vectors
"""
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.build_nn_modules()
def build_nn_modules(self) -> None:
self.embedding = torch.nn.Embedding(self.in_dim, self.out_dim)
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""Call forward"""
return self.embedding(in_tensor)
+386
View File
@@ -0,0 +1,386 @@
"""
Encoding functions
"""
from abc import abstractmethod
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.field_modules.base import FieldModule
from pyrad.utils.math import components_from_spherical_harmonics
class Encoding(FieldModule):
"""Encode an input tensor. Intended to be subclassed"""
def __init__(self, in_dim: int) -> None:
"""
Args:
in_dim (int): Input dimension of tensor
"""
super().__init__()
if in_dim <= 0:
raise ValueError("Input dimension should be greater than zero")
self.in_dim = in_dim
@abstractmethod
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""Encodes an input tensor.
Args:
x (TensorType[..., "input_dim"]): Input tensor to be encoded
Returns:
TensorType[..., "output_dim"]: A encoded input tensor
"""
raise NotImplementedError
def forward(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""Call forward"""
return self.encode(in_tensor)
class Identity(Encoding):
"""Identity encoding (Does not modify input)"""
def get_out_dim(self) -> int:
return self.in_dim
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
return in_tensor
class ScalingAndOffset(Encoding):
"""Simple scaling and offet to input"""
def __init__(self, in_dim: int, scaling: float = 1.0, offset: float = 0.0) -> None:
"""Each input is scaled then offset
Args:
in_dim (int): Input dimension of tensor
scaling (float, optional): Scaling applied to tensor. Defaults to 1.0.
offset (float, optional): Offset applied to tensor. Defaults to 0.0.
"""
super().__init__(in_dim)
self.scaling = scaling
self.offset = offset
def get_out_dim(self) -> int:
return self.in_dim
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
return self.scaling * in_tensor + self.offset
class NeRFEncoding(Encoding):
"""Multi-scale sinousoidal encoding proposed in the original NeRF paper"""
def __init__(
self, in_dim: int, num_frequencies: int, min_freq_exp: float, max_freq_exp: float, include_input: bool = False
) -> None:
"""Each axis is encoded with frequencies ranging from 2^min_freq_exp to 2^max_freq_exp.
Args:
in_dim (int): Input dimension of tensor
num_frequencies (int): Number of encoded frequencies per axis
min_freq_exp (float): Minimum frequency exponent
max_freq_exp (float): Maximum frequency exponent
include_input (float): Append the input coordinate to the encoding
"""
super().__init__(in_dim)
self.num_frequencies = num_frequencies
self.min_freq = min_freq_exp
self.max_freq = max_freq_exp
self.include_input = include_input
def get_out_dim(self) -> int:
out_dim = self.in_dim * self.num_frequencies * 2
if self.include_input:
out_dim += self.in_dim
return out_dim
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""
Args:
in_tensor (TensorType[..., "input_dim"]): For best performance, the input tensor should be between 0 and 1.
Returns:
TensorType[..., "output_dim"]: Output values will be between -1 and 1
"""
freqs = 2 ** torch.linspace(self.min_freq, self.max_freq, self.num_frequencies).to(in_tensor.device)
scaled_inputs = 2 * torch.pi * in_tensor[..., None] * freqs # [..., "input_dim", "num_scales"]
scaled_inputs = scaled_inputs.view(*scaled_inputs.shape[:-2], -1) # [..., "input_dim" * "num_scales"]
encoded_inputs = torch.cat([torch.sin(scaled_inputs), torch.cos(scaled_inputs)], axis=-1)
if self.include_input:
encoded_inputs = torch.cat([encoded_inputs, in_tensor], axis=-1)
return encoded_inputs
class RFFEncoding(Encoding):
"""Random Fourier Feature encoding"""
def __init__(self, in_dim: int, num_frequencies: int, scale: float) -> None:
"""
Args:
in_dim (int): Input dimension of tensor
num_frequencies (int): Number of encoding frequencies
scale (float): Std of Gaussian to sample frequencies. Must be greater than zero
"""
super().__init__(in_dim)
self.num_frequencies = num_frequencies
if not scale > 0:
raise ValueError("RFF encoding scale should be greater than zero")
self.scale = scale
self.b_matrix = torch.normal(mean=0, std=self.scale, size=(self.in_dim, self.num_frequencies))
def get_out_dim(self) -> int:
return self.num_frequencies * 2
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
"""
Args:
in_tensor (TensorType[..., "input_dim"]): For best performance, the input tensor should be between 0 and 1.
Returns:
TensorType[..., "output_dim"]: Output values will be between -1 and 1
"""
scaled_inputs = in_tensor @ self.b_matrix # [..., "num_frequencies"]
encoded_inputs = torch.cat([torch.sin(scaled_inputs), torch.cos(scaled_inputs)], axis=-1)
return encoded_inputs
class HashEncoding(Encoding):
"""Hash encoding"""
def __init__(
self,
num_levels: int = 16,
min_res: int = 16,
max_res: int = 1024,
hash_table_size: int = 2**19,
features_per_level: int = 2,
hash_init_scale: float = 0.001,
) -> None:
"""_summary_
Args:
num_levels (int, optional): Number of feature grids. Defaults to 16.
min_res (int, optional): Resolution of smallest feature grid. Defaults to 16.
max_res (int, optional): Resolution of largest feature grid. Defaults to 1024.
hash_table_size (int, optional): Size of hash table. Defaults to 2**19.
features_per_level (int, optional): Number of features per level. Defaults to 2.
hash_init_scale (float, optional): Value to initialize hash grid. Defaults to 0.001.
"""
super().__init__(in_dim=3)
self.num_levels = num_levels
self.features_per_level = features_per_level
self.hash_table_size = hash_table_size
levels = torch.arange(num_levels)
growth_factor = np.exp((np.log(max_res) - np.log(min_res)) / (num_levels - 1))
self.scalings = torch.floor(min_res * growth_factor**levels)
self.hash_offset = levels * hash_table_size
self.hash_table = torch.rand(size=(hash_table_size * num_levels, features_per_level)) * 2 - 1
self.hash_table *= hash_init_scale
self.hash_table = nn.Parameter(self.hash_table)
def get_out_dim(self) -> int:
return self.num_levels * self.features_per_level
def hash_fn(self, in_tensor: TensorType[..., "num_levels", 3]) -> TensorType[..., "num_levels"]:
"""Hash tensor using method described in Instant-NGP
Args:
in_tensor (TensorType[..., &quot;num_levels&quot;, 3]): Tensor to be hashed
Returns:
TensorType[..., &quot;num_levels&quot;]: Hashed tensor
"""
in_tensor = in_tensor * torch.tensor([1, 2654435761, 805459861]).to(in_tensor.device)
x = torch.bitwise_xor(in_tensor[..., 0], in_tensor[..., 1])
x = torch.bitwise_xor(x, in_tensor[..., 2])
x %= self.hash_table_size
x += self.hash_offset.to(x.device)
return x
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
assert in_tensor.shape[-1] == 3
in_tensor = in_tensor[..., None, :] # [..., 1, 3]
scaled = in_tensor * self.scalings.view(-1, 1).to(in_tensor.device) # [..., L, 3]
scaled_c = torch.ceil(scaled).type(torch.int32)
scaled_f = torch.floor(scaled).type(torch.int32)
offset = scaled - scaled_f
hashed_0 = self.hash_fn(scaled_c) # [..., num_levels]
hashed_1 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_f[..., 1:2], scaled_c[..., 2:3]], dim=-1))
hashed_2 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_f[..., 1:2], scaled_c[..., 2:3]], dim=-1))
hashed_3 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_c[..., 1:2], scaled_c[..., 2:3]], dim=-1))
hashed_4 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_c[..., 1:2], scaled_f[..., 2:3]], dim=-1))
hashed_5 = self.hash_fn(torch.cat([scaled_c[..., 0:1], scaled_f[..., 1:2], scaled_f[..., 2:3]], dim=-1))
hashed_6 = self.hash_fn(scaled_f)
hashed_7 = self.hash_fn(torch.cat([scaled_f[..., 0:1], scaled_c[..., 1:2], scaled_f[..., 2:3]], dim=-1))
f_0 = self.hash_table[hashed_0] # [..., num_levels, features_per_level]
f_1 = self.hash_table[hashed_1]
f_2 = self.hash_table[hashed_2]
f_3 = self.hash_table[hashed_3]
f_4 = self.hash_table[hashed_4]
f_5 = self.hash_table[hashed_5]
f_6 = self.hash_table[hashed_6]
f_7 = self.hash_table[hashed_7]
f_03 = f_0 * offset[..., 0:1] + f_3 * (1 - offset[..., 0:1])
f_12 = f_1 * offset[..., 0:1] + f_2 * (1 - offset[..., 0:1])
f_56 = f_5 * offset[..., 0:1] + f_6 * (1 - offset[..., 0:1])
f_47 = f_4 * offset[..., 0:1] + f_7 * (1 - offset[..., 0:1])
f0312 = f_03 * offset[..., 1:2] + f_12 * (1 - offset[..., 1:2])
f4756 = f_47 * offset[..., 1:2] + f_56 * (1 - offset[..., 1:2])
encoded_value = f0312 * offset[..., 2:3] + f4756 * (
1 - offset[..., 2:3]
) # [..., num_levels, features_per_level]
return torch.flatten(encoded_value, start_dim=-2, end_dim=-1) # [..., num_levels * features_per_level]
class TensorCPEncoding(Encoding):
"""Learned CANDECOMP/PARFAC (CP) decomposition encoding used in TensoRF"""
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
"""
Args:
resolution (int, optional): Resolution of grid. Defaults to 256.
num_components (int, optional): Number of components per dimension. Defaults to 24.
init_scale (float, optional): Initialization scale. Defaults to 0.1.
"""
super().__init__(in_dim=3)
self.resolution = resolution
self.num_components = num_components
# TODO Learning rates should be different for these
self.line_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, 1)))
def get_out_dim(self) -> int:
return self.num_components
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
in_tensor = in_tensor / 4.0 + 0.5
line_coord = torch.stack([in_tensor[..., 2], in_tensor[..., 1], in_tensor[..., 0]]) # [3, ...]
line_coord = torch.stack([torch.zeros_like(line_coord), line_coord], dim=-1) # [3, ...., 2]
# Stop gradients from going to sampler
line_coord = line_coord.view(3, -1, 1, 2).detach()
line_features = F.grid_sample(self.line_coef, line_coord, align_corners=True) # [3, Components, -1, 1]
features = torch.prod(line_features, dim=0)
features = torch.moveaxis(features.view(self.num_components, *in_tensor.shape[:-1]), 0, -1)
return features # [..., Components]
@torch.no_grad()
def upsample_grid(self, resolution: int) -> None:
"""Upsamples underyling feature grid
Args:
resolution (int): Target resolution.
"""
self.line_coef.data = F.interpolate(
self.line_coef.data, size=(resolution, 1), mode="bilinear", align_corners=True
)
self.resolution = resolution
class TensorVMEncoding(Encoding):
"""Learned vector-matrix encoding proposed by TensoRF"""
def __init__(self, resolution: int = 256, num_components: int = 24, init_scale: float = 0.1) -> None:
"""
Args:
resolution (int, optional): Resolution of grid. Defaults to 256.
num_components (int, optional): Number of components per dimension. Defaults to 24.
init_scale (float, optional): Initialization scale. Defaults to 0.1.
"""
super().__init__(in_dim=3)
self.resolution = resolution
self.num_components = num_components
# TODO Learning rates should be different for these
self.plane_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, resolution)))
self.line_coef = nn.Parameter(init_scale * torch.randn((3, num_components, resolution, 1)))
def get_out_dim(self) -> int:
return self.num_components * 3
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
in_tensor = in_tensor / 4.0 + 0.5
plane_coord = torch.stack([in_tensor[..., [0, 1]], in_tensor[..., [0, 2]], in_tensor[..., [1, 2]]]) # [3,...,2]
line_coord = torch.stack([in_tensor[..., 2], in_tensor[..., 1], in_tensor[..., 0]]) # [3, ...]
line_coord = torch.stack([torch.zeros_like(line_coord), line_coord], dim=-1) # [3, ...., 2]
# Stop gradients from going to sampler
plane_coord = plane_coord.view(3, -1, 1, 2).detach()
line_coord = line_coord.view(3, -1, 1, 2).detach()
plane_features = F.grid_sample(self.plane_coef, plane_coord, align_corners=True) # [3, Components, -1, 1]
line_features = F.grid_sample(self.line_coef, line_coord, align_corners=True) # [3, Components, -1, 1]
features = plane_features * line_features # [3, Components, -1, 1]
features = torch.moveaxis(features.view(3 * self.num_components, *in_tensor.shape[:-1]), 0, -1)
return features # [..., 3 * Components]
@torch.no_grad()
def upsample_grid(self, resolution: int) -> None:
"""Upsamples underyling feature grid
Args:
resolution (int): Target resolution.
"""
self.plane_coef.data = F.interpolate(
self.plane_coef.data, size=(resolution, resolution), mode="bilinear", align_corners=True
)
self.line_coef.data = F.interpolate(
self.line_coef.data, size=(resolution, 1), mode="bilinear", align_corners=True
)
self.resolution = resolution
class SHEncoding(Encoding):
"""Spherical harmonic encoding"""
def __init__(self, levels: int = 4) -> None:
"""
Args:
levels (int, optional): Number of spherical hamonic levels to encode. Defaults to 4.
"""
super().__init__(in_dim=3)
if levels <= 0 or levels > 4:
raise ValueError(f"Spherical harmonic encoding only suports 1 to 4 levels, requested {levels}")
self.levels = levels
def get_out_dim(self) -> int:
return self.levels**2
@torch.no_grad()
def encode(self, in_tensor: TensorType[..., "input_dim"]) -> TensorType[..., "output_dim"]:
return components_from_spherical_harmonics(levels=self.levels, directions=in_tensor)
+143
View File
@@ -0,0 +1,143 @@
"""
Collection of render heads
"""
from enum import Enum
from typing import Optional
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.field_modules.base import FieldModule
class FieldHeadNames(Enum):
"""Possible field outputs"""
RGB = "rgb"
SH = "sh"
DENSITY = "density"
UNCERTAINTY = "uncertainty"
TRANSIENT_RGB = "transient_rgb"
TRANSIENT_DENSITY = "transient_density"
SEMANTICS_STUFF = "semantics_stuff"
SEMANTICS_THING = "semantics_thing"
class FieldHead(FieldModule):
"""Base field output"""
def __init__(
self,
out_dim: int,
field_head_name: FieldHeadNames,
in_dim: Optional[int] = None,
activation: Optional[nn.Module] = None,
) -> None:
"""
Args:
out_dim (int): output dimension for renderer
field_head_name (FieldHeadNames): Field type
in_dim (int, optional): input dimension. If not defined in constructor, it must be set later.
activation (Optional[nn.Module]): output head activation
"""
super().__init__()
self.out_dim = out_dim
self.activation = activation
self.field_head_name = field_head_name
self.net = None
if in_dim is not None:
self.in_dim = in_dim
self._construct_net()
def set_in_dim(self, in_dim: int) -> None:
"""Set input dimension of Field Head"""
self.in_dim = in_dim
self._construct_net()
def _construct_net(self):
layers = [nn.Linear(self.in_dim, self.out_dim)]
if self.activation:
layers.append(self.activation)
self.net = nn.Sequential(*layers)
def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType:
"""Process network output for renderer
Args:
in_tensor (TensorType[..., "in_dim]): Network input
Returns:
TensorType[..., "out_dim"]: Render head output
"""
if not self.net:
raise SystemError("in_dim not set. Must be provided to construtor, or set_in_dim() should be called.")
out_tensor = self.net(in_tensor)
return out_tensor
class DensityFieldHead(FieldHead):
"""Density output"""
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
super().__init__(in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.DENSITY, activation=activation)
class RGBFieldHead(FieldHead):
"""RGB output"""
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Sigmoid()) -> None:
super().__init__(in_dim=in_dim, out_dim=3, field_head_name=FieldHeadNames.RGB, activation=activation)
class SHFieldHead(FieldHead):
"""Spherical harmonics output"""
def __init__(
self, in_dim: Optional[int] = None, levels: int = 3, channels: int = 3, activation: Optional[nn.Module] = None
) -> None:
"""
Args:
in_dim (int): Input dimension
levels (int, optional): Number of spherical harmonics layers. Defaults to 3.
channels (int, optional): Number of channels. Defaults to 3 (ie RGB).
activation (Optional[nn.Module], optional): Output activation. Defaults to None.
"""
out_dim = channels * levels**2
super().__init__(in_dim=in_dim, out_dim=out_dim, field_head_name=FieldHeadNames.SH, activation=activation)
class UncertaintyFieldHead(FieldHead):
"""Uncertainty output"""
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
super().__init__(in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.UNCERTAINTY, activation=activation)
class TransientRGBHead(FieldHead):
"""Transient RGB output"""
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Sigmoid()) -> None:
super().__init__(in_dim=in_dim, out_dim=3, field_head_name=FieldHeadNames.TRANSIENT_RGB, activation=activation)
class TransientDensityHead(FieldHead):
"""Transient density output"""
def __init__(self, in_dim: Optional[int] = None, activation: Optional[nn.Module] = nn.Softplus()) -> None:
super().__init__(
in_dim=in_dim, out_dim=1, field_head_name=FieldHeadNames.TRANSIENT_DENSITY, activation=activation
)
class SemanticStuffHead(FieldHead):
"""Semantic stuff output"""
def __init__(self, num_classes: int, in_dim: Optional[int] = None) -> None:
"""
Args:
num_classes (int): Number of semantic classes
in_dim (int): Input dimension
"""
super().__init__(
in_dim=in_dim, out_dim=num_classes, field_head_name=FieldHeadNames.SEMANTICS_STUFF, activation=None
)
Whitespace-only changes.
+81
View File
@@ -0,0 +1,81 @@
"""
Multi Layer Perceptron
"""
from typing import Tuple, Optional
import torch
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.field_modules.base import FieldModule
class MLP(FieldModule):
"""Multilayer perceptron"""
def __init__(
self,
in_dim: int,
num_layers: int,
layer_width: int,
out_dim: Optional[int] = None,
skip_connections: Tuple[int] = (),
activation: Optional[nn.Module] = nn.ReLU(),
out_activation: Optional[nn.Module] = None,
) -> None:
"""Initialize parameters of mulilayer perceptron.
Args:
in_dim (int): Input layer dimension
num_layers (int): Number of network layers
layer_width (int): Width of each MLP layer
out_dim (int, optional): Ouput layer dimension. Defaults to layer_width
activation (Optional[nn.Module], optional): intermediate layer activation function. Defaults to nn.ReLU.
out_activation (Optional[nn.Module], optional): output activation function. Defaults to None.
"""
super().__init__()
self.in_dim = in_dim
assert self.in_dim > 0
self.out_dim = out_dim if out_dim is not None else layer_width
self.num_layers = num_layers
self.layer_width = layer_width
self.skip_connections = skip_connections
self.activation = activation
self.out_activation = out_activation
self.net = None
self.build_nn_modules()
def build_nn_modules(self) -> None:
"""Initialize multi-layer perceptron."""
layers = []
if self.num_layers == 1:
layers.append(nn.Linear(self.in_dim, self.out_dim))
else:
for i in range(self.num_layers - 1):
if i == 0:
assert i not in list(self.skip_connections), "Skip connection at layer 0 doesn't make sense."
layers.append(nn.Linear(self.in_dim, self.layer_width))
elif i in self.skip_connections:
layers.append(nn.Linear(self.layer_width + self.in_dim, self.layer_width))
else:
layers.append(nn.Linear(self.layer_width, self.layer_width))
layers.append(nn.Linear(self.layer_width, self.out_dim))
self.layers = nn.ModuleList(layers)
def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType[..., "out_dim"]:
"""Process input with a multilayer perceptron.
Args:
in_tensor (TensorType[..., "in_dim]): Network input
Returns:
TensorType[..., "out_dim"]: Network output
"""
x = in_tensor
for i, layer in enumerate(self.layers):
if i in self.skip_connections:
x = torch.cat([in_tensor, x], -1)
x = layer(x)
if self.activation:
x = self.activation(x)
return x
View File
Whitespace-only changes.
+82
View File
@@ -0,0 +1,82 @@
"""
Base class for the graphs.
"""
from abc import abstractmethod
from typing import Dict, Optional, Tuple
from torch import nn
import torch
from torchtyping import TensorType
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.structures.rays import PointSamples
from pyrad.utils.misc import is_not_none
class Field(nn.Module):
"""Base class for fields."""
def density_fn(self, positions):
"""Returns only the density. Used primarily with the occupancy grid."""
point_samples = PointSamples(positions=positions)
density, _ = self.get_density(point_samples)
return density
@abstractmethod
def get_density(self, point_samples: PointSamples) -> Tuple[TensorType[..., 1], TensorType[..., "num_features"]]:
"""Computes and returns the densities.
Args:
point_samples (PointSamples): Samples locations to compute density.
Returns:
Tuple[TensorType[...,1], TensorType[...,"num_features"]]: A tensor of densities and a tensor of features.
"""
@abstractmethod
def get_outputs(
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
) -> Dict[FieldHeadNames, TensorType]:
"""Computes and returns the colors.
Args:
point_samples (PointSamples): Samples locations to compute outputs.
density_embedding (TensorType, optional): Density embeddings to condition on.
Returns:
Dict[FieldHeadNames, TensorType]: Output field values.
"""
def forward(self, point_samples: PointSamples):
"""Evaluates the field at points along the ray."""
valid_mask = point_samples.valid_mask
if is_not_none(valid_mask):
# Hacky handling of empty masks. Tests on a single ray but doesn't use results
if not valid_mask.any():
point_samples = PointSamples(
positions=point_samples.positions[0, :], directions=point_samples.directions[0, :]
)
else:
point_samples = point_samples.apply_masks()
density_masked, density_embedding_masked = self.get_density(point_samples)
field_outputs_masked = self.get_outputs(point_samples, density_embedding=density_embedding_masked)
field_outputs = {}
for k, value in field_outputs_masked.items():
zeros = torch.zeros(*valid_mask.shape, value.shape[-1], dtype=torch.float32, device=valid_mask.device)
if valid_mask.any():
zeros[valid_mask] = value
else:
zeros[0, :] = value
field_outputs[k] = zeros
density = torch.zeros(*valid_mask.shape, 1, dtype=torch.float32, device=valid_mask.device)
if valid_mask.any():
density[valid_mask] = density_masked
else:
density, density_embedding = self.get_density(point_samples)
field_outputs = self.get_outputs(point_samples, density_embedding=density_embedding)
field_outputs[FieldHeadNames.DENSITY] = density
return field_outputs
+152
View File
@@ -0,0 +1,152 @@
"""
Instant-NGP field implementations using tiny-cuda-nn, torch, ....
"""
from typing import Tuple
import torch
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from pyrad.nerf.field_modules.encoding import Encoding, HashEncoding, SHEncoding
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.nerf.fields.base import Field
from pyrad.nerf.fields.nerf_field import NeRFField
from pyrad.structures.rays import PointSamples
from pyrad.utils.misc import is_not_none
try:
import tinycudann as tcnn
except ImportError as e:
# tinycudann module doesn't exist
pass
def get_normalized_positions(positions, aabb):
"""Return normalized positions in range [0, 1] based on the aabb axis-aligned bounding box."""
aabb_lengths = aabb[1] - aabb[0]
positions = (positions - aabb[0]) / aabb_lengths
return positions
class TCNNInstantNGPField(Field):
"""NeRF Field"""
def __init__(
self, aabb, num_layers=2, hidden_dim=64, geo_feat_dim=15, num_layers_color=3, hidden_dim_color=64
) -> None:
super().__init__()
# TODO: make this a parameter that is put to the correct device
self.aabb = Parameter(aabb, requires_grad=False)
self.geo_feat_dim = geo_feat_dim
# TODO: set this properly based on the aabb
per_level_scale = 1.4472692012786865
self.position_encoding = tcnn.Encoding(
n_input_dims=3,
encoding_config={
"otype": "HashGrid",
"n_levels": 16,
"n_features_per_level": 2,
"log2_hashmap_size": 19,
"base_resolution": 16,
"per_level_scale": per_level_scale,
},
)
self.direction_encoding = tcnn.Encoding(
n_input_dims=3,
encoding_config={
"otype": "SphericalHarmonics",
"degree": 4,
},
)
self.mlp_base = tcnn.Network(
n_input_dims=32,
n_output_dims=1 + self.geo_feat_dim,
network_config={
"otype": "FullyFusedMLP",
"activation": "ReLU",
"output_activation": "None",
"n_neurons": hidden_dim,
"n_hidden_layers": num_layers - 1,
},
)
self.mlp_head = tcnn.Network(
n_input_dims=self.direction_encoding.n_output_dims + self.geo_feat_dim,
n_output_dims=3,
network_config={
"otype": "FullyFusedMLP",
"activation": "ReLU",
"output_activation": "None",
"n_neurons": hidden_dim_color,
"n_hidden_layers": num_layers_color - 1,
},
)
def get_density(self, point_samples: PointSamples):
"""Computes and returns the densities."""
# TODO: add valid_mask masking!
# remap positions to range 0 to 1 based on the aabb
positions = get_normalized_positions(point_samples.positions, self.aabb)
positions_flat = positions.view(-1, 3)
dtype = positions_flat.dtype
x = self.position_encoding(positions_flat)
h = self.mlp_base(x).view(*point_samples.positions.shape[:-1], -1).to(dtype)
density_before_activation, base_mlp_out = torch.split(h, [1, self.geo_feat_dim], dim=-1)
density = F.softplus(density_before_activation)
return density, base_mlp_out
def get_outputs(self, point_samples: PointSamples, density_embedding=None):
# TODO: add valid_mask masking!
assert is_not_none(density_embedding)
directions = point_samples.directions
directions_flat = directions.view(-1, 3)
dtype = directions_flat.dtype
d = self.direction_encoding(directions_flat)
h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim)], dim=-1)
h = self.mlp_head(h).view(*point_samples.directions.shape[:-1], -1).to(dtype)
rgb = torch.sigmoid(h)
return {FieldHeadNames.RGB: rgb}
class TorchInstantNGPField(NeRFField):
"""
PyTorch implementation of the instant-ngp field.
"""
def __init__(
self,
aabb,
position_encoding: Encoding = HashEncoding(),
direction_encoding: Encoding = SHEncoding(),
base_mlp_num_layers: int = 3,
base_mlp_layer_width: int = 64,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 32,
skip_connections: Tuple = (4,),
) -> None:
super().__init__(
position_encoding,
direction_encoding,
base_mlp_num_layers,
base_mlp_layer_width,
head_mlp_num_layers,
head_mlp_layer_width,
skip_connections,
)
self.aabb = Parameter(aabb, requires_grad=False)
def get_density(self, point_samples: PointSamples):
normalized_point_samples = point_samples
normalized_point_samples.positions = get_normalized_positions(normalized_point_samples.positions, self.aabb)
return super().get_density(normalized_point_samples)
field_implementation_to_class = {"tcnn": TCNNInstantNGPField, "torch": TorchInstantNGPField}
+80
View File
@@ -0,0 +1,80 @@
""" Classic NeRF field"""
from typing import Dict, Optional, Tuple
import torch
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.field_modules.encoding import Encoding, Identity
from pyrad.nerf.field_modules.field_heads import DensityFieldHead, FieldHead, FieldHeadNames, RGBFieldHead
from pyrad.nerf.field_modules.mlp import MLP
from pyrad.nerf.fields.base import Field
from pyrad.structures.rays import PointSamples
class NeRFField(Field):
"""NeRF Field"""
def __init__(
self,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
) -> None:
"""Create boilerplate NeRF field.
Args:
position_encoding (Encoding, optional): Position encoder. Defaults to Identity(in_dim=3).
direction_encoding (Encoding, optional): Direction encoder. Defaults to Identity(in_dim=3).
base_mlp_num_layers (int, optional): Number of layers for base MLP. Defaults to 8.
base_mlp_layer_width (int, optional): Width of base MLP layers. Defaults to 256.
head_mlp_num_layers (int, optional): Number of layer for ourput head MLP. Defaults to 2.
head_mlp_layer_width (int, optional): Width of output head MLP layers. Defaults to 128.
skip_connections (Tuple, optional): Where to add skip connection in base MLP. Defaults to (4,).
"""
super().__init__()
self.position_encoding = position_encoding
self.direction_encoding = direction_encoding
self.mlp_base = MLP(
in_dim=self.position_encoding.get_out_dim(),
num_layers=base_mlp_num_layers,
layer_width=base_mlp_layer_width,
skip_connections=skip_connections,
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
num_layers=head_mlp_num_layers,
layer_width=head_mlp_layer_width,
)
self.field_output_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
self.field_heads = nn.ModuleList(field_heads)
for field_head in self.field_heads:
field_head.set_in_dim(self.mlp_head.get_out_dim())
def get_density(self, point_samples: PointSamples):
"""Computes and returns the densities."""
encoded_xyz = self.position_encoding(point_samples.positions)
base_mlp_out = self.mlp_base(encoded_xyz)
density = self.field_output_density(base_mlp_out)
return density, base_mlp_out
def get_outputs(
self, point_samples: PointSamples, density_embedding: Optional[TensorType] = None
) -> Dict[FieldHeadNames, TensorType]:
"""Computes and returns the outputs."""
outputs = {}
for field_head in self.field_heads:
encoded_dir = self.direction_encoding(point_samples.directions)
mlp_out = self.mlp_head(torch.cat([encoded_dir, density_embedding], dim=-1))
outputs[field_head.field_head_name] = field_head(mlp_out)
return outputs
+162
View File
@@ -0,0 +1,162 @@
"""
The Graph module contains all trainable parameters.
"""
from abc import abstractmethod
from collections import defaultdict
from typing import Dict, List, Union
import torch
from omegaconf import DictConfig
from torch import nn
from torch.nn import Parameter
from torchtyping import TensorType
from pyrad.nerf.dataset.structs import SceneBounds
from pyrad.nerf.ray_generator import RayGenerator
from pyrad.nerf.colliders import AABBBoxCollider
from pyrad.structures.cameras import get_camera_model
from pyrad.structures.rays import RayBundle
from pyrad.utils.misc import get_masked_dict
from pyrad.utils.misc import is_not_none
class AbstractGraph(nn.Module):
"""Highest level graph class. Somewhat useful to lift code up and out of the way."""
def __init__(self) -> None:
super().__init__()
# 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
def forward(
self,
ray_indices: TensorType["num_rays", 3],
batch: Union[str, Dict[str, torch.tensor]] = None,
step: int = None,
):
"""Process starting with ray indices. Turns them into rays, then performs volume rendering."""
class Graph(AbstractGraph):
"""_summary_"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
loss_coefficients: DictConfig = None,
steps_per_occupancy_grid_update=16,
scene_bounds: SceneBounds = None,
**kwargs,
) -> None:
super().__init__()
assert is_not_none(scene_bounds), "scene_bounds is needed to use the occupancy grid"
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
self.scene_bounds = scene_bounds
self.loss_coefficients = loss_coefficients
self.steps_per_occupancy_grid_update = steps_per_occupancy_grid_update
self.kwargs = kwargs
self.collider = None
self.ray_generator = RayGenerator(self.intrinsics, self.camera_to_world)
self.populate_collider()
self.populate_fields()
self.populate_misc_modules() # populate the modules
def populate_collider(self):
"""Set the scene bounds collider to use."""
self.collider = AABBBoxCollider(self.scene_bounds)
@abstractmethod
def populate_misc_modules(self):
"""Initializes any additional modules that are part of the network."""
@abstractmethod
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
"""
@abstractmethod
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,
step: int = None,
):
# get the rays
original_ray_bundle = self.ray_generator.forward(ray_indices) # RayBundle
intersected_ray_bundle = self.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) # NOTE(ethan): this is really slow if on CPU!
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]:
"""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, training_camera_index=0):
"""Takes in camera parameters and computes the output of the graph."""
# NOTE(ethan): this function has a spike in CPU usage
device = self.get_device()
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()
# TODO(ethan): decide how to properly handle the image indices for validation images
camera_ray_bundle.set_camera_indices(camera_index=training_camera_index)
camera_ray_bundle.move_to_device(device)
image_height, image_width = camera_ray_bundle.origins.shape[:2]
num_rays = len(camera_ray_bundle)
outputs = {}
outputs_lists = defaultdict(list)
for i in range(0, num_rays, chunk_size):
start_idx = i
end_idx = i + chunk_size
original_ray_bundle = camera_ray_bundle.get_row_major_sliced_ray_bundle(start_idx, end_idx)
intersected_ray_bundle = self.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():
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, mask, outputs):
"""Writes the test image outputs."""
+152
View File
@@ -0,0 +1,152 @@
"""
Implementation of Instant NGP.
"""
from typing import Dict, List
import torch
from torch.nn import Parameter
from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from pyrad.nerf.colliders import AABBBoxCollider
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.nerf.fields.instant_ngp_field import field_implementation_to_class
from pyrad.nerf.graph.base import Graph
from pyrad.nerf.loss import MSELoss
from pyrad.nerf.occupancy_grid import OccupancyGrid
from pyrad.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
from pyrad.nerf.sampler import PDFSampler, UniformSampler
from pyrad.structures import colors
from pyrad.structures.rays import RayBundle
from pyrad.utils import visualization, writer
class NGPGraph(Graph):
"""Instant NGP graph"""
def __init__(self, field_implementation="torch", intrinsics=None, camera_to_world=None, **kwargs) -> None:
assert field_implementation in field_implementation_to_class
self.field_implementation = field_implementation
self.field = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
def populate_collider(self):
self.collider = AABBBoxCollider(self.scene_bounds)
def populate_fields(self):
"""Set the fields."""
# torch or tiny-cuda-nn version
self.field = field_implementation_to_class[self.field_implementation](self.scene_bounds.aabb)
def populate_misc_modules(self):
# occupancy grid
self.occupancy_grid = OccupancyGrid(aabb=self.scene_bounds.aabb)
# samplers
self.sampler_occupancy_grid = UniformSampler(num_samples=128, occupancy_field=self.occupancy_grid)
# NOTE(ethan): are we sure we want the include_original flag used like this?
# it could be easily forgotten that it's by default True...?
self.sampler_pdf = PDFSampler(num_samples=128, include_original=False)
# renderers
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
self.renderer_accumulation = AccumulationRenderer()
self.renderer_depth = DepthRenderer()
# losses
self.rgb_loss = MSELoss()
# metrics
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
self.ssim = StructuralSimilarityIndexMeasure()
self.lpips = LearnedPerceptualImagePatchSimilarity()
def get_param_groups(self) -> Dict[str, List[Parameter]]:
param_groups = {}
param_groups["fields"] = list(self.field.parameters())
return param_groups
def get_outputs(self, ray_bundle: RayBundle):
# uniform sampling
ray_samples_uniform = self.sampler_occupancy_grid(ray_bundle)
field_outputs_uniform = self.field.forward(ray_samples_uniform.to_point_samples())
weights_uniform = ray_samples_uniform.get_weights(field_outputs_uniform[FieldHeadNames.DENSITY])
# pdf sampling
ray_samples_pdf = self.sampler_pdf(ray_bundle, ray_samples_uniform, weights_uniform)
field_outputs_pdf = self.field.forward(ray_samples_pdf.to_point_samples())
ts, indices = torch.sort(torch.cat([ray_samples_uniform.ts, ray_samples_pdf.ts], -1), -1)
ray_samples = ray_bundle.get_ray_samples(ts)
field_outputs = {}
for fo_name, _ in field_outputs_pdf.items():
fo_uniform = field_outputs_uniform[fo_name]
fo_pdf = field_outputs_pdf[fo_name]
fo_uniform_pdf = torch.cat([fo_uniform, fo_pdf], 1)
index = indices.view(fo_uniform_pdf[..., :1].shape)
index = index.expand(-1, -1, fo_uniform_pdf.shape[-1]) # TODO: don't hardcode this
field_outputs[fo_name] = torch.gather(fo_uniform_pdf, dim=1, index=index)
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
rgb = self.renderer_rgb(
rgb=field_outputs[FieldHeadNames.RGB],
weights=weights,
)
accumulation = self.renderer_accumulation(weights)
depth = self.renderer_depth(weights, ray_samples.ts)
densities_occupancy_grid = self.occupancy_grid.get_densities(ray_samples.positions)
weights_occupancy_grid = ray_samples.get_weights(densities_occupancy_grid)
depth_occupancy_grid = self.renderer_depth(weights_occupancy_grid, ray_samples.ts)
outputs = {
"rgb": rgb,
"accumulation": accumulation,
"depth": depth,
"depth_occupancy_grid": depth_occupancy_grid,
}
return outputs
def get_loss_dict(self, outputs, batch):
device = self.get_device()
pixels = batch["pixels"].to(device)
rgb_loss = self.rgb_loss(pixels, outputs["rgb"])
loss_dict = {"rgb_loss": rgb_loss}
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, mask, outputs):
rgb = outputs["rgb"]
acc = visualization.apply_colormap(outputs["accumulation"])
depth = visualization.apply_depth_colormap(
outputs["depth"],
accumulation=outputs["accumulation"],
)
combined_rgb = torch.cat([image, rgb], dim=1)
combined_acc = torch.cat([acc], dim=1)
combined_depth = torch.cat([depth], dim=1)
writer.put_image(name=f"img/image_idx_{image_idx}", image=combined_rgb, step=step)
writer.put_image(name=f"accumulation/image_idx_{image_idx}", image=combined_acc, step=step)
writer.put_image(name=f"depth/image_idx_{image_idx}", image=combined_depth, step=step)
depth = visualization.apply_depth_colormap(outputs["depth_occupancy_grid"])
writer.put_image(name=f"depth_occupancy_grid/image_idx_{image_idx}", image=combined_depth, step=step)
# Switch images from [H, W, C] to [1, C, H, W] for metrics computations
image = torch.moveaxis(image, -1, 0)[None, ...]
rgb = torch.moveaxis(rgb, -1, 0)[None, ...]
psnr = self.psnr(image, rgb)
ssim = self.ssim(image, rgb)
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"lpips/val_{image_idx}", scalar=float(lpips), step=step)
return psnr.item()
+213
View File
@@ -0,0 +1,213 @@
"""
NeRF-W (NeRF in the wild) implementation.
TODO:
"""
from typing import Tuple
import torch
from torch import nn
from pyrad.nerf.field_modules.embedding import Embedding
from pyrad.nerf.field_modules.field_heads import (
FieldHeadNames,
TransientDensityHead,
TransientRGBHead,
UncertaintyFieldHead,
)
from pyrad.nerf.field_modules.mlp import MLP
from pyrad.nerf.graph.vanilla_nerf import NeRFField, NeRFGraph
from pyrad.nerf.renderers import UncertaintyRenderer
from pyrad.structures.rays import RayBundle, RaySamples
from pyrad.utils import visualization, writer
class NerfWField(Field):
"""The NeRF-W field which has appearance and transient conditioning."""
def __init__(
self,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
) -> None:
super().__init__()
self.num_images = num_images
self.appearance_embedding_dim = 48
self.transient_embedding_dim = 16
self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim)
self.embedding_transient = Embedding(self.num_images, self.transient_embedding_dim)
self.mlp_transient = MLP(
in_dim=self.mlp_base.get_out_dim() + self.embedding_transient.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=4,
layer_width=self.layer_width,
activation=nn.ReLU(),
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim()
+ self.encoding_dir.get_out_dim()
+ self.embedding_appearance.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
def build_heads(self):
super().build_heads()
self.field_output_transient_uncertainty = UncertaintyFieldHead(in_dim=self.mlp_transient.get_out_dim())
self.field_output_transient_rgb = TransientRGBHead(in_dim=self.mlp_transient.get_out_dim())
self.field_output_transient_density = TransientDensityHead(in_dim=self.mlp_transient.get_out_dim())
def forward(self, ray_samples: RaySamples):
positions = ray_samples.positions
directions = ray_samples.directions
camera_indices = ray_samples.get_camera_indices()
encoded_xyz = self.encoding_xyz(positions)
encoded_dir = self.encoding_dir(directions)
embedded_appearance = self.embedding_appearance(camera_indices)
embedded_transient = self.embedding_transient(camera_indices)
base_mlp_out = self.mlp_base(encoded_xyz)
rgb_mlp_out = self.mlp_rgb(torch.cat([base_mlp_out, encoded_dir, embedded_appearance], dim=-1))
transient_mlp_out = self.mlp_transient(torch.cat([base_mlp_out, embedded_transient], dim=-1))
field_rgb_output = self.field_output_rgb(rgb_mlp_out)
field_density_out = self.field_output_density(base_mlp_out)
field_transient_uncertainty_out = self.field_output_transient_uncertainty(transient_mlp_out)
field_transient_rgb_out = self.field_output_transient_rgb(transient_mlp_out)
field_transient_density_out = self.field_output_transient_density(transient_mlp_out)
field_outputs = {}
field_outputs.update(field_rgb_output)
field_outputs.update(field_density_out)
field_outputs.update(field_transient_uncertainty_out)
field_outputs.update(field_transient_rgb_out)
field_outputs.update(field_transient_density_out)
return field_outputs
class NerfWGraph(NeRFGraph):
"""NeRF-W graph"""
def __init__(self, intrinsics=None, camera_to_world=None, **kwargs) -> None:
self.num_images = len(intrinsics)
self.appearance_embedding_dim = 48
self.transient_embedding_dim = 16
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
self.renderer_uncertainty = UncertaintyRenderer()
def populate_fields(self):
"""Set the fields."""
self.field_coarse = NeRFField()
self.field_fine = NerfWField(
num_images=self.num_images,
appearance_embedding_dim=self.appearance_embedding_dim,
transient_embedding_dim=self.transient_embedding_dim,
)
def get_outputs(self, ray_bundle: RayBundle):
# coarse network
uniform_ray_samples = self.sampler_uniform(ray_bundle)
coarse_field_outputs = self.field_coarse(uniform_ray_samples)
coarse_weights = uniform_ray_samples.get_weights(coarse_field_outputs[FieldHeadNames.DENSITY])
rgb_coarse = self.renderer_rgb(
rgb=coarse_field_outputs[FieldHeadNames.RGB],
weights=coarse_weights,
).rgb
depth_coarse = self.renderer_depth(coarse_weights, uniform_ray_samples.ts).depth
# fine network
pdf_ray_samples = self.sampler_pdf(uniform_ray_samples, coarse_weights)
fine_field_outputs = self.field_fine(pdf_ray_samples)
fine_weights = pdf_ray_samples.get_weights(
fine_field_outputs[FieldHeadNames.DENSITY] + fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
)
fine_weights_static = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.DENSITY])
fine_weights_transient = pdf_ray_samples.get_weights(fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY])
rgb_fine_static_component = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.RGB],
weights=fine_weights,
).rgb
rgb_fine_transient_component = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.TRANSIENT_RGB],
weights=fine_weights,
).rgb
rgb_fine = rgb_fine_static_component + rgb_fine_transient_component
rgb_fine_static = self.renderer_rgb(
rgb=fine_field_outputs[FieldHeadNames.RGB],
weights=fine_weights_static,
).rgb
# fine_renderer_accumulation_static = self.renderer_accumulation(fine_weights_static)
depth_fine = self.renderer_depth(fine_weights, pdf_ray_samples.ts).depth
depth_fine_static = self.renderer_depth(fine_weights_static, pdf_ray_samples.ts).depth
uncertainty = self.renderer_uncertainty(
fine_field_outputs[FieldHeadNames.UNCERTAINTY], fine_weights_transient
).uncertainty
density_transient = fine_field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
# outputs:
outputs = {
"rgb_coarse": rgb_coarse, # (num_rays, 3)
"rgb_fine": rgb_fine,
"rgb_fine_static": rgb_fine_static,
"depth_coarse": depth_coarse,
"depth_fine": depth_fine,
"depth_fine_static": depth_fine_static,
"density_transient": density_transient, # (num_rays, num_samples, 1)
"uncertainty": uncertainty, # (num_rays, 1)
}
return outputs
def get_loss_dict(self, outputs, batch):
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
density_transient = outputs["density_transient"]
betas = outputs["uncertainty"]
rgb_loss_coarse = 0.5 * ((pixels - rgb_coarse) ** 2).sum(-1).mean()
rgb_loss_fine = 0.5 * (((pixels - rgb_fine) ** 2).sum(-1) / (betas[..., 0] ** 2)).mean()
uncertainty_loss = 0.5 * (3 + torch.log(betas)).mean()
density_loss = density_transient.mean()
loss_dict = {
"rgb_loss_coarse": rgb_loss_coarse,
"rgb_loss_fine": rgb_loss_fine,
"uncertainty_loss": uncertainty_loss,
"density_loss": density_loss,
}
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, mask, outputs):
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
rgb_fine_static = outputs["rgb_fine_static"]
depth_coarse = outputs["depth_coarse"]
depth_fine = outputs["depth_fine"]
depth_fine_static = outputs["depth_fine_static"]
uncertainty = outputs["uncertainty"]
depth_coarse = visualization.apply_depth_colormap(depth_coarse)
depth_fine = visualization.apply_depth_colormap(depth_fine)
depth_fine_static = visualization.apply_depth_colormap(depth_fine_static)
uncertainty = visualization.apply_depth_colormap(uncertainty)
row0 = torch.cat([image, uncertainty, torch.ones_like(rgb_fine)], dim=-2)
row1 = torch.cat([rgb_fine, rgb_fine_static, rgb_coarse], dim=-2)
row2 = torch.cat([depth_fine, depth_fine_static, depth_coarse], dim=-2)
combined_image = torch.cat([row0, row1, row2], dim=-3)
writer.put_image(name="img/image_idx_{image_idx}-nerfw", image=combined_image, step=step)
+158
View File
@@ -0,0 +1,158 @@
"""
Semantic NeRF implementation.
"""
from typing import Tuple
import torch
from torch import nn
from pyrad.nerf.field_modules.field_heads import FieldHeadNames, SemanticStuffHead
from pyrad.nerf.field_modules.mlp import MLP
from pyrad.nerf.graph.vanilla_nerf import NeRFField, NeRFGraph
from pyrad.nerf.renderers import SemanticRenderer
from pyrad.structures.rays import RayBundle, RaySamples
from pyrad.utils import visualization, writer
class SemanticNerfField(NeRFField):
"""Semantic-NeRF field"""
def __init__(
self, num_layers=8, layer_width=256, skip_connections: Tuple = (4,), num_stuff_classes: int = None
) -> None:
assert num_stuff_classes is not None
self.num_stuff_classes = num_stuff_classes
super().__init__(num_layers=num_layers, layer_width=layer_width, skip_connections=skip_connections)
self.semantic_mlp = MLP(
in_dim=self.mlp_base.get_out_dim(),
out_dim=self.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
)
self.field_output_semantic = SemanticStuffHead(
in_dim=self.semantic_mlp.get_out_dim(), num_classes=num_stuff_classes
)
self.semantic_sequential = torch.nn.Sequential(self.semantic_mlp, self.field_output_semantic)
def forward(self, ray_samples: RaySamples):
"""Evaluates the field at points along the ray."""
positions = ray_samples.positions
directions = ray_samples.directions
encoded_xyz = self.encoding_xyz(positions)
encoded_dir = self.encoding_dir(directions)
base_mlp_out = self.mlp_base(encoded_xyz)
rgb_mlp_out = self.mlp_rgb(torch.cat([encoded_dir, base_mlp_out], dim=-1))
field_rgb_output = self.field_output_rgb(rgb_mlp_out)
field_density_out = self.field_output_density(base_mlp_out)
field_semantic_output = self.semantic_sequential(base_mlp_out)
field_outputs = {}
field_outputs.update(field_rgb_output)
field_outputs.update(field_density_out)
field_outputs.update(field_semantic_output)
return field_outputs
class SemanticNerfGraph(NeRFGraph):
"""Semantic-NeRF graph"""
def __init__(self, intrinsics=None, camera_to_world=None, stuff_classes: int = None, **kwargs) -> None:
assert stuff_classes is not None
self.stuff_classes = stuff_classes
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
self.renderer_semantic = SemanticRenderer()
self.cross_entropy_loss = nn.CrossEntropyLoss(reduction="mean")
def populate_fields(self):
"""Set the fields."""
self.field_coarse = NeRFField()
self.field_fine = SemanticNerfField(num_stuff_classes=len(self.stuff_classes))
def get_outputs(self, ray_bundle: RayBundle):
# coarse network:
uniform_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples
coarse_field_outputs = self.field_coarse(uniform_ray_samples) # FieldOutputs
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
coarse_renderer_accumulation = self.renderer_accumulation(coarse_weights) # RendererOutputs
coarse_renderer_depth = self.renderer_depth(coarse_weights, uniform_ray_samples.ts)
# 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
fine_renderer_accumulation = self.renderer_accumulation(fine_weights) # RendererOutputs
fine_renderer_depth = self.renderer_depth(fine_weights, pdf_ray_samples.ts)
# TODO refactor this into "vis" section. Doesn't need to be run during training.
coarse_renderer_depth = visualization.apply_depth_colormap(
coarse_renderer_depth.depth,
accumulation=coarse_renderer_accumulation.accumulation,
near_plane=self.near_plane,
far_plane=self.far_plane,
)
fine_renderer_depth = visualization.apply_depth_colormap(
fine_renderer_depth.depth,
accumulation=fine_renderer_accumulation.accumulation,
near_plane=self.near_plane,
far_plane=self.far_plane,
)
coarse_renderer_accumulation = visualization.apply_colormap(coarse_renderer_accumulation.accumulation)
fine_renderer_accumulation = visualization.apply_colormap(fine_renderer_accumulation.accumulation)
semantic_logits = self.renderer_semantic(
fine_field_outputs[FieldHeadNames.SEMANTICS_STUFF], weights=fine_weights
).semantics
# outputs:
outputs = {
"rgb_coarse": coarse_renderer_outputs.rgb,
"rgb_fine": fine_renderer_outputs.rgb,
"accumulation_coarse": coarse_renderer_accumulation,
"accumulation_fine": fine_renderer_accumulation,
"depth_coarse": coarse_renderer_depth,
"depth_fine": fine_renderer_depth,
"semantic_logits": semantic_logits,
}
return outputs
def get_loss_dict(self, outputs, batch):
# TODO(ethan): batch has "stuff_image". use it
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_loss_coarse = self.rgb_loss(pixels, outputs["rgb_coarse"])
rgb_loss_fine = self.rgb_loss(pixels, outputs["rgb_fine"])
semantic_logits = outputs["semantic_logits"]
semantic_classes = batch["stuff_image"][..., 0].to(device).long()
semantic_loss_fine = self.cross_entropy_loss(semantic_logits, semantic_classes)
loss_dict = {
"rgb_loss_coarse": rgb_loss_coarse,
"rgb_loss_fine": rgb_loss_fine,
"semantic_loss_fine": semantic_loss_fine,
}
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, mask, outputs):
super().log_test_image_outputs(image_idx, step, image, mask, outputs)
semantic_labels = torch.argmax(torch.nn.functional.softmax(outputs["semantic_logits"], dim=-1), dim=-1) / len(
self.stuff_classes
)
semantic_labels_image = visualization.apply_colormap(semantic_labels[..., None])
writer.put_image(name="semantics/image_idx_{image_idx}", image=semantic_labels_image, step=step)
+4
View File
@@ -0,0 +1,4 @@
"""
TensorRF implementation.
TODO:
"""
+177
View File
@@ -0,0 +1,177 @@
"""
Implementation of vanilla nerf.
"""
from typing import Dict, List
import torch
from torch.nn import Parameter
from torchmetrics import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from pyrad.nerf.field_modules.encoding import NeRFEncoding
from pyrad.nerf.field_modules.field_heads import FieldHeadNames
from pyrad.nerf.fields.nerf_field import NeRFField
from pyrad.nerf.graph.base import Graph
from pyrad.nerf.loss import MSELoss
from pyrad.nerf.renderers import AccumulationRenderer, DepthRenderer, RGBRenderer
from pyrad.nerf.sampler import PDFSampler, UniformSampler
from pyrad.structures import colors
from pyrad.structures.rays import RayBundle
from pyrad.nerf.colliders import NearFarCollider
from pyrad.utils import visualization, writer
class NeRFGraph(Graph):
"""Vanilla NeRF graph"""
def __init__(
self,
intrinsics=None,
camera_to_world=None,
near_plane=2.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
self.field_coarse = None
self.field_fine = None
super().__init__(intrinsics=intrinsics, camera_to_world=camera_to_world, **kwargs)
def populate_collider(self):
self.collider = NearFarCollider(self.near_plane, self.far_plane)
def populate_fields(self):
"""Set the fields."""
position_encoding = NeRFEncoding(
in_dim=3, num_frequencies=10, min_freq_exp=0.0, max_freq_exp=8.0, include_input=True
)
direction_encoding = NeRFEncoding(
in_dim=3, num_frequencies=4, min_freq_exp=0.0, max_freq_exp=4.0, include_input=True
)
self.field_coarse = NeRFField(position_encoding=position_encoding, direction_encoding=direction_encoding)
self.field_fine = NeRFField(position_encoding=position_encoding, direction_encoding=direction_encoding)
def populate_misc_modules(self):
# samplers
self.sampler_uniform = UniformSampler(num_samples=self.num_coarse_samples)
self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
# renderers
self.renderer_rgb = RGBRenderer(background_color=colors.WHITE)
self.renderer_accumulation = AccumulationRenderer()
self.renderer_depth = DepthRenderer()
# losses
self.rgb_loss = MSELoss()
# metrics
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
self.ssim = StructuralSimilarityIndexMeasure()
self.lpips = LearnedPerceptualImagePatchSimilarity()
def get_param_groups(self) -> Dict[str, List[Parameter]]:
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):
# uniform sampling
ray_samples_uniform = self.sampler_uniform(ray_bundle)
# coarse field:
field_outputs_coarse = self.field_coarse.forward(ray_samples_uniform.to_point_samples())
weights_coarse = ray_samples_uniform.get_weights(field_outputs_coarse[FieldHeadNames.DENSITY])
rgb_coarse = self.renderer_rgb(
rgb=field_outputs_coarse[FieldHeadNames.RGB],
weights=weights_coarse,
)
accumulation_coarse = self.renderer_accumulation(weights_coarse)
depth_coarse = self.renderer_depth(weights_coarse, ray_samples_uniform.ts)
# pdf sampling
ray_samples_pdf = self.sampler_pdf(ray_bundle, ray_samples_uniform, weights_coarse)
# fine field:
field_outputs_fine = self.field_fine.forward(ray_samples_pdf.to_point_samples())
weights_fine = ray_samples_pdf.get_weights(field_outputs_fine[FieldHeadNames.DENSITY])
rgb_fine = self.renderer_rgb(
rgb=field_outputs_fine[FieldHeadNames.RGB],
weights=weights_fine,
)
accumulation_fine = self.renderer_accumulation(weights_fine)
depth_fine = self.renderer_depth(weights_fine, ray_samples_pdf.ts)
outputs = {
"rgb_coarse": rgb_coarse,
"rgb_fine": rgb_fine,
"accumulation_coarse": accumulation_coarse,
"accumulation_fine": accumulation_fine,
"depth_coarse": depth_coarse,
"depth_fine": depth_fine,
}
return outputs
def get_loss_dict(self, outputs, batch):
device = outputs["rgb_coarse"].device
pixels = batch["pixels"].to(device)
rgb_loss_coarse = self.rgb_loss(pixels, outputs["rgb_coarse"])
rgb_loss_fine = self.rgb_loss(pixels, outputs["rgb_fine"])
loss_dict = {"rgb_loss_coarse": rgb_loss_coarse, "rgb_loss_fine": rgb_loss_fine}
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, mask, outputs):
rgb_coarse = outputs["rgb_coarse"]
rgb_fine = outputs["rgb_fine"]
acc_coarse = visualization.apply_colormap(outputs["accumulation_coarse"])
acc_fine = visualization.apply_colormap(outputs["accumulation_fine"])
depth_coarse = visualization.apply_depth_colormap(
outputs["depth_coarse"],
accumulation=outputs["accumulation_coarse"],
near_plane=self.near_plane,
far_plane=self.far_plane,
)
depth_fine = visualization.apply_depth_colormap(
outputs["depth_fine"],
accumulation=outputs["accumulation_fine"],
near_plane=self.near_plane,
far_plane=self.far_plane,
)
combined_rgb = torch.cat([image, rgb_coarse, rgb_fine], dim=1)
combined_acc = torch.cat([acc_coarse, acc_fine], dim=1)
combined_depth = torch.cat([depth_coarse, depth_fine], dim=1)
mask = visualization.apply_depth_colormap(mask[..., None])
writer.put_image(name=f"img/image_idx_{image_idx}", image=combined_rgb, step=step)
writer.put_image(name=f"accumulation/image_idx_{image_idx}", image=combined_acc, step=step)
writer.put_image(name=f"depth/image_idx_{image_idx}", image=combined_depth, step=step)
writer.put_image(name=f"mask/image_idx_{image_idx}", image=mask, step=step)
# Switch images from [H, W, C] to [1, C, H, W] for metrics computations
image = torch.moveaxis(image, -1, 0)[None, ...]
rgb_coarse = torch.moveaxis(rgb_coarse, -1, 0)[None, ...]
rgb_fine = torch.moveaxis(rgb_fine, -1, 0)[None, ...]
coarse_psnr = self.psnr(image, rgb_coarse)
fine_psnr = self.psnr(image, rgb_fine)
fine_ssim = self.ssim(image, rgb_fine)
fine_lpips = self.lpips(image, rgb_fine)
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"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)
return fine_psnr.item()
+9
View File
@@ -0,0 +1,9 @@
"""
Collection of Losses
"""
from torch import nn
L1Loss = nn.L1Loss
MSELoss = nn.MSELoss
LOSSES = {"L1": L1Loss, "MSE": MSELoss}
+133
View File
@@ -0,0 +1,133 @@
"""
Code to implement the density grid.
"""
import torch
import torch.nn.functional as F
from torch import nn
from torchtyping import TensorType
from pyrad.utils.misc import is_not_none
class OccupancyGrid(nn.Module):
"""Module to keep track of the density and occupancy."""
def __init__(
self, num_cascades=1, resolution=128, aabb=None, density_fn=None, update_every_num_iters: int = 16
) -> None:
super().__init__()
assert is_not_none(aabb), "The axis-aligned bounding box aabb is not defined!"
self.num_cascades = num_cascades # the number of levels (i.e, cascades)
self.resolution = resolution
self.register_buffer("aabb", aabb) # axis-aligned bounding box
occupancy_grid = torch.ones(
[self.num_cascades] + [self.resolution] * 3
) # (num_cascades, x_resolution, y_resolution, z_resolution)
# not a module parameter, but it still should be saved and part of `state_dict`
self.register_buffer("occupancy_grid", occupancy_grid)
self.mean_density = 0.0
self.density_fn = density_fn
self.update_every_num_iters = update_every_num_iters
self.iteration_count = 0
def reset(self):
"""Zero out the occupancy grid."""
self.occupancy_grid.zero_()
@torch.no_grad()
def mark_untrained_grid(self):
"""Marks the locations in the density grid that are never seen by training views."""
# TODO: only query points that are covered by the training cameras viewing frustrum
# We'll need to pass in the camera poses and intrinsics to this function
raise NotImplementedError()
@torch.no_grad()
def update_occupancy_grid(self, density_fn, decay=0.95, split_size=64):
"""Update the occupancy grid with density values.
Args:
density_fn: Function from takes points in the shape (..., 3) and
returns a tensor of densities of shape (..., 1).
"""
# TODO(ethan): remove this pylint disable
# pylint: disable=invalid-name
device = self.occupancy_grid.device
assert self.num_cascades == 1, "Still need to implement code for multiple cascades."
temp_occupancy_grid = torch.zeros_like(self.occupancy_grid)
X_length, Y_length, Z_length = self.aabb[1] - self.aabb[0]
X_half_voxel_length = 0.5 * X_length / self.resolution
Y_half_voxel_length = 0.5 * Y_length / self.resolution
Z_half_voxel_length = 0.5 * Z_length / self.resolution
half_voxel_lengths = torch.tensor(
[X_half_voxel_length, Y_half_voxel_length, Z_half_voxel_length], device=device
)
X = torch.linspace(
self.aabb[0][0] + X_half_voxel_length, self.aabb[1][0] - X_half_voxel_length, self.resolution, device=device
).split(split_size)
Y = torch.linspace(
self.aabb[0][1] + Y_half_voxel_length, self.aabb[1][1] - Y_half_voxel_length, self.resolution, device=device
).split(split_size)
Z = torch.linspace(
self.aabb[0][2] + Z_half_voxel_length, self.aabb[1][2] - Z_half_voxel_length, self.resolution, device=device
).split(split_size)
for x_index, xs in enumerate(X):
for y_index, ys in enumerate(Y):
for z_index, zs in enumerate(Z):
x_len, y_len, z_len = len(xs), len(ys), len(zs)
grid_x, grid_y, grid_z = torch.meshgrid(xs, ys, zs, indexing="ij")
xyzs = torch.stack([grid_x, grid_y, grid_z], dim=-1) # (resolution, resolution,, resolution, 3)
# add noise to the points
xyzs_rand = (
torch.rand_like(xyzs) * half_voxel_lengths
) # range [-half_voxel_length, half_voxel_length] for each dimension
xyzs += xyzs_rand
densities = density_fn(xyzs)
assert densities.shape[-1] == 1
temp_occupancy_grid[
0,
x_index * split_size : x_index * split_size + x_len,
y_index * split_size : y_index * split_size + y_len,
z_index * split_size : z_index * split_size + z_len,
] = densities[..., 0]
# exponential moving average update
valid_mask = self.occupancy_grid >= 0.0
self.occupancy_grid[valid_mask] = torch.maximum(
self.occupancy_grid[valid_mask] * decay, temp_occupancy_grid[valid_mask]
)
self.mean_density = torch.mean(self.occupancy_grid[valid_mask]).item()
@torch.no_grad()
def get_densities(self, xyzs: TensorType[..., 3]) -> TensorType[..., 1]:
"""Trilinear interpolation to get the density values.
Args:
xyzs (TensorType[..., 3]): 3D querry coordinate
Returns:
TensorType[..., 1]: Density values
"""
occupancy_grid = self.occupancy_grid[None, ...] # shape (1, num_cascades, X_res, Y_res, Z_res)
xyzs_shape = xyzs.shape
xyzs_reshaped = xyzs.view(1, -1, 1, 1, 3)
voxel_lengths = self.aabb[1] - self.aabb[0]
xyzs_reshaped_normalized = ((xyzs_reshaped - self.aabb[0]) / voxel_lengths) * 2.0 - 1.0
densities = F.grid_sample(
occupancy_grid.permute(
0, 1, 4, 3, 2
), # (xyz to zyx) for grid sample useage because the xyzs have xyz ordering
xyzs_reshaped_normalized,
align_corners=True,
padding_mode="zeros",
)
densities = densities.view(*xyzs_shape[:-1], 1)
return densities
def forward(self, x):
"""Not implemented."""
raise NotImplementedError()
+96
View File
@@ -0,0 +1,96 @@
"""
Optimizers class.
"""
from typing import Dict, List
import numpy as np
from hydra.utils import instantiate
from omegaconf import DictConfig
from torch.nn import Parameter
from torch.optim.lr_scheduler import LambdaLR
from pyrad.utils import writer
class ExponentialDecaySchedule(LambdaLR):
"""Exponential learning rate decay function.
See https://github.com/google-research/google-research/blob/
fd2cea8cdd86b3ed2c640cbe5561707639e682f3/jaxnerf/nerf/utils.py#L360
for details.
"""
def __init__(self, optimizer, lr_init, lr_final, max_steps, lr_delay_steps=0, lr_delay_mult=1.0) -> None:
def func(step):
if lr_delay_steps > 0:
delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(
0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)
)
else:
delay_rate = 1.0
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 delay_rate * multiplier
super().__init__(optimizer, lr_lambda=func)
class Optimizers:
"""_summary_"""
def __init__(self, config: DictConfig, param_groups: Dict[str, List[Parameter]]):
"""_summary_
Args:
config (DictConfig): _description_
param_dict (Dict[str, List[Parameter]]): _description_
"""
self.config = config
self.optimizers = {}
self.schedulers = {}
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_group_name: str) -> None:
"""fetch and step corresponding optimizer
Args:
param_group_name (str): name of optimizer to step forward
"""
self.optimizers[param_group_name].step()
def scheduler_step(self, param_group_name: str) -> None:
"""fetch and step corresponding scheduler
Args:
param_group_name (str): name of scheduler to step forward
"""
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"""
for _, optimizer in self.optimizers.items():
optimizer.zero_grad()
def optimizer_step_all(self):
"""Run step for all optimizers."""
for _, optimizer in self.optimizers.items():
# note that they key is the parameter name
optimizer.step()
def scheduler_step_all(self, step):
"""Run step for all schedulers."""
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.put_scalar(name=f"learning_rate/{param_group_name}", scalar=lr, step=step)
+56
View File
@@ -0,0 +1,56 @@
"""
Ray generator.
"""
from torch import nn
from torchtyping import TensorType
from pyrad.structures.rays import RayBundle
from pyrad.structures.cameras import get_camera_model
class RayGenerator(nn.Module):
"""torch.nn Module for generating rays.
This class will store the intrinsics and extrinsics parameters of the cameras."""
def __init__(
self,
intrinsics: TensorType["num_cameras", "num_intrinsics_params"],
camera_to_world: TensorType["num_cameras", 3, 4],
) -> None:
"""_summary_
Args:
intrinsics (TensorType[&quot;num_cameras&quot;, &quot;num_intrinsics_params&quot;]):
The intrinsics parameters.
camera_to_world (TensorType[&quot;num_cameras&quot;, 3, 4]): Camera to world transformation matrix.
"""
super().__init__()
self.num_cameras, self.num_intrinsics_params = intrinsics.shape
assert self.num_cameras >= 0
self.intrinsics = nn.Parameter(intrinsics, requires_grad=False)
self.camera_to_world = nn.Parameter(camera_to_world, requires_grad=False)
# TODO(ethan): add learnable parameters that are deltas on the intrinsics and camera_to_world parameters
# NOTE(ethan): we currently assume all images have the same height and width
camera_index = 0
self.camera_class = get_camera_model(self.num_intrinsics_params)
camera = self.camera_class(*self.intrinsics[camera_index].tolist())
self.image_coords = nn.Parameter(camera.get_image_coords(), requires_grad=False)
def forward(self, ray_indices: TensorType["num_rays", 3]) -> RayBundle:
"""Index into the cameras to generate the rays.
Args:
x (_type_): _description_
"""
c = ray_indices[:, 0] # camera indices
y = ray_indices[:, 1] # row indices
x = ray_indices[:, 2] # col indices
intrinsics = self.intrinsics[c]
camera_to_world = self.camera_to_world[c]
coords = self.image_coords[y, x]
ray_bundle = self.camera_class.generate_rays(
intrinsics=intrinsics, camera_to_world=camera_to_world, coords=coords
)
ray_bundle.camera_indices = c
return ray_bundle
+205
View File
@@ -0,0 +1,205 @@
"""
Collection of renderers
"""
import math
from typing import Optional
import torch
from torch import nn
from torchtyping import TensorType
from pyrad.utils.math import components_from_spherical_harmonics
class RGBRenderer(nn.Module):
"""Standard volumetic rendering."""
def __init__(self, background_color: Optional[TensorType[3]] = None) -> None:
"""
Args:
background_color (TensorType[3], optional): Background color as RGB. Defaults to random.
"""
super().__init__()
self.background_color = background_color
@classmethod
def combine_rgb(
cls,
rgb: TensorType[..., "num_samples", 3],
weights: TensorType[..., "num_samples"],
background_color: Optional[TensorType[3]] = None,
) -> TensorType[..., 3]:
"""Composite samples along ray and render color image
Args:
rgb (TensorType[..., "num_samples", -1]): RGB for each sample
weights (TensorType[..., "num_samples"]): Weights for each sample
background_color (TensorType[3], optional): Background color as RGB. Defaults to random.
Returns:
TensorType[..., 3]: Outputs rgb values.
"""
rgb = torch.sum(weights[..., None] * rgb, dim=-2)
if background_color is None:
background_color = torch.rand_like(rgb).to(rgb.device)
rgb = rgb + background_color.to(weights.device) * (1.0 - torch.sum(weights, dim=-1)[..., None])
return rgb
def forward(
self,
rgb: TensorType[..., "num_samples", 3],
weights: TensorType[..., "num_samples"],
) -> TensorType[..., 3]:
"""Composite samples along ray and render color image
Args:
rgb (TensorType[..., "num_samples", -1]): RGB for each sample
weights (TensorType[..., "num_samples"]): Weights for each sample
Returns:
TensorType[..., 3]: Outputs of rgb values.
"""
rgb = self.combine_rgb(rgb, weights, background_color=self.background_color)
if not self.training:
torch.clamp_(rgb, min=0.0, max=1.0)
return rgb
class SHRenderer(nn.Module):
"""Render RGB value from spherical harmonics."""
def __init__(
self, background_color: Optional[TensorType[3]] = None, activation: Optional[nn.Module] = nn.Sigmoid()
) -> None:
"""
Args:
background_color (TensorType[3], optional): Background color as RGB. Defaults to random.
activation (Optional[nn.Module], optional): Output activation. Defaults to Sigmoid().
"""
super().__init__()
self.background_color = background_color
self.activation = activation
def forward(
self,
sh: TensorType[..., "num_samples", "coeffs"],
directions: TensorType[..., "num_samples", 3],
weights: TensorType[..., "num_samples"],
) -> TensorType[..., 3]:
"""Composite samples along ray and render color image
Args:
sh (TensorType[..., "num_samples", "coeffs"]): Spherical hamonics coefficients for each sample
directions: (TensorType[..., "num_samples", 3]): Sample direction
weights (TensorType[..., "num_samples"]): Weights for each sample
Returns:
TensorType[..., 3]: Outputs of rgb values.
"""
sh = sh.view(*sh.shape[:-1], 3, sh.shape[-1] // 3)
levels = int(math.sqrt(sh.shape[-1]))
components = components_from_spherical_harmonics(levels=levels, directions=directions)
rgb = sh * components[..., None, :] # [..., num_samples, 3, sh_components]
rgb = torch.sum(sh, dim=-1) + 0.5 # [..., num_samples, 3]
if self.activation is not None:
self.activation(rgb)
rgb = RGBRenderer.combine_rgb(rgb, weights, background_color=self.background_color)
return rgb
class AccumulationRenderer(nn.Module):
"""Accumulated value along a ray."""
@classmethod
def forward(
cls,
weights: TensorType[..., "num_samples"],
) -> TensorType:
"""Composite samples along ray and calculate accumulation.
Args:
weights (TensorType[..., "num_samples"]): Weights for each sample
Returns:
TensorType: Outputs of accumulated values.
"""
accumulation = torch.sum(weights, dim=-1)[..., None]
return accumulation
class DepthRenderer(nn.Module):
"""Calcualte depth along ray."""
def __init__(self, method: str = "expected") -> None:
"""
Args:
method (str, optional): Depth calculation method. Defaults to 'expected'.
"""
super().__init__()
if method not in {"expected"}:
raise ValueError(f"{method} is an invalid depth calculation method")
self.method = method
def forward(
self, weights: TensorType[..., "num_samples"], ts: TensorType[..., "num_samples"]
) -> TensorType[..., 1]:
"""Composite samples along ray and calculate disparities.
Args:
weights (TensorType[..., "num_samples"]): Weights for each sample
ts (TensorType[..., "num_samples"]): Sample locations along rays
Returns:
TensorType[..., 1]: Outputs of depth values.
"""
if self.method == "expected":
eps = 1e-10
depth = torch.sum(weights * ts, dim=-1) / (torch.sum(weights, -1) + eps)
depth = torch.clip(depth, ts[..., 0], ts[..., -1])
return depth[..., None]
raise NotImplementedError(f"Method {self.method} not implemented")
class UncertaintyRenderer(nn.Module):
"""Calculate uncertainty along the ray."""
@classmethod
def forward(cls, betas: TensorType[..., "num_samples", 1], weights: TensorType[..., "num_samples"]) -> TensorType:
"""_summary_
Args:
betas (TensorType[..., &quot;num_samples&quot;, 1]): _description_
weights (TensorType[..., &quot;num_samples&quot;]): _description_
Returns:
TensorType: _description_
"""
uncertainty = torch.sum(weights[..., None] * betas, dim=-2)
return uncertainty
class SemanticRenderer(nn.Module):
"""Calculate semantics along the ray."""
@classmethod
def forward(
cls, semantics: TensorType[..., "num_samples", "num_classes"], weights: TensorType[..., "num_samples"]
) -> TensorType[..., "num_classes"]:
"""_summary_"""
sem = torch.sum(weights[..., None] * semantics, dim=-2)
return sem
+192
View File
@@ -0,0 +1,192 @@
"""
Collection of sampling strategies
"""
from abc import abstractmethod
from typing import Optional
import torch
from torch import nn
from torchtyping import TensorType
from pyrad.nerf.occupancy_grid import OccupancyGrid
from pyrad.structures.rays import RayBundle, RaySamples
class Sampler(nn.Module):
"""Generate Samples"""
def __init__(
self, num_samples: int, occupancy_field: Optional[OccupancyGrid] = None, weight_threshold: float = 1e-4
) -> None:
super().__init__()
self.num_samples = num_samples
self.occupancy_field = occupancy_field
self.weight_threshold = weight_threshold
@abstractmethod
def generate_ray_samples(self) -> RaySamples:
"""Generate Ray Samples"""
def forward(self, *args, **kwargs) -> RaySamples:
"""Generate ray samples with optional occupancy filtering"""
ray_samples = self.generate_ray_samples(*args, **kwargs)
if self.occupancy_field is not None:
densities = self.occupancy_field.get_densities(ray_samples.positions)
weights = ray_samples.get_weights(densities)
valid_mask = weights >= self.weight_threshold
ray_samples.set_valid_mask(valid_mask)
return ray_samples
class UniformSampler(Sampler):
"""Sample uniformly along a ray"""
def __init__(
self,
num_samples: int,
train_stratified=True,
occupancy_field: Optional[OccupancyGrid] = None,
weight_threshold: float = 1e-4,
) -> None:
"""
Args:
num_samples (int): Number of samples per ray
train_stratified (bool): Use stratified sampling during training. Defults to True
occupancy_field (OccupancyGrid, optional): Occupancy grid. If provides,
samples below weight_threshold as set as invalid.
weight_thershold (float): Removes samples below threshold weight. Only used if occupancy field is provided.
"""
super().__init__(num_samples=num_samples, occupancy_field=occupancy_field, weight_threshold=weight_threshold)
self.train_stratified = train_stratified
@torch.no_grad()
def generate_ray_samples(
self,
ray_bundle: RayBundle = None,
num_samples: Optional[int] = None,
) -> RaySamples:
"""Generates position samples uniformly.
Args:
ray_bundle (RayBundle): Rays to generate samples for
num_samples (Optional[int]): Number of samples per ray
Returns:
RaySamples: Positions and deltas for samples along a ray
"""
assert ray_bundle is not None
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(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[:, :-1] + t_rand * (bins[:, 1:] - bins[:, :-1]) # shape (num_rays, num_samples)
else:
ts = (bins[:, 1:] + bins[:, :-1]) / 2
ray_samples = ray_bundle.get_ray_samples(ts)
return ray_samples
class PDFSampler(Sampler):
"""Sample based on probability distribution"""
def __init__(
self,
num_samples: int,
train_stratified: bool = True,
include_original: bool = True,
occupancy_field: OccupancyGrid = None,
weight_threshold: float = 1e-4,
) -> None:
"""
Args:
num_samples (int): Number of samples per ray
train_stratified: boolean: Randomize location within each bin during training. Defaults to True
include_original: Add original samples to ray. Defaults to True
occupancy_field (OccupancyGrid, optional): Occupancy grid. If provides,
samples below weight_threshold as set as invalid.
weight_thershold (float): Removes samples below threshold weight. Only used if occupancy field is provided.
"""
super().__init__(num_samples=num_samples, occupancy_field=occupancy_field, weight_threshold=weight_threshold)
self.train_stratified = train_stratified
self.include_original = include_original
@torch.no_grad()
def generate_ray_samples(
self,
ray_bundle: RayBundle = None,
ray_samples: RaySamples = None,
weights: TensorType[..., "num_samples"] = None,
num_samples: Optional[int] = None,
eps: float = 1e-5,
) -> RaySamples:
"""Generates position samples given a distribution.
Args:
ray_bundle (RayBundle): Rays to generate samples for
TensorType[..., "output_dim"]: A encoded input tensor
bins (TensorType[..., "num_samples"]): Ray bins
weights: (TensorType[..., "num_samples"]): Weights for each bin
num_samples (Optional[int]): Number of samples per ray
eps: float: Small value to prevent numerical issues. Defaults to 1e-5
Returns:
RaySamples: Positions and deltas for samples along a ray
"""
num_samples = num_samples or self.num_samples
weights = weights[..., :-1]
# Add small offset to rays with zero weight to prevent NaNs
weights_sum = torch.sum(weights, dim=-1, keepdim=True)
padding = torch.relu(eps - weights_sum)
weights = weights + padding / weights.shape[-1]
weights_sum += padding
pdf = weights / weights_sum
cdf = torch.min(torch.ones_like(pdf), torch.cumsum(pdf, dim=-1))
cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], dim=-1)
if self.train_stratified and self.training:
u = torch.rand(size=(*cdf.shape[:-1], num_samples), device=cdf.device)
else:
u = torch.linspace(0.0, 1.0, steps=num_samples, device=cdf.device)
u = u.expand(size=(*cdf.shape[:-1], num_samples))
u = u.contiguous()
indicies = torch.searchsorted(cdf, u, right=True)
below = torch.max(torch.zeros_like(indicies), indicies - 1)
above = torch.min(cdf.shape[-1] - torch.ones_like(indicies), indicies)
indicies_g = torch.stack([below, above], -1)
matched_shape = (indicies_g.shape[0], indicies_g.shape[1], cdf.shape[-1])
cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), dim=2, index=indicies_g)
bins_g = torch.gather(ray_samples.ts.unsqueeze(1).expand(matched_shape), dim=2, index=indicies_g)
denom = cdf_g[..., 1] - cdf_g[..., 0]
denom = torch.where(denom < eps, torch.ones_like(denom), denom)
t = (u - cdf_g[..., 0]) / denom
ts = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0])
if self.include_original:
ts, _ = torch.sort(torch.cat([ray_samples.ts, ts], -1), -1)
else:
ts, _ = torch.sort(ts, -1)
# Stop gradients
ts = ts.detach()
ray_samples = ray_bundle.get_ray_samples(ts)
return ray_samples
+288
View File
@@ -0,0 +1,288 @@
"""
Code to train model.
"""
import copy
import logging
import os
from pydoc import locate
from time import time
from typing import Callable, Dict, List
import torch
import torch.distributed as dist
from omegaconf import DictConfig
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader
from pyrad.nerf.dataset.collate import CollateIterDataset, collate_batch_size_one
from pyrad.nerf.dataset.image_dataset import ImageDataset, collate_batch
from pyrad.nerf.dataset.utils import DatasetInputs, get_dataset_inputs
from pyrad.nerf.optimizers import Optimizers
from pyrad.utils import profiler, writer
from pyrad.utils.callbacks import update_occupancy
from pyrad.utils.decorators import check_main_thread
from pyrad.utils.misc import get_dict_to_torch
logging.getLogger("PIL").setLevel(logging.WARNING)
class Trainer:
"""Training class"""
def __init__(self, config: DictConfig, local_rank: int = 0, world_size: int = 1):
"""_summary_
Args:
config (DictConfig): _description_
local_rank (int, optional): _description_. Defaults to 0.
world_size (int, optional): _description_. Defaults to 1.
cpu (bool, optional): Whether or not to use the CPU.
"""
self.config = config
self.local_rank = local_rank
self.world_size = world_size
# dataset variables
self.train_image_dataset = None
self.train_dataset = None
self.train_dataloader = None
self.val_image_dataset = None
self.val_image_intrinsics = None
self.val_image_camera_to_world = None
# model variables
self.graph = None
self.optimizers = None
self.start_step = 0
# logging variables
writer.setup_event_writers(config)
profiler.setup_profiler(config.logging)
self.device = "cpu" if self.world_size == 0 else f"cuda:{self.local_rank}"
def setup(self, test_mode=False):
"""Setup the Trainer by calling other setup functions."""
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.
I'm only using this for multiprocess pickle issues for now.
"""
return collate_batch(batch_list, self.config.data.dataloader.num_rays_per_batch, keep_full_image=False)
@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.image_filenames,
downscale_factor=dataset_inputs.downscale_factor,
alpha_color=dataset_inputs.alpha_color,
)
self.val_image_intrinsics = dataset_inputs.intrinsics
self.val_image_camera_to_world = dataset_inputs.camera_to_world
@profiler.time_function
def setup_dataset_train(self, dataset_inputs: DatasetInputs):
"""_summary_"""
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_images=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):
"""Setup the graph. The dataset inputs should be set with the training data.
Args:
dataset_inputs (DatasetInputs): The inputs which will be used to define the camera parameters.
"""
# 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,
)
self.graph.to(self.device)
self.setup_optimizers() # NOTE(ethan): can this be before DDP?
if self.config.graph.resume_train.load_dir:
self.load_checkpoint(self.config.graph.resume_train)
if self.world_size > 1:
self.graph = DDP(self.graph, device_ids=[self.local_rank])
dist.barrier(device_ids=[self.local_rank])
def setup_optimizers(self):
"""_summary_"""
self.optimizers = Optimizers(self.config.graph.param_groups, self.graph.get_param_groups())
def load_checkpoint(self, load_config: DictConfig) -> int:
"""Load the checkpoint from the given path
Args:
load_path (str): path from which to load the model
Returns:
int: step iteration associated with the loaded checkpoint
"""
load_path = os.path.join(load_config.load_dir, f"step-{load_config.load_step:09d}.ckpt")
assert os.path.exists(load_path), f"Checkpoint {load_path} does not exist"
loaded_state = torch.load(load_path, map_location="cpu")
self.graph.load_state_dict({key.replace("module.", ""): value for key, value in loaded_state["model"].items()})
for k, v in loaded_state["optimizers"].items():
self.optimizers.optimizers[k].load_state_dict(v)
self.start_step = loaded_state["step"] + 1
logging.info("done loading checkpoint from %s", load_path)
@check_main_thread
def save_checkpoint(self, output_dir: str, step: int) -> None:
"""Save the model and optimizers
Args:
output_dir (str): directory to save the checkpoint
step (int): number of steps in training for given checkpoint
model (Graph): Graph model to be saved
optimizers (Optimizers): Optimizers to be saved
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
ckpt_path = os.path.join(output_dir, f"step-{step:09d}.ckpt")
torch.save(
{
"step": step,
"model": self.graph.module.state_dict() if hasattr(self.graph, "module") else self.graph.state_dict(),
"optimizers": {k: v.state_dict() for (k, v) in self.optimizers.optimizers.items()},
},
ckpt_path,
)
@classmethod
def get_aggregated_loss(cls, loss_dict: Dict[str, torch.tensor]):
"""Returns the aggregated losses and the scalar for calling .backwards() on.
# TODO: move this out to another file/class/etc.
"""
loss_sum = 0.0
for loss_name in loss_dict.keys():
# TODO(ethan): add loss weightings here from a config
loss_sum += loss_dict[loss_name]
return loss_sum
def train(self) -> None:
"""_summary_"""
train_start = time()
num_iterations = self.config.graph.max_num_iterations
iter_dataset = iter(self.train_dataloader)
for step in range(self.start_step, self.start_step + num_iterations):
data_start = time()
batch = next(iter_dataset)
batch = get_dict_to_torch(batch, device=self.device)
writer.put_time(
name=writer.EventName.ITER_LOAD_TIME,
start_time=data_start,
end_time=time(),
step=step,
avg_over_iters=True,
)
iter_start = time()
loss_dict = self.train_iteration(batch, step, _callback=[update_occupancy])
writer.put_time(
name=writer.EventName.RAYS_PER_SEC,
start_time=iter_start,
end_time=time(),
step=step,
avg_over_iters=True,
avg_over_batch=batch["indices"].shape[0],
)
writer.put_time(
name=writer.EventName.ITER_TRAIN_TIME,
start_time=iter_start,
end_time=time(),
step=step,
avg_over_iters=True,
update_eta=True,
)
if step != 0 and step % self.config.logging.steps_per_log == 0:
writer.put_dict(name="Loss/train-loss_dict", scalar_dict=loss_dict, step=step)
# TODO: add the learning rates to tensorboard/logging
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.val_image_indices:
_ = self.test_image(image_idx=image_idx, step=step)
self._write_out_storage(step)
writer.put_time(
name=writer.EventName.TOTAL_TRAIN_TIME, start_time=train_start, end_time=time(), step=num_iterations
)
self._write_out_storage(num_iterations)
def _write_out_storage(self, step):
"""Perform writes only during appropriate time steps"""
if (
step % self.config.logging.steps_per_log == 0
or (self.config.graph.steps_per_save and step % self.config.graph.steps_per_save == 0)
or step % self.config.graph.steps_per_test == 0
or step == self.config.graph.max_num_iterations
):
writer.write_out_storage()
@profiler.time_function
def train_iteration(self, batch: dict, step: int, _callback: List[Callable] = None):
"""Run one iteration with a batch of inputs."""
ray_indices = batch["indices"]
_, loss_dict = self.graph.forward(ray_indices, batch=batch, step=step)
loss = loss_dict["aggregated_loss"]
self.optimizers.zero_grad_all()
loss.backward()
self.optimizers.optimizer_step_all()
self.optimizers.scheduler_step_all(step)
if _callback:
for _func in _callback:
_func(self.graph)
return loss_dict
@profiler.time_function
def test_image(self, image_idx, step):
"""Test a specific image."""
self.graph.eval()
intrinsics = self.val_image_intrinsics[image_idx]
camera_to_world = self.val_image_camera_to_world[image_idx]
chunk_size = self.config.data.val_num_rays_per_chunk
training_camera_index = image_idx # TODO(ethan): change this because training and test should not be the same
outputs = self.graph.get_outputs_for_camera(
intrinsics, camera_to_world, chunk_size=chunk_size, training_camera_index=training_camera_index
)
val_image_data = self.val_image_dataset[image_idx]
image = val_image_data["image"].to(self.device)
mask = val_image_data["mask"].to(self.device)
psnr = self.graph.log_test_image_outputs(image_idx, step, image, mask, outputs)
self.graph.train()
return psnr
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+269
View File
@@ -0,0 +1,269 @@
"""
Camera Models
"""
from abc import abstractmethod
from dataclasses import dataclass
from typing import Optional, Type
import torch
from torch.nn.functional import normalize
from torchtyping import TensorType
from pyrad.structures.rays import RayBundle
@dataclass
class Rays:
"""Camera rays. Can be arbitrary dimension"""
origin: TensorType[..., 3]
direction: TensorType[..., 3]
class Camera:
"""Base Camera. Intended to be subclassed"""
def __init__(self, camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3]) -> None:
self.camera_to_world = camera_to_world
@abstractmethod
def get_num_intrinsics_params(self) -> int:
"""
Returns:
int: number of optimizable intrinsic parameters
"""
return
@abstractmethod
def get_intrinsics(self) -> torch.Tensor:
"""
Returns:
torch.Tensor: Intrinsics matrix
"""
return
def get_camera_to_world(self) -> TensorType[3, 4]:
"""
Returns:
int: Camera to world transformation
"""
return self.camera_to_world
@abstractmethod
def get_image_height(self) -> int:
"""
Returns:
int: Image height
"""
return
@abstractmethod
def get_image_width(self) -> int:
"""
Returns:
int: Image width
"""
return
def get_image_coords(self, pixel_offset: float = 0.5) -> TensorType["image_height", "image_width", 2]:
"""
Args:
pixel_offset (float): Offset for each pixel. Defaults to center of pixel (0.5)
Returns:
TensorType["image_height", "image_width", 2]: Grid of image coordinates.
"""
image_height = self.get_image_height()
image_width = self.get_image_width()
image_coords = torch.meshgrid(torch.arange(image_height), torch.arange(image_width), indexing="ij")
image_coords = torch.stack(image_coords, dim=-1) + pixel_offset # stored as (y, x) coordinates
return image_coords
@classmethod
@abstractmethod
def generate_rays(
cls,
intrinsics: TensorType["num_rays", "num_intrinsics_params"],
camera_to_world: TensorType["num_rays", 3, 4],
coords: TensorType["image_height", "image_width", 2],
) -> RayBundle:
"""
Args:
intrinsics (TensorType["num_rays", "num_intrinsics_params"]): Camera intrinsics
camera_to_world (TensorType["num_rays", 3, 4]): Camera to world transformation matrix
coords (TensorType["image_height", "image_width", 2]): Image grid coordinates
Returns:
RayBundle: A bundle of rays for each grid coordinate.
"""
return
def generate_camera_rays(self) -> RayBundle:
"""Generate rays for the camera.
Returns:
Rays: Camera rays of shape [height, width]
"""
height = self.get_image_height()
width = self.get_image_width()
intrinsics = self.get_intrinsics().unsqueeze(0).repeat(height, width, 1) # (num_rays, num_intrinsics_params)
camera_to_world = self.camera_to_world.unsqueeze(0).repeat(height, width, 1, 1) # (num_rays, 3, 4)
coords = self.get_image_coords()
ray_bundle = self.generate_rays(intrinsics, camera_to_world, coords)
return ray_bundle
class PinholeCamera(Camera):
"""Pinhole camera model."""
def __init__(
self, cx: float, cy: float, fx: float, fy: float, camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3]
):
super().__init__(camera_to_world)
self.cx = cx
self.cy = cy
self.fx = fx
self.fy = fy
def get_num_intrinsics_params(self) -> int:
return 4
def get_image_width(self) -> int:
return int(self.cx * 2.0)
def get_image_height(self) -> int:
return int(self.cy * 2.0)
def get_intrinsics_matrix(self) -> TensorType[3, 3]:
"""
Returns:
TensorType[3, 3]: Pinhole camera intrinsics matrix
"""
K = torch.tensor(
[[self.fx, 0.0, self.cx], [0.0, self.fy, self.cy], [0, 0, 1.0]],
dtype=torch.float32,
)
return K
def get_intrinsics(self) -> torch.Tensor:
return torch.tensor([self.cx, self.cy, self.fx, self.fy])
@classmethod
def fx_index(cls):
"""TODO(ethan): redo this in a better way.
Ideally we can dynamically grab the focal length parameters depending on
Simple vs. not Simple Pinhole Model.
Returns:
_type_: _description_
"""
return 2
@classmethod
def fy_index(cls):
"""_summary_
Returns:
_type_: _description_
"""
return 3
@classmethod
def generate_rays(
cls,
intrinsics: TensorType[..., "num_intrinsics_params"],
camera_to_world: TensorType[..., 3, 4],
coords: TensorType[..., 2],
) -> RayBundle:
cx = intrinsics[..., 0:1]
cy = intrinsics[..., 1:2]
fx = intrinsics[..., cls.fx_index() : cls.fx_index() + 1]
fy = intrinsics[..., cls.fy_index() : cls.fy_index() + 1]
y = coords[..., 0:1] # (..., 1)
x = coords[..., 1:2] # (..., 1)
original_directions = torch.cat([(x - cx) / fx, -(y - cy) / fy, -torch.ones_like(x)], -1) # (..., 3)
rotation = camera_to_world[..., :3, :3] # (..., 3, 3)
directions = torch.sum(
original_directions[..., None, :] * rotation, dim=-1
) # (..., 1, 3) * (..., 3, 3) -> (..., 3)
directions = normalize(directions, dim=-1)
origins = camera_to_world[..., :3, 3] # (..., 3)
return RayBundle(origins=origins, directions=directions)
class SimplePinholeCamera(PinholeCamera):
"""Simple Pinhole Camera model."""
def __init__(self, cx: float, cy: float, f: float, camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3]):
super().__init__(cx, cy, f, f, camera_to_world)
@classmethod
def fx_index(cls):
return 2
@classmethod
def fy_index(cls):
return 2
class EquirectangularCamera(Camera):
"""Equirectangular (360 degree) camera model."""
def __init__(self, height: int, width: int, camera_to_world: Optional[TensorType[3, 4]] = torch.eye(4)[:3]):
super().__init__(camera_to_world)
self.height = height
self.width = width
def get_num_intrinsics_params(self):
return 2
def get_image_width(self):
return self.width
def get_image_height(self):
return self.height
def get_intrinsics(self) -> torch.Tensor:
return torch.tensor([self.height, self.width])
@classmethod
def generate_rays(
cls,
intrinsics: TensorType["num_rays", 2],
camera_to_world: TensorType["num_rays", 3, 4],
coords: TensorType["num_rays", 2],
) -> RayBundle:
phi = coords[:, 0:1] # (num_rays, 1)
theta = coords[:, 1:2] # (num_rays, 1)
height = intrinsics[:, 0:1]
width = intrinsics[:, 1:2]
phi = phi / height * torch.pi
theta = -theta / width * 2 * torch.pi
directions = torch.stack(
[torch.cos(theta) * torch.sin(phi), torch.sin(theta) * torch.sin(phi), torch.cos(phi)], dim=-1
)
origins = camera_to_world[:, :3, 3] # (num_rays, 3)
return RayBundle(origins=origins, directions=directions)
def get_camera_model(num_intrinsics_params: int) -> Type[Camera]:
"""Returns the camera model given the specified number of intrinsics parameters.
Args:
num_intrinsics_params (int): Number of intrinsic parametes.
Returns:
Camera: Camera model
"""
if num_intrinsics_params == 2:
return EquirectangularCamera
if num_intrinsics_params == 3:
return SimplePinholeCamera
if num_intrinsics_params == 4:
return PinholeCamera
raise NotImplementedError
+40
View File
@@ -0,0 +1,40 @@
"""Common Colors"""
from typing import Union
from omegaconf import ListConfig
import torch
from torchtyping import TensorType
WHITE = torch.tensor([1.0, 1.0, 1.0])
BLACK = torch.tensor([0.0, 0.0, 0.0])
RED = torch.tensor([1.0, 0.0, 0.0])
GREEN = torch.tensor([0.0, 1.0, 0.0])
BLUE = torch.tensor([0.0, 0.0, 1.0])
COLORS_DICT = {
"white": WHITE,
"black": BLACK,
"red": RED,
"green": GREEN,
"blue": BLUE,
}
def get_color(color: Union[str, list, ListConfig]) -> TensorType[3]:
"""
Args:
color (Union[str, list, ListConfig]): Color as a string or a rgb list
Returns:
TensorType[3]: Parsed color
"""
if isinstance(color, str):
color = color.lower()
if color not in COLORS_DICT:
raise ValueError(f"{color} is not a valid preset color")
return COLORS_DICT[color]
if isinstance(color, (list, ListConfig)):
if len(color) != 3:
raise ValueError(f"Color should be 3 values (RGB) instead got {color}")
return torch.tensor(color)
raise ValueError(f"Color should be an RGB list or string, instead got {type(color)}")
+244
View File
@@ -0,0 +1,244 @@
"""
Some ray datastructures.
"""
import random
from dataclasses import dataclass
from typing import Optional
import torch
from torchtyping import TensorType
from pyrad.utils.misc import is_not_none
@dataclass
class PointSamples:
"""Samples in space.
Args:
positions (TensorType[..., 3]): XYZ locations
directions (TensorType[..., 3]): Unit direction vector
camera_indices (TensorType[..., 1]): Camera index
valid_mask (TensorType[...]): Rays that are valid
"""
positions: TensorType[..., 3]
directions: TensorType[..., 3] = None
camera_indices: TensorType[..., 1] = None
valid_mask: TensorType[...] = None
def apply_masks(self) -> "PointSamples":
"""Use valid_mask to mask samples.
Returns:
PointSamples: New set of masked samples.
"""
if is_not_none(self.valid_mask):
positions = self.positions[self.valid_mask]
directions = self.directions[self.valid_mask] if is_not_none(self.directions) else self.directions
camera_indices = (
self.camera_indices[self.valid_mask] if is_not_none(self.camera_indices) else self.camera_indices
)
return PointSamples(
positions=positions,
directions=directions,
camera_indices=camera_indices,
)
return PointSamples(
positions=self.positions,
directions=self.directions,
camera_indices=self.camera_indices,
)
@dataclass
class RaySamples:
"""Samples along a ray
Args:
positions (TensorType[..., 3]): XYZ locations
directions (TensorType[..., 3]): Unit direction vector
camera_indices (TensorType[..., 1]): Camera index
valid_mask (TensorType[...]): Rays that are valid
ts (TensorType[..., 1]): "time steps", distances along ray
deltas )TensorType[..., 1]): "width" of each sample
"""
positions: TensorType[..., 3]
directions: TensorType[..., 3] = None
camera_indices: TensorType[..., 1] = None
valid_mask: TensorType[...] = None
ts: TensorType[..., 1] = None
deltas: TensorType[..., 1] = None
def to_point_samples(self) -> PointSamples:
"""Convert to PointSamples instance and return."""
# TODO: make this more interpretable
return PointSamples(positions=self.positions, directions=self.directions, valid_mask=self.valid_mask)
def get_weights(self, densities: TensorType[..., "num_samples", 1]) -> TensorType[..., "num_samples"]:
"""Return weights based on predicted densities
Args:
densities (TensorType[..., "num_samples", 1]): Predicted densities for samples along ray
Returns:
TensorType[..., "num_samples"]: Weights for each sample
"""
delta_density = self.deltas * densities[..., 0]
alphas = 1 - torch.exp(-delta_density)
# mip-nerf version of transmittance calculation:
transmittance = torch.cumsum(delta_density[..., :-1], dim=-1)
transmittance = torch.cat(
[torch.zeros((*transmittance.shape[:1], 1)).to(densities.device), transmittance], axis=-1
)
transmittance = torch.exp(-transmittance) # [..., "num_samples"]
# most nerf codebases do the following:
# transmittance = torch.cat(
# [torch.ones((*alphas.shape[:1], 1)).to(densities.device), 1.0 - alphas + 1e-10], dim=-1
# )
# transmittance = torch.cumprod(transmittance, dim=-1)[..., :-1] # [..., "num_samples"]
weights = alphas * transmittance # [..., "num_samples"]
return weights
def set_valid_mask(self, valid_mask: TensorType[..., "num_samples"]) -> None:
"""Sets valid mask"""
self.valid_mask = valid_mask
@dataclass
class RayBundle:
"""A bundle of ray parameters.
Args:
origins (TensorType[..., 3]): Ray origins (XYZ)
directions (TensorType[..., 3]): Unit ray direction vector
camera_indices (TensorType[..., 1]): Camera indices
nears (TensorType[..., 1]): Distance along ray to start sampling
fars (TensorType[..., 1]): Rays Distance along ray to stop sampling
valid_mask (TensorType[...]): Rays that are valid
"""
origins: TensorType["num_rays", 3]
directions: TensorType["num_rays", 3]
camera_indices: Optional[TensorType["num_rays", 1]] = None
nears: Optional[TensorType["num_rays"]] = None
fars: Optional[TensorType["num_rays"]] = None
valid_mask: Optional[TensorType["num_rays"]] = None
def move_to_device(self, device: torch.device) -> None:
"""Move bundle data to a device.
Args:
device (torch.device): Device to move tensors to.
"""
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 set_camera_indices(self, camera_index: int) -> None:
"""Sets all of the the camera indices to a specific camera index.
Args:
camera_index (int): Camera index.
"""
self.camera_indices = torch.ones_like(self.origins[..., 0]).long() * camera_index
def __len__(self):
num_rays = torch.numel(self.origins) // self.origins.shape[-1]
return num_rays
def sample(self, num_rays: int) -> "RayBundle":
"""Returns a RayBundle as a subset of rays.
Args:
num_rays (int): Number of rays in output RayBundle
Returns:
RayBundle: RayBundle with subset of rays.
"""
assert num_rays <= len(self)
indices = random.sample(range(len(self)), k=num_rays)
return RayBundle(
origins=self.origins[indices],
directions=self.directions[indices],
camera_indices=self.camera_indices[indices],
)
def get_masked_ray_bundle(self, valid_mask: TensorType) -> "RayBundle":
"""Return a masked instance of the ray bundle.
Args:
valid_mask (TensorType): Mask of rays to keep.
Returns:
RayBundle: RayBundle of masked rays.
"""
return RayBundle(
origins=self.origins[valid_mask],
directions=self.directions[valid_mask],
camera_indices=self.camera_indices[valid_mask] if is_not_none(self.camera_indices) else None,
nears=self.nears[valid_mask] if is_not_none(self.nears) else None,
fars=self.fars[valid_mask] if is_not_none(self.fars) else None,
valid_mask=self.valid_mask[valid_mask] if is_not_none(self.valid_mask) else None,
)
def get_row_major_sliced_ray_bundle(self, start_idx: int, end_idx: int) -> "RayBundle":
"""Flattens RayBundle and extracts chunk given start and end indicies.
Args:
start_idx (int): Start index of RayBundle chunk.
end_idx (int): End index of RayBundle chunk.
Returns:
RayBundle: Flattened RayBundle with end_idx-start_idx rays.
"""
camera_indices = (
self.camera_indices.view(-1)[start_idx:end_idx] if not isinstance(self.camera_indices, 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,
)
def get_ray_samples(self, ts: TensorType[..., "num_samples"]) -> RaySamples:
"""Produces samples for each ray by projection points along the ray direction.
Args:
ts (TensorType[..., "num_samples"]): Distance from origin of sample points.
Returns:
RaySamples: Samples projected along ray.
"""
positions = self.origins[:, None] + ts[:, :, None] * self.directions[:, None]
directions = self.directions.unsqueeze(1).repeat(1, positions.shape[1], 1)
valid_mask = torch.ones_like(ts, dtype=torch.bool)
dists = ts[..., 1:] - ts[..., :-1]
dists = torch.cat([dists, dists[..., -1:]], -1) # [N_rays, N_samples]
deltas = dists * torch.norm(self.directions[..., None, :], dim=-1)
if self.camera_indices is not None:
camera_indices = self.camera_indices.unsqueeze(1).repeat(1, positions.shape[1])
else:
camera_indices = None
ray_samples = RaySamples(
positions=positions,
directions=directions,
camera_indices=camera_indices,
valid_mask=valid_mask,
ts=ts,
deltas=deltas,
)
return ray_samples
View File
Whitespace-only changes.
+21
View File
@@ -0,0 +1,21 @@
"""
Callback functions for training iterations
"""
from pyrad.nerf.graph.base import Graph
from pyrad.nerf.occupancy_grid import OccupancyGrid
def update_occupancy(graph: Graph):
"""Update the occupancy grid depending on iteration count after every train step"""
if not hasattr(graph, "occupancy_pointers"):
occupancy_grids = []
for _, module in graph.__dict__["_modules"].items():
if isinstance(module, OccupancyGrid):
occupancy_grids.append(module)
graph.occupancy_pointers = occupancy_grids
for grid in graph.occupancy_pointers:
grid.iteration_count += 1
if grid.iteration_count % grid.update_every_num_iters == 0:
if grid.density_fn is not None:
grid.update_occupancy_grid(grid.density_fn)
+72
View File
@@ -0,0 +1,72 @@
"""functionality to handle multiprocessing syncing and communicating"""
import torch
import torch.distributed as dist
_LOCAL_PROCESS_GROUP = None
def get_world_size() -> int:
"""Get total number of available gpus"""
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def get_rank() -> int:
"""Get global rank of current thread"""
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_local_rank() -> int:
"""The rank of the current process within the local (per-machine) process group."""
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
assert (
_LOCAL_PROCESS_GROUP is not None
), "Local process group is not created! Please use launch() to spawn processes!"
return dist.get_rank(group=_LOCAL_PROCESS_GROUP)
def get_local_size() -> int:
"""
The size of the per-machine process group,
i.e. the number of processes per machine.
"""
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size(group=_LOCAL_PROCESS_GROUP)
def is_main_process() -> bool:
"""check to see if you are currently on the main process"""
return get_rank() == 0
def synchronize(world_size):
"""
Helper function to synchronize (barrier) among all processes when
using distributed training
"""
if not dist.is_available():
return
if not dist.is_initialized():
return
world_size = dist.get_world_size()
if world_size == 1:
return
if dist.get_backend() == dist.Backend.NCCL:
# This argument is needed to avoid warnings.
# It's valid only for NCCL backend.
dist.barrier(device_ids=[torch.cuda.current_device()])
else:
dist.barrier()
+43
View File
@@ -0,0 +1,43 @@
"""
Decorator definitions
"""
from typing import Callable, List
from pyrad.utils import comms
def decorate_all(decorators: List[Callable]) -> Callable:
"""A decorator to decorate all member functions of a class"""
def decorate(cls):
for attr in cls.__dict__:
if callable(getattr(cls, attr)) and attr != "__init__":
for decorator in decorators:
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate
def check_profiler_enabled(func: Callable) -> Callable:
"""Decorator: check if profiler is enabled"""
def wrapper(self, *args, **kwargs):
ret = None
if self.config.enable_profiler:
ret = func(self, *args, **kwargs)
return ret
return wrapper
def check_main_thread(func: Callable) -> Callable:
"""Decorator: check if you are on main thread"""
def wrapper(*args, **kwargs):
ret = None
if comms.is_main_process():
ret = func(*args, **kwargs)
return ret
return wrapper
+99
View File
@@ -0,0 +1,99 @@
"""
Input/output utils.
"""
import json
import os
import logging
def load_from_json(filename: str):
"""_summary_
Args:
filename (str): _description_
Returns:
_type_: _description_
"""
assert filename.endswith(".json")
with open(filename, "r", encoding="UTF-8") as file:
return json.load(file)
def write_to_json(filename: str, content: dict):
"""_summary_
Args:
filename (str): _description_
content (dict): _description_
"""
assert filename.endswith(".json")
with open(filename, "w", encoding="UTF-8") as file:
json.dump(content, file)
def get_git_root(path, dirs=(".git",), default=None):
"""_summary_
"https://stackoverflow.com/questions/22081209/find-the-root-of-the-git-repository-where-the-file-lives
Args:
path (_type_): _description_
dirs (tuple, optional): _description_. Defaults to (".git",).
default (_type_, optional): _description_. Defaults to None.
Returns:
_type_: _description_
"""
prev, test = None, os.path.abspath(path)
while prev != test:
if any(os.path.isdir(os.path.join(test, directory)) for directory in dirs):
return test
prev, test = test, os.path.abspath(os.path.join(test, os.pardir))
return default
def get_project_root(path):
"""Return the project root directory from an environment variable.
# TODO: handle this better and report user error
"""
project_root = os.getenv("PROJECT_ROOT")
if project_root is None:
logging.info(
(
"Please set PROJECT_ROOT to the root directory of this repo. "
"Going to try calling get_git_root(path) instead."
)
)
project_root = get_git_root(path)
return project_root
def get_absolute_path(path, proj_root_func=get_project_root):
"""
Returns the full, absolute path.
Relative paths are assumed to start at the repo directory.
"""
if path == "":
return ""
absolute_path = path
if absolute_path[0] != "/":
absolute_path = os.path.join(proj_root_func(path), absolute_path)
return absolute_path
def make_dir(filename_or_folder):
"""Make the directory for either the filename or folder.
Note that filename_or_folder currently needs to end in / for it to be recognized as a folder.
"""
if filename_or_folder[-1] != "/" and filename_or_folder.find(".") < 0:
folder = os.path.dirname(filename_or_folder + "/")
else:
folder = os.path.dirname(filename_or_folder)
if not os.path.exists(folder):
try:
os.makedirs(folder)
except Exception as e: # pylint: disable=broad-except
print(f"Couldn't create folder: {folder}. Maybe due to a parallel process?")
print(e)
return filename_or_folder
+69
View File
@@ -0,0 +1,69 @@
""" Math Helper Functions """
import torch
from torchtyping import TensorType
def components_from_spherical_harmonics(levels: int, directions: TensorType[..., 3]) -> TensorType[..., "components"]:
"""
Args:
levels (int): Number of spherical harmonic levels to compute.
coeffs (TensorType[..., &quot;coeffs&quot;]): Spherical hamonic coefficients
Returns:
TensorType[..., "components"]: Value for each component.
"""
num_components = levels**2
components = torch.zeros((*directions.shape[:-1], num_components)).to(directions.device)
assert 1 <= levels <= 5, f"SH levels must be in [1,4], got {levels}"
assert directions.shape[-1] == 3, f"Direction input should have three dimensions. Got {directions.shape[-1]}"
x = directions[..., 0]
y = directions[..., 1]
z = directions[..., 2]
xx = x**2
yy = y**2
zz = z**2
# l0
components[..., 0] = 0.28209479177387814
# l1
if levels > 1:
components[..., 1] = 0.4886025119029199 * y
components[..., 2] = 0.4886025119029199 * z
components[..., 3] = 0.4886025119029199 * x
# l2
if levels > 2:
components[..., 4] = 1.0925484305920792 * x * y
components[..., 5] = 1.0925484305920792 * y * z
components[..., 6] = 0.9461746957575601 * zz
components[..., 7] = 1.0925484305920792 * x * z
components[..., 8] = 0.5462742152960396 * (xx - yy)
# l3
if levels > 3:
components[..., 9] = 0.5900435899266435 * y * (3 * xx - yy)
components[..., 10] = 2.890611442640554 * x * y * z
components[..., 11] = 0.4570457994644658 * y * (5 * zz - 1)
components[..., 12] = 0.3731763325901154 * z * (5 * zz - 3)
components[..., 13] = 0.4570457994644658 * x * (5 * zz - 1)
components[..., 14] = 1.445305721320277 * z * (xx - yy)
components[..., 15] = 0.5900435899266435 * x * (xx - 3 * yy)
# l4
if levels > 4:
components[..., 16] = 2.5033429417967046 * x * y * (xx - yy)
components[..., 17] = 1.7701307697799304 * y * z * (3 * xx - yy)
components[..., 18] = 0.9461746957575601 * x * y * (7 * zz - 1)
components[..., 19] = 0.6690465435572892 * y * (7 * zz - 3 * z)
components[..., 20] = 0.10578554691520431 * (35 * zz * zz - 30 * zz + 3)
components[..., 21] = 0.6690465435572892 * x * z * (7 * zz - 3)
components[..., 22] = 0.47308734787878004 * (xx - yy) * (7 * zz - 1)
components[..., 23] = 1.7701307697799304 * x * z * (xx - 3 * yy)
components[..., 24] = 0.4425326924449826 * (xx * (xx - 3 * yy) - yy * (3 * xx - yy))
return components
+53
View File
@@ -0,0 +1,53 @@
"""
Miscellaneous helper code.
"""
import torch
class DotDict(dict):
"""
dot.notation access to dictionary attributes
"""
def __getattr__(self, attr):
return self[attr]
__setattr__ = dict.__setitem__
__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
def is_not_none(var):
"""Return True if the variable var is None."""
return not isinstance(var, type(None))
def get_masked_dict(d, mask):
"""Return a masked dictionary.
TODO(ethan): add more asserts/checks so this doesn't have unpredictable behavior."""
masked_dict = {}
for key, value in d.items():
masked_dict[key] = value[mask]
return masked_dict
+70
View File
@@ -0,0 +1,70 @@
"""
Profiler base class and functionality
"""
import logging
import time
from typing import Callable
from omegaconf import DictConfig
from pyrad.utils import comms
from pyrad.utils.decorators import check_main_thread, check_profiler_enabled, decorate_all
PROFILER = []
def time_function(func: Callable) -> Callable:
"""Decorator: time a function call"""
def wrapper(*args, **kwargs):
start = time.time()
ret = func(*args, **kwargs)
if PROFILER:
class_str = func.__qualname__
PROFILER[0].update_time(class_str, start, time.time())
return ret
return wrapper
def flush_profiler(config: DictConfig):
"""Method that checks if profiler is enabled before flushing"""
if config.enable_profiler and PROFILER:
PROFILER[0].print_profile()
def setup_profiler(config: DictConfig):
"""Initialization of profilers"""
if comms.is_main_process():
PROFILER.append(Profiler(config))
@decorate_all([check_profiler_enabled, check_main_thread])
class Profiler:
"""Profiler class"""
def __init__(self, config: DictConfig):
self.config = config
self.profiler_dict = {}
def update_time(self, func_name: str, start_time: float, end_time: float):
"""update the profiler dictionary with running averages of durations
Args:
func_name (str): the function name that is being profiled
start_time (float): the start time when function is called
end_time (float): the end time when function terminated
"""
val = end_time - start_time
func_dict = self.profiler_dict.get(func_name, {"val": 0, "step": 0})
prev_val = func_dict["val"]
prev_step = func_dict["step"]
self.profiler_dict[func_name] = {"val": (prev_val * prev_step + val) / (prev_step + 1), "step": prev_step + 1}
def print_profile(self):
"""helper to print out the profiler stats"""
logging.info("Printing profiling stats, from longest to shortest duration in seconds")
sorted_keys = [k for k, _ in sorted(self.profiler_dict.items(), key=lambda item: item[1]["val"], reverse=True)]
for k in sorted_keys:
val = f"{self.profiler_dict[k]['val']:0.4f}"
print(f"{k:<20}: {val:<20}")
+61
View File
@@ -0,0 +1,61 @@
""" Helper functions for visualizing outputs """
from typing import Optional
import torch
from matplotlib import cm
from torchtyping import TensorType
def apply_colormap(image: TensorType[..., 1], cmap="viridis") -> TensorType[..., 3]:
"""Convert single channel to a color image.
Args:
image (TensorType[..., 1]): Single channel image.
cmap (str, optional): Colormap for image. Defaults to 'turbo'.
Returns:
TensorType[..., 3]: Colored image
"""
colormap = cm.get_cmap(cmap)
colormap = torch.tensor(colormap.colors).to(image.device)
image_long = (image * 255).long()
image_long_min = torch.min(image_long)
image_long_max = torch.max(image_long)
assert image_long_min >= 0, f"the min value is {image_long_min}"
assert image_long_max <= 255, f"the max value is {image_long_max}"
return colormap[image_long[..., 0]]
def apply_depth_colormap(
depth: TensorType[..., 1],
accumulation: Optional[TensorType[..., 1]] = None,
near_plane: Optional[float] = None,
far_plane: Optional[float] = None,
cmap="turbo",
) -> TensorType[..., 3]:
"""Converts a depth image to color for easier analysis.
Args:
depth (TensorType[..., 1]): Depth image.
accumulation (TensorType[..., 1], optional): Ray accumulation used for masking vis. Defaults to None.
near_plane (float, optional): Closest depth to consider. If None, use min image value. Defaults to None.
far_plane (float, optional): Furthest depth to consider. If None, use max image value. Defaults to None.
cmap (str, optional): Colormap to apply. Defaults to "turbo".
Returns:
TensorType[..., 3]: Colored depth image
"""
near_plane = near_plane or torch.min(depth)
far_plane = far_plane or torch.max(depth)
depth = (depth - near_plane) / (far_plane - near_plane + 1e-10)
depth = torch.clip(depth, 0, 1)
colored_image = apply_colormap(depth, cmap=cmap)
if accumulation is not None:
colored_image = colored_image * accumulation + (1 - accumulation)
return colored_image
+330
View File
@@ -0,0 +1,330 @@
"""
Generic Writer class
"""
import enum
import os
from abc import abstractmethod
from typing import Dict
import imageio
import numpy as np
import torch
from omegaconf import DictConfig, ListConfig
from torch.utils.tensorboard import SummaryWriter
from torchtyping import TensorType
import pyrad.utils.writer
from pyrad.utils.decorators import check_main_thread, decorate_all
to8b = lambda x: (255 * torch.clamp(x, min=0, max=1)).to(torch.uint8)
EVENT_WRITERS = []
EVENT_STORAGE = []
GLOBAL_BUFFER = {}
class EventName(enum.Enum):
"""Names of possible events that can be logged via Local Writer for convenience.
see config/logging/default_logging.yaml"""
ITER_LOAD_TIME = "Data Load (time)"
ITER_TRAIN_TIME = "Train Iter (time)"
TOTAL_TRAIN_TIME = "Train Total (time)"
ETA = "ETA (time)"
RAYS_PER_SEC = "Rays Per Sec"
CURR_TEST_PSNR = "Test PSNR"
class EventType(enum.Enum):
"""Possible Event types and their associated write function"""
IMAGE = "write_image"
SCALAR = "write_scalar"
DICT = "write_scalar_dict"
@check_main_thread
def put_image(name, image: TensorType["H", "W", "C"], step: int):
"""Setter function to place images into the queue to be written out"""
if isinstance(name, EventName):
name = name.value
EVENT_STORAGE.append({"name": name, "write_type": EventType.IMAGE, "event": image, "step": step})
@check_main_thread
def put_scalar(name: str, scalar: float, step: int):
"""Setter function to place scalars into the queue to be written out"""
if isinstance(name, EventName):
name = name.value
EVENT_STORAGE.append({"name": name, "write_type": EventType.SCALAR, "event": scalar, "step": step})
@check_main_thread
def put_dict(name: str, scalar_dict: float, step: int):
"""Setter function to place a dictionary of scalars into the queue to be written out"""
EVENT_STORAGE.append({"name": name, "write_type": EventType.DICT, "event": scalar_dict, "step": step})
@check_main_thread
def put_time(
name: str,
start_time: float,
end_time: float,
step: int,
avg_over_iters: bool = False,
avg_over_batch: int = None,
update_eta: bool = False,
):
"""Setter function to place a time element into the queue to be written out
Processes the time info according to the options:
avg_over_iters (bool): if True, calculate and record a running average of the times
avg_over_batch (int): if set, the size of the batch for which we take the average over (batch/second)
update_eta (bool): if True, update the ETA. should only be set for the training iterations/s
"""
if isinstance(name, EventName):
name = name.value
GLOBAL_BUFFER["step"] = step
val = end_time - start_time
if avg_over_batch:
val = avg_over_batch / val
if avg_over_iters:
curr_event = GLOBAL_BUFFER["events"].get(name, {"buffer": [], "avg": 0})
curr_buffer = curr_event["buffer"]
curr_avg = curr_event["avg"]
if len(curr_buffer) >= GLOBAL_BUFFER["max_buffer_size"]:
curr_buffer.pop(0)
curr_buffer.append(val)
curr_avg = sum(curr_buffer) / len(curr_buffer)
put_scalar(name, curr_avg, step)
GLOBAL_BUFFER["events"][name] = {"buffer": curr_buffer, "avg": curr_avg}
else:
put_scalar(name, val, step)
if update_eta:
## NOTE: eta should be called with avg train iteration time
remain_iter = GLOBAL_BUFFER["max_iter"] - step
remain_time = remain_iter * GLOBAL_BUFFER["events"][name]["avg"]
put_scalar(EventName.ETA, remain_time, step)
@check_main_thread
def write_out_storage():
"""Function that writes all the events in storage to all the writer locations"""
for writer in EVENT_WRITERS:
for event in EVENT_STORAGE:
write_func = getattr(writer, event["write_type"].value)
if event["write_type"] == EventType.DICT:
write_func(event["event"], event["step"])
if isinstance(writer, LocalWriter):
continue
else:
write_func(event["name"], event["event"], event["step"])
if isinstance(writer, LocalWriter):
break
EVENT_STORAGE.clear()
@check_main_thread
def setup_event_writers(config: DictConfig) -> None:
"""Initialization of all event writers specified in config"""
logging_configs = config.logging.writer
for writer_type in logging_configs:
writer_class = getattr(pyrad.utils.writer, writer_type)
writer_config = logging_configs[writer_type]
if writer_type == "LocalWriter":
curr_writer = writer_class(writer_config.save_dir, writer_config.stats_to_track, writer_config.max_log_size)
else:
curr_writer = writer_class(writer_config.save_dir)
EVENT_WRITERS.append(curr_writer)
## configure all the global buffer basic information
GLOBAL_BUFFER["max_iter"] = config.graph.max_num_iterations
GLOBAL_BUFFER["max_buffer_size"] = config.logging.max_buffer_size
GLOBAL_BUFFER["steps_per_log"] = config.logging.steps_per_log
GLOBAL_BUFFER["events"] = {}
class Writer:
"""Writer class"""
def __init__(self, save_dir: str):
self.save_dir = save_dir
@abstractmethod
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
"""_summary_
Args:
name (str): data identifier
image (TensorType["H", "W", "C"]): rendered image to write
step (int): the time step to log
"""
raise NotImplementedError
@abstractmethod
def write_scalar(self, name: str, scalar: float, step: int) -> None:
"""Required method to write a single scalar value to the logger
Args:
name (str): data identifier
step (int): the time step to log
"""
raise NotImplementedError
@check_main_thread
def write_scalar_dict(self, scalar_dict: Dict[str, float], step: int) -> None:
"""Function that writes out all scalars from a given dictionary to the logger
Args:
scalar_dict (dict): dictionary containing all scalar values with key names and quantities
step (int): the time step to log
"""
for name, scalar in scalar_dict.items():
self.write_scalar(name, scalar, step)
@decorate_all([check_main_thread])
class TensorboardWriter(Writer):
"""Tensorboard Writer Class"""
def __init__(self, save_dir: str):
super().__init__(save_dir)
self.tb_writer = SummaryWriter(log_dir=self.save_dir)
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
"""_summary_
Args:
name (str): data identifier
image (TensorType["H", "W", "C"]): rendered image to write
"""
image = to8b(image)
self.tb_writer.add_image(name, image, step, dataformats="HWC")
def write_scalar(self, name: str, scalar: float, step: int) -> None:
"""Tensorboard method to write a single scalar value to the logger
Args:
name (str): data identifier
x (float): x value to write
y (float): y value to write
"""
self.tb_writer.add_scalar(name, scalar, step)
def _cursorup(x: int):
"""utility tool to move the cursor up on the terminal
Args:
x (int): amount of lines to move cursor upward
"""
print(f"\r\033[{x}A", end="\x1b[1K\r")
def _format_time(seconds):
"""utility tool to format time in human readable form given seconds"""
ms = seconds % 1
ms = ms * 1e3
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
return f"{days} d, {hours} h, {minutes} m, {seconds} s"
if hours > 0:
return f"{hours} h, {minutes} m, {seconds} s"
if minutes > 0:
return f"{minutes} m, {seconds} s"
if seconds > 0:
return f"{seconds} s, {ms:0.3f} ms"
return f"{ms:0.3f} ms"
@decorate_all([check_main_thread])
class LocalWriter(Writer):
"""Local Writer Class"""
def __init__(self, save_dir: str, stats_to_track: ListConfig, max_log_size: int = 0):
"""
Args:
stats_to_track (ListConfig): the names of stats that should be logged.
max_log size (int): max number of lines that will be logged to teminal.
"""
super().__init__(save_dir)
self.stats_to_track = [EventName[name].value for name in stats_to_track]
self.max_log_size = max_log_size
self.keys = set()
self.past_mssgs = ["", ""]
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
if name in self.stats_to_track:
image = to8b(image)
image_path = os.path.join(self.save_dir, f"{name}.jpg")
imageio.imwrite(image_path, np.uint8(image.cpu().numpy() * 255.0))
def write_scalar(self, name: str, scalar: float, step: int) -> None:
if step > 0:
latest_map, new_key = self._consolidate_events()
self._update_header(latest_map, new_key)
self._print_stats(latest_map)
def _consolidate_events(self):
latest_map = {}
new_key = False
for event in EVENT_STORAGE:
name = event["name"]
if name not in self.keys:
self.keys.add(name)
new_key = True
latest_map[name] = event["event"]
return latest_map, new_key
def _update_header(self, latest_map, new_key):
"""helper to handle the printing of the header labels"""
full_log_cond = not self.max_log_size and GLOBAL_BUFFER["step"] <= GLOBAL_BUFFER["steps_per_log"]
capped_log_cond = self.max_log_size and (len(self.past_mssgs) <= 2 or new_key)
if full_log_cond or capped_log_cond:
mssg = f"{'Step (% Done)':<20}"
for name, _ in latest_map.items():
if name in self.stats_to_track:
mssg += f"{name:<20} "
self.past_mssgs[0] = mssg
self.past_mssgs[1] = "-" * len(mssg)
if full_log_cond:
print(mssg)
print("-" * len(mssg))
def _print_stats(self, latest_map, padding=" "):
"""helper to print out the stats in a readable format"""
step = GLOBAL_BUFFER["step"]
fraction_done = step / GLOBAL_BUFFER["max_iter"]
curr_mssg = f"{step} ({fraction_done*100:.02f}%)"
curr_mssg = f"{curr_mssg:<20}"
for name, v in latest_map.items():
if name in self.stats_to_track:
if "(time)" in name:
v = _format_time(v)
else:
v = f"{v:0.4f}"
curr_mssg += f"{v:<20} "
# update the history buffer
if self.max_log_size:
cursor_idx = len(self.past_mssgs)
if len(self.past_mssgs[2:]) >= self.max_log_size:
self.past_mssgs.pop(2)
self.past_mssgs.append(curr_mssg)
_cursorup(cursor_idx)
for mssg in self.past_mssgs:
pad_len = len(self.past_mssgs[0])
print(f"{mssg:{padding}<{pad_len}}")
else:
print(curr_mssg)
+10
View File
@@ -0,0 +1,10 @@
# Viewer
The backend viewer code (python, websockets, ...).
# References
```
https://github.com/lp-research/openvslam/tree/main/viewer
https://github.com/rdeits/meshcat
```
View File
Whitespace-only changes.
+113
View File
@@ -0,0 +1,113 @@
"""
Visualization code for plotly.
"""
import numpy as np
import plotly.graph_objects as go
import torch
from pyrad.structures.rays import RayBundle
def color_str(color):
"""Plotly color string.
Args:
color: list [r, g, b] in [0, 1] range
Returns:
str: plotly-formatted color string
"""
color = list((np.array(color) * 255.0).astype("int"))
return f"""rgb({color[0]}, {color[1]}, {color[2]})"""
def get_line_segments_from_lines(
lines,
color=color_str((1, 0, 0)),
marker_color=color_str((1, 0, 0)),
colors=None,
draw_marker=True,
draw_line=True,
marker_size=4,
line_width=10,
):
"""Returns a list of Scatter3D objects for creating lines with plotly.
# TODO(ethan): make this function more efficient instead of having a list of objects.
Args:
lines (_type_): list of [np.array(2, 3), ...], line is defined by a (2, 3) array
color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
marker_color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
colors (_type_, optional): _description_. Defaults to None.
draw_marker (bool, optional): _description_. Defaults to True.
draw_line (bool, optional): _description_. Defaults to True.
marker_size (int, optional): _description_. Defaults to 4.
line_width (int, optional): _description_. Defaults to 10.
Returns:
_type_: _description_
"""
data = []
for idx, line in enumerate(lines):
thiscolor = color if draw_line else "rgba(0, 0, 0, 0)"
if colors is not None:
marker_color = colors[idx]
thiscolor = colors[idx]
data.append(
go.Scatter3d(
x=line[:, 0],
y=line[:, 1],
z=line[:, 2],
showlegend=False,
marker=dict(
size=marker_size,
color=marker_color,
colorscale="Viridis",
)
if draw_marker
else dict(color="rgba(0, 0, 0, 0)"),
line=dict(color=thiscolor, width=line_width),
)
)
return data
def visualize_dataset(camera_origins, ray_bundle: RayBundle):
"""Visualize a dataset with plotly using our cameras and generated rays."""
skip = 1
size = 8
assert len(ray_bundle) < 500, "Let's not break plotly by plotting too many rays!"
data = []
data += [
go.Scatter3d(
x=camera_origins[::skip, 0],
y=camera_origins[::skip, 1],
z=camera_origins[::skip, 2],
mode="markers",
name="camera origins",
marker=dict(color="rgba(0, 0, 0, 1)", size=size),
)
]
length = 2.0
lines = torch.stack(
[ray_bundle.origins, ray_bundle.origins + ray_bundle.directions * length], dim=1
) # (num_rays, 2, 3)
data += get_line_segments_from_lines(lines)
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
margin=go.layout.Margin(l=50, r=50, b=100, t=100, pad=4),
scene=go.layout.Scene(
aspectmode="data",
camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=1.25, y=1.25, z=1.25)),
),
)
fig = go.Figure(data=data, layout=layout)
return fig