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