update docstrings and random cleanups (#387)

* fixing docstrings and small nits; up to fileds

* finished adding and fixing docstrings
This commit is contained in:
evonneng authored and GitHub committed 2022-09-10 23:09:44 -07:00
1 parent bd5967461d
commit d50c71ac43
52 files changed
+846 -646

No files matched your search

+13 -3
View File
@@ -31,8 +31,11 @@ class TrainingCallbackAttributes:
# TODO(ethan): type this without circular imports
optimizers: Optional[InitVar]
"""optimizers for training"""
grad_scaler: Optional[InitVar]
"""gradient scalers"""
pipeline: Optional[InitVar]
"""reference to training pipeline"""
class TrainingCallbackLocation(Enum):
@@ -48,8 +51,10 @@ class TrainingCallback:
including at iteration 0. The function is called after the training iteration.
Args:
update_every_num_iters: How often to call the function `func`.
where_to_run: List of locations for when to run callbak (before/after iteration)
func: The function that will be called.
update_every_num_iters: How often to call the function `func`.
iters: Tuple of iteration steps to perform callback
args: args for the function 'func'.
kwargs: kwargs for the function 'func'.
"""
@@ -77,7 +82,7 @@ class TrainingCallback:
"""Callback to run after training step
Args:
step (int): current iteration step
step: current iteration step
"""
if self.update_every_num_iters is not None:
if step % self.update_every_num_iters == 0:
@@ -87,6 +92,11 @@ class TrainingCallback:
self.func(*self.args, **self.kwargs, step=step)
def run_callback_at_location(self, step: int, location: TrainingCallbackLocation):
"""Runs the callback if it's supposed to be run at the given location."""
"""Runs the callback if it's supposed to be run at the given location.
Args:
step: current iteration step
location: when to run callback (before/after iteration)
"""
if location in self.where_to_run:
self.run_callback(step=step)
+25 -37
View File
@@ -47,80 +47,68 @@ import numpy as np
@dataclass
class CameraModel:
"""Camera model.
Attributes:
model_id: Model identifier.
model_name: Model name.
num_params: Number of parameters.
"""
"""Camera model"""
model_id: int
"""Model identifier"""
model_name: str
"""Model name"""
num_params: int
"""Number of parameters"""
@dataclass
class Camera:
"""Camera
Attributes:
camera_id: Camera identifier.
model: Camera model.
width: Image width.
height: Image height.
params: Camera parameters.
"""
"""Camera"""
id: int
"""Camera identifier"""
model: str
"""Camera model"""
width: int
"""Image width"""
height: int
"""Image height"""
params: np.ndarray
"""Camera parameters"""
@dataclass
class Image:
"""Data the corresponds to a single image.
Attributes:
id: Image identifier.
qvec: Quaternion vector.
tvec: Translation vector.
camera_id: Camera identifier.
name: Image name.
xys: 2D points.
point3D_ids: Point3D identifiers.
"""
"""Data the corresponds to a single image"""
id: int
"""Image identifier"""
qvec: np.ndarray
"""Quaternion vector"""
tvec: np.ndarray
"""Translation vector"""
camera_id: int
"""Camera identifier"""
name: str
"""Image name"""
xys: np.ndarray
"""2D points"""
point3d_ids: np.ndarray
"""Point3D identifiers"""
@dataclass
class Point3D:
"""Data that corresponds to a single 3D point.
Attributes:
id: Point3D identifier.
xyz: 3D point.
rgb: Color.
error: Reconstruction error.
image_ids: Image identifiers.
point2d_idxs: Point2D indices.
"""
"""Data that corresponds to a single 3D point"""
id: int
"""Point3D identifier"""
xyz: np.ndarray
"""3D point"""
rgb: np.ndarray
"""Color"""
error: float
"""Reconstruction error"""
image_ids: np.ndarray
"""Image identifiers"""
point2d_idxs: np.ndarray
"""Point2D indices"""
CAMERA_MODELS = [
+5 -1
View File
@@ -21,7 +21,11 @@ from nerfactory.utils import comms
def decorate_all(decorators: List[Callable]) -> Callable:
"""A decorator to decorate all member functions of a class"""
"""A decorator to decorate all member functions of a class
Args:
decorators: list of decorators to add to all functions in the class
"""
def decorate(cls):
for attr in cls.__dict__:
+22 -23
View File
@@ -22,12 +22,11 @@ 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.
directions (TensorType[..., 3]): Spherical hamonic coefficients
Returns value for each component of spherical harmonics.
Returns:
TensorType[..., "components"]: Value for each component.
Args:
levels: Number of spherical harmonic levels to compute.
directions: Spherical hamonic coefficients
"""
num_components = levels**2
components = torch.zeros((*directions.shape[:-1], num_components)).to(directions.device)
@@ -90,8 +89,8 @@ class Gaussians:
"""Stores Gaussians
Args:
mean (TensorType[..., "dim"]): Mean of multivariate Gaussian
cov (TensorType[..., "dim", "dim"]): Covariance of multivariate Gaussian.
mean: Mean of multivariate Gaussian
cov: Covariance of multivariate Gaussian.
"""
mean: TensorType[..., "dim"]
@@ -107,10 +106,10 @@ def compute_3d_gaussian(
"""Compute guassian along ray.
Args:
directions (TensorType[..., 3]): Axis of Gaussian.
means (TensorType[..., 3]): Mean of Gaussian.
dir_variance (TensorType[..., 3]): Variance along direction axis.
radius_variance (TensorType[..., 3]): Variance tangent to direction axis.
directions: Axis of Gaussian.
means: Mean of Gaussian.
dir_variance: Variance along direction axis.
radius_variance: Variance tangent to direction axis.
Returns:
Gaussians: Oriented 3D gaussian.
@@ -136,11 +135,11 @@ def cylinder_to_gaussian(
"""Approximates cylinders with a Gaussian distributions.
Args:
origins (TensorType[..., 3]): Origins of cylinders.
directions (TensorType[..., 3]): Direction (axis) of cylinders.
starts (TensorType[..., 1]): Start of cylinders.
ends (TensorType[..., 1]): End of cylinders.
radius (TensorType[..., 1]): Radii of cylinders.
origins: Origins of cylinders.
directions: Direction (axis) of cylinders.
starts: Start of cylinders.
ends: End of cylinders.
radius: Radii of cylinders.
Returns:
Gaussians: Approximation of cylinders
@@ -163,11 +162,11 @@ def conical_frustum_to_gaussian(
Uses stable parameterization described in mip-NeRF publication.
Args:
origins (TensorType[..., 3]): Origins of cones.
directions (TensorType[..., 3]): Direction (axis) of frustums.
starts (TensorType[..., 1]): Start of conical frustums.
ends (TensorType[..., 1]): End of conical frustums.
radius (TensorType[..., 1]): Radii of cone a distance of 1 from the origin.
origins: Origins of cones.
directions: Direction (axis) of frustums.
starts: Start of conical frustums.
ends: End of conical frustums.
radius: Radii of cone a distance of 1 from the origin.
Returns:
Gaussians: Approximation of conical frustums
@@ -184,8 +183,8 @@ def expected_sin(x_means: torch.Tensor, x_vars: torch.Tensor) -> torch.Tensor:
"""Computes the expected value of sin(y) where y ~ N(x_means, x_vars)
Args:
x_means (torch.Tensor): Mean values.
x_vars (torch.Tensor): Variance of values.
x_means: Mean values.
x_vars: Variance of values.
Returns:
torch.Tensor: The expected value of sin.
+36 -15
View File
@@ -24,8 +24,12 @@ from typing import Any, Callable, Dict, Union
import torch
def get_dict_to_torch(stuff, device: Union[torch.device, str] = "cpu"):
"""Set everything in the dict to the specified torch device."""
def get_dict_to_torch(stuff: Any, device: Union[torch.device, str] = "cpu"):
"""Set everything in the dict to the specified torch device.
Args:
stuff: things to convert to torch
"""
if isinstance(stuff, dict):
for k, v in stuff.items():
stuff[k] = get_dict_to_torch(v, device)
@@ -35,8 +39,12 @@ def get_dict_to_torch(stuff, device: Union[torch.device, str] = "cpu"):
return stuff
def get_dict_to_cpu(stuff):
"""Set everything in the dict to CPU."""
def get_dict_to_cpu(stuff: Any):
"""Set everything in the dict to CPU.
Args:
stuff: things to place onto cpu
"""
if isinstance(stuff, dict):
for k, v in stuff.items():
stuff[k] = get_dict_to_cpu(v)
@@ -46,14 +54,19 @@ def get_dict_to_cpu(stuff):
return stuff
def is_not_none(var):
def is_not_none(var: Any) -> bool:
"""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."""
TODO(ethan): add more asserts/checks so this doesn't have unpredictable behavior.
Args:
d: dict to process
mask: mask to apply to values in dictionary
"""
masked_dict = {}
for key, value in d.items():
masked_dict[key] = value[mask]
@@ -62,7 +75,11 @@ def get_masked_dict(d, mask):
def get_hash_str_from_dict(dictionary: Dict[str, Any]) -> str:
"""MD5 hash of a dictionary. Based on
https://www.doc.ic.ac.uk/~nuric/coding/how-to-hash-a-dictionary-in-python.html"""
https://www.doc.ic.ac.uk/~nuric/coding/how-to-hash-a-dictionary-in-python.html
Args:
dictionary: dict to process
"""
dhash = hashlib.md5()
encoded = json.dumps(dictionary, sort_keys=True).encode()
dhash.update(encoded)
@@ -79,16 +96,16 @@ class IterableWrapper: # pylint: disable=too-few-public-methods
for.
Args:
new_iter (callable): function that will be called instead as the __iter__() function
new_next (callable): function that will be called instead as the __next__() function
length (int): length of the iterable. If -1, the iterable will be infinite.
new_iter: function that will be called instead as the __iter__() function
new_next: function that will be called instead as the __next__() function
length: length of the iterable. If -1, the iterable will be infinite.
Attributes:
new_iter (callable): object's pointer to the function we are calling for __iter__()
new_next (callable): object's pointer to the function we are calling for __next__()
length (int): length of the iterable. If -1, the iterable will be infinite.
i (int): current index of the iterable.
new_iter: object's pointer to the function we are calling for __iter__()
new_next: object's pointer to the function we are calling for __next__()
length: length of the iterable. If -1, the iterable will be infinite.
i: current index of the iterable.
"""
@@ -112,7 +129,11 @@ class IterableWrapper: # pylint: disable=too-few-public-methods
def human_format(num):
"""Format a number in a more human readable way"""
"""Format a number in a more human readable way
Args:
num: number to format
"""
units = ["", "K", "M", "B", "T", "P"]
k = 1000.0
magnitude = int(floor(log(num, k)))
+9 -9
View File
@@ -24,10 +24,10 @@ def to4x4(pose: TensorType[..., 3, 4]) -> TensorType[..., 4, 4]:
"""Convert 3x4 pose matrices to a 4x4 with the addition of a homogeneous coordinate.
Args:
pose (TensorType[..., 3, 4]): Camera pose without homogenous coordinate.
pose: Camera pose without homogenous coordinate.
Returns:
TensorType[..., 4, 4]: Camera poses with additional homogenous coordinate added.
Camera poses with additional homogenous coordinate added.
"""
constants = torch.zeros_like(pose[..., :1, :], device=pose.device)
constants[..., :, 3] = 1
@@ -38,10 +38,10 @@ def inverse(pose: TensorType[..., 3, 4]) -> TensorType[..., 3, 4]:
"""Invert provided pose matrix.
Args:
pose (TensorType[..., 3, 4]): Camera pose without homogenous coordinate.
pose: Camera pose without homogenous coordinate.
Returns:
TensorType[..., 3, 4]: Inverse of pose.
Inverse of pose.
"""
R = pose[..., :3, :3]
t = pose[..., :3, 3:]
@@ -54,11 +54,11 @@ def multiply(pose_a: TensorType[..., 3, 4], pose_b: TensorType[..., 3, 4]) -> Te
"""Multiply two pose matrices, A @ B.
Args:
pose_a (TensorType[..., 3, 4]): Left pose matrix, usually a transformation applied to the right.
pose_b (TensorType[..., 3, 4]): Right pose matrix, usually a camera pose that will be tranformed by pose_a.
pose_a: Left pose matrix, usually a transformation applied to the right.
pose_b: Right pose matrix, usually a camera pose that will be tranformed by pose_a.
Returns:
TensorType[..., 3, 4]: Camera pose matrix where pose_a was applied to pose_b.
Camera pose matrix where pose_a was applied to pose_b.
"""
R1, t1 = pose_a[..., :3, :3], pose_a[..., :3, 3:]
R2, t2 = pose_b[..., :3, :3], pose_b[..., :3, 3:]
@@ -71,10 +71,10 @@ def normalize(poses: TensorType[..., 3, 4]) -> TensorType[..., 3, 4]:
"""Normalize the XYZs of poses to fit within a unit cube ([-1, 1]). Note: This operation is not in-place.
Args:
poses (TensorType[..., 3, 4]): A collection of poses to be normalized.
poses: A collection of poses to be normalized.
Returns;
TensorType[..., 3, 4]: Normalized collection of poses.
Normalized collection of poses.
"""
pose_copy = torch.clone(poses)
pose_copy[..., :3, 3] /= torch.max(torch.abs(poses[..., :3, 3]))
+3 -3
View File
@@ -70,9 +70,9 @@ class Profiler:
"""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
func_name: the function name that is being profiled
start_time: the start time when function is called
end_time: the end time when function terminated
"""
val = end_time - start_time
func_dict = self.profiler_dict.get(func_name, {"val": 0, "step": 0})
+20 -17
View File
@@ -60,7 +60,8 @@ class TensorDataclass:
"""Finishes setting up the TensorDataclass
This will 1) find the broadcasted shape and 2) broadcast all fields to this shape 3)
set _shape to be the broadcasted shape."""
set _shape to be the broadcasted shape.
"""
if not dataclasses.is_dataclass(self):
raise TypeError("TensorDataclass must be a dataclass")
@@ -83,10 +84,11 @@ class TensorDataclass:
"""Returns batch shapes of all tensors in a dictionary
Args:
dict_ (Dict): The dictionary to get the batch shapes of.
dict_: The dictionary to get the batch shapes of.
Returns:
list: The batch shapes of all tensors in the dictionary."""
The batch shapes of all tensors in the dictionary.
"""
batch_shapes = []
for v in dict_.values():
if isinstance(v, torch.Tensor):
@@ -101,10 +103,11 @@ class TensorDataclass:
"""Broadcasts all tensors in a dictionary according to batch_shape
Args:
dict_ (Dict): The dictionary to broadcast.
dict_: The dictionary to broadcast.
Returns:
Dict: The broadcasted dictionary."""
The broadcasted dictionary.
"""
new_dict = {}
for k, v in dict_.items():
if isinstance(v, torch.Tensor):
@@ -161,10 +164,10 @@ class TensorDataclass:
This should deepcopy as well.
Args:
shape (Tuple[int, ...]): The new shape of the tensor dataclass.
shape: The new shape of the tensor dataclass.
Returns:
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
A new TensorDataclass with the same data but with a new shape.
"""
if isinstance(shape, int):
shape = (shape,)
@@ -187,10 +190,10 @@ class TensorDataclass:
meaning it is NOT a deepcopy, and they are still linked.
Args:
shape (Tuple[int, ...]): The new shape of the tensor dataclass.
shape: The new shape of the tensor dataclass.
Returns:
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
A new TensorDataclass with the same data but with a new shape.
"""
return self._apply_fn_to_fields(lambda x: x.broadcast_to((*shape, x.shape[-1])))
@@ -201,7 +204,7 @@ class TensorDataclass:
device: The device to place the tensor dataclass.
Returns:
TensorDataclass: A new TensorDataclass with the same data but on the specified device.
A new TensorDataclass with the same data but on the specified device.
"""
return self._apply_fn_to_fields(lambda x: x.to(device))
@@ -220,11 +223,11 @@ class TensorDataclass:
from dataclasses.fields(self) as we do below and in other places.
Args:
fn (Callable): The function to apply to tensor fields.
dataclass_fn (Optional[Callable]): The function to apply to TensorDataclass fields.
fn: The function to apply to tensor fields.
dataclass_fn: The function to apply to TensorDataclass fields.
Returns:
TensorDataclass: A new TensorDataclass with the same data but with a new shape.
A new TensorDataclass with the same data but with a new shape.
"""
new_fields = self._apply_fn_to_dict(
@@ -237,12 +240,12 @@ class TensorDataclass:
"""A helper function for _apply_fn_to_fields, applying a function to all fields of dict_
Args:
dict_ (Dict): The dictionary to apply the function to.
fn (Callable): The function to apply to tensor fields.
dataclass_fn (Optional[Callable]): The function to apply to TensorDataclass fields.
dict_: The dictionary to apply the function to.
fn: The function to apply to tensor fields.
dataclass_fn: The function to apply to TensorDataclass fields.
Returns:
Dict: A new dictionary with the same data but with a new shape. Will deep copy"""
A new dictionary with the same data but with a new shape. Will deep copy"""
field_names = dict_.keys()
new_dict = {}
+64 -49
View File
@@ -65,7 +65,12 @@ class EventType(enum.Enum):
@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"""
"""Setter function to place images into the queue to be written out
Args:
image: image to write out
step: step associated with image
"""
if isinstance(name, EventName):
name = name.value
@@ -74,7 +79,13 @@ def put_image(name, image: TensorType["H", "W", "C"], step: int):
@check_main_thread
def put_scalar(name: str, scalar: float, step: int):
"""Setter function to place scalars into the queue to be written out"""
"""Setter function to place scalars into the queue to be written out
Args:
name: name of scalar
scalar: value
step: step associated with scalar
"""
if isinstance(name, EventName):
name = name.value
@@ -83,17 +94,27 @@ def put_scalar(name: str, scalar: float, step: int):
@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"""
"""Setter function to place a dictionary of scalars into the queue to be written out
Args:
name: name of scalar dictionary
scalar_dict: values to write out
step: step associated with dict
"""
EVENT_STORAGE.append({"name": name, "write_type": EventType.DICT, "event": scalar_dict, "step": step})
@check_main_thread
def put_time(name: str, duration: float, step: int, avg_over_steps: bool = True, update_eta: bool = False):
"""Setter function to place a time element into the queue to be written out
"""Setter function to place a time element into the queue to be written out.
Processes the time info according to the options.
Processes the time info according to the options:
avg_over_steps (bool): if True, calculate and record a running average of the times
update_eta (bool): if True, update the ETA. should only be set for the training iterations/s
Args:
name: name of time item
duration: value
step: step associated with value
avg_over_steps: if True, calculate and record a running average of the times
update_eta: if True, update the ETA. should only be set for the training iterations/s
"""
if isinstance(name, EventName):
name = name.value
@@ -139,7 +160,13 @@ def write_out_storage():
@check_main_thread
def setup_event_writers(config: cfg.LoggingConfig, max_iter: int, banner_messages: Optional[List[str]] = None) -> None:
"""Initialization of all event writers specified in config"""
"""Initialization of all event writers specified in config
Args:
config: configuration to instantiate loggers
max_iter: maximum number of train iterations
banner_messages: list of messages to always display at bottom of screen
"""
for writer_type_config in config.writer:
if writer_type_config.enable:
if isinstance(writer_type_config, cfg.LocalWriterConfig):
@@ -164,12 +191,12 @@ class Writer:
@abstractmethod
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
"""_summary_
"""method to write out image
Args:
name (str): data identifier
image (TensorType["H", "W", "C"]): rendered image to write
step (int): the time step to log
name: data identifier
image: rendered image to write
step: the time step to log
"""
raise NotImplementedError
@@ -178,8 +205,9 @@ class Writer:
"""Required method to write a single scalar value to the logger
Args:
name (str): data identifier
step (int): the time step to log
name: data identifier
scalar: value to write out
step: the time step to log
"""
raise NotImplementedError
@@ -188,8 +216,8 @@ class Writer:
"""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
scalar_dict: dictionary containing all scalar values with key names and quantities
step: the time step to log
"""
for name, scalar in scalar_dict.items():
self.write_scalar(name, scalar, step)
@@ -233,22 +261,10 @@ class WandbWriter(Writer):
wandb.init(dir=config.log_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 = torch.permute(image, (2, 0, 1))
wandb.log({name: wandb.Image(image)}, step=step)
def write_scalar(self, name: str, scalar: float, step: int) -> None:
"""Wandb method to write a single scalar value to the logger
Args:
name (str): data identifier
scalar (float): scalar value to write
"""
wandb.log({name: scalar}, step=step)
@@ -261,22 +277,10 @@ class TensorboardWriter(Writer):
self.tb_writer = SummaryWriter(log_dir=config.log_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
scalar (float): scalar value to write
"""
self.tb_writer.add_scalar(name, scalar, step)
@@ -284,7 +288,7 @@ def _cursorup(x: int):
"""utility tool to move the cursor up on the terminal
Args:
x (int): amount of lines to move cursor upward
x: amount of lines to move cursor upward
"""
print(f"\r\033[{x}A", end="\x1b[1K\r")
@@ -311,14 +315,15 @@ def _format_time(seconds):
@decorate_all([check_main_thread])
class LocalWriter(Writer):
"""Local Writer Class"""
"""Local Writer Class
TODO: migrate to prettyprint
Args:
config: configuration to instatiate class
banner_messages: list of messages to always display at bottom of screen
"""
def __init__(self, config: cfg.LocalWriterConfig, banner_messages: Optional[List[str]] = None):
"""
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__(config.log_dir)
self.stats_to_track = [name.value for name in config.stats_to_track]
self.max_log_size = config.max_log_size
@@ -360,7 +365,12 @@ class LocalWriter(Writer):
return latest_map, new_key
def _update_header(self, latest_map, new_key):
"""helper to handle the printing of the header labels"""
"""helper to handle the printing of the header labels
Args:
latest_map: the most recent dictionary of stats that have been recorded
new_key: indicator whether or not there is a new key added to logger
"""
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) - self.banner_len <= 2 or new_key)
if full_log_cond or capped_log_cond:
@@ -376,7 +386,12 @@ class LocalWriter(Writer):
# self.has_printed = True
def _print_stats(self, latest_map, padding=" "):
"""helper to print out the stats in a readable format"""
"""helper to print out the stats in a readable format
Args:
latest_map: the most recent dictionary of stats that have been recorded
padding: type of characters to print to pad open space
"""
step = GLOBAL_BUFFER["step"]
fraction_done = step / GLOBAL_BUFFER["max_iter"]
curr_mssg = f"{step} ({fraction_done*100:.02f}%)"