torchtyping => jaxtyping (#1838)

* Run `ruff --fix`

* Add jaxtyping migration script

* Run migration scripts + ruff + black

* Merge remote-tracking branch 'origin/main' into brent/jaxtyping

* black

* Fix lint

* fix lint

* Cleanup and more specific types

* Fixed annotation errors

* Fix more errors

* Fix annotation

* Delete _torchtyping_to_jaxtyping.py

---------

Co-authored-by: Matt Tancik <mattt4001@gmail.com>
This commit is contained in:
Brent YiandMatt Tancik authored and GitHub committed 2023-05-16 15:57:47 -07:00
1 parent 9b6290ea43
commit 6ba2a18b2b
65 files changed
+597 -531

No files matched your search

+4 -4
View File
@@ -24,8 +24,8 @@ from typing import Literal, Type, Union
import torch
import tyro
from torch import nn
from torchtyping import TensorType
from jaxtyping import Float, Int
from torch import Tensor, nn
from typing_extensions import assert_never
from nerfstudio.cameras.lie_groups import exp_map_SE3, exp_map_SO3xR3
@@ -101,8 +101,8 @@ class CameraOptimizer(nn.Module):
def forward(
self,
indices: TensorType["num_cameras"],
) -> TensorType["num_cameras", 3, 4]:
indices: Int[Tensor, "num_cameras"],
) -> Float[Tensor, "num_cameras 3 4"]:
"""Indexing into camera adjustments.
Args:
indices: indices of Cameras to optimize.
+16 -15
View File
@@ -21,8 +21,9 @@ from typing import List, Literal, Optional, Tuple
import numpy as np
import torch
from jaxtyping import Float
from numpy.typing import ArrayLike
from torchtyping import TensorType
from torch import Tensor
_EPS = np.finfo(float).eps * 4.0
@@ -184,7 +185,7 @@ def get_interpolated_poses(pose_a: ArrayLike, pose_b: ArrayLike, steps: int = 10
return poses_ab
def get_interpolated_k(k_a, k_b, steps: int = 10) -> TensorType[3, 4]:
def get_interpolated_k(k_a, k_b, steps: int = 10) -> Float[Tensor, "3 4"]:
"""
Returns interpolated path between two camera poses with specified number of steps.
@@ -202,9 +203,9 @@ def get_interpolated_k(k_a, k_b, steps: int = 10) -> TensorType[3, 4]:
def get_ordered_poses_and_k(
poses: TensorType["num_poses", 3, 4],
Ks: TensorType["num_poses", 3, 3],
) -> Tuple[TensorType["num_poses", 3, 4], TensorType["num_poses", 3, 3]]:
poses: Float[Tensor, "num_poses 3 4"],
Ks: Float[Tensor, "num_poses 3 3"],
) -> Tuple[Float[Tensor, "num_poses 3 4"], Float[Tensor, "num_poses 3 3"]]:
"""
Returns ordered poses and intrinsics by euclidian distance between poses.
@@ -238,11 +239,11 @@ def get_ordered_poses_and_k(
def get_interpolated_poses_many(
poses: TensorType["num_poses", 3, 4],
Ks: TensorType["num_poses", 3, 3],
poses: Float[Tensor, "num_poses 3 4"],
Ks: Float[Tensor, "num_poses 3 3"],
steps_per_transition: int = 10,
order_poses: bool = False,
) -> Tuple[TensorType["num_poses", 3, 4], TensorType["num_poses", 3, 3]]:
) -> Tuple[Float[Tensor, "num_poses 3 4"], Float[Tensor, "num_poses 3 3"]]:
"""Return interpolated poses for many camera poses.
Args:
@@ -273,7 +274,7 @@ def get_interpolated_poses_many(
return torch.tensor(traj, dtype=torch.float32), torch.tensor(k_interp, dtype=torch.float32)
def normalize(x: torch.Tensor) -> TensorType[...]:
def normalize(x: torch.Tensor) -> Float[Tensor, "*batch"]:
"""Returns a normalized vector."""
return x / torch.linalg.norm(x)
@@ -293,7 +294,7 @@ def normalize_with_norm(x: torch.Tensor, dim: int) -> Tuple[torch.Tensor, torch.
return x / norm, norm
def viewmatrix(lookat: torch.Tensor, up: torch.Tensor, pos: torch.Tensor) -> TensorType[...]:
def viewmatrix(lookat: torch.Tensor, up: torch.Tensor, pos: torch.Tensor) -> Float[Tensor, "*batch"]:
"""Returns a camera transformation matrix.
Args:
@@ -319,7 +320,7 @@ def get_distortion_params(
k4: float = 0.0,
p1: float = 0.0,
p2: float = 0.0,
) -> TensorType[...]:
) -> Float[Tensor, "*batch"]:
"""Returns a distortion parameters matrix.
Args:
@@ -442,7 +443,7 @@ def radial_and_tangential_undistort(
return torch.stack([x, y], dim=-1)
def rotation_matrix(a: TensorType[3], b: TensorType[3]) -> TensorType[3, 3]:
def rotation_matrix(a: Float[Tensor, "3"], b: Float[Tensor, "3"]) -> Float[Tensor, "3 3"]:
"""Compute the rotation matrix that rotates vector a to vector b.
Args:
@@ -470,7 +471,7 @@ def rotation_matrix(a: TensorType[3], b: TensorType[3]) -> TensorType[3, 3]:
return torch.eye(3) + skew_sym_mat + skew_sym_mat @ skew_sym_mat * ((1 - c) / (s**2 + 1e-8))
def focus_of_attention(poses: TensorType["num_poses":..., 4, 4], initial_focus: TensorType[3]) -> TensorType[3]:
def focus_of_attention(poses: Float[Tensor, "*num_poses 4 4"], initial_focus: Float[Tensor, "3"]) -> Float[Tensor, "3"]:
"""Compute the focus of attention of a set of cameras. Only cameras
that have the focus of attention in front of them are considered.
@@ -509,10 +510,10 @@ def focus_of_attention(poses: TensorType["num_poses":..., 4, 4], initial_focus:
def auto_orient_and_center_poses(
poses: TensorType["num_poses":..., 4, 4],
poses: Float[Tensor, "*num_poses 4 4"],
method: Literal["pca", "up", "vertical", "none"] = "up",
center_method: Literal["poses", "focus", "none"] = "poses",
) -> Tuple[TensorType["num_poses":..., 3, 4], TensorType[3, 4]]:
) -> Tuple[Float[Tensor, "*num_poses 3 4"], Float[Tensor, "3 4"]]:
"""Orients and centers the poses. We provide two methods for orientation: pca and up.
pca: Orient the poses so that the principal directions of the camera centers are aligned
+44 -43
View File
@@ -24,8 +24,9 @@ from typing import Dict, List, Optional, Tuple, Union
import cv2
import torch
import torchvision
from jaxtyping import Float, Int, Shaped
from torch import Tensor
from torch.nn import Parameter
from torchtyping import TensorType
import nerfstudio.utils.math
import nerfstudio.utils.poses as pose_utils
@@ -77,44 +78,44 @@ class Cameras(TensorDataclass):
and will be broadcasted to the rays generated from any derivative RaySamples we create with this
"""
camera_to_worlds: TensorType["num_cameras":..., 3, 4]
fx: TensorType["num_cameras":..., 1]
fy: TensorType["num_cameras":..., 1]
cx: TensorType["num_cameras":..., 1]
cy: TensorType["num_cameras":..., 1]
width: TensorType["num_cameras":..., 1]
height: TensorType["num_cameras":..., 1]
distortion_params: Optional[TensorType["num_cameras":..., 6]]
camera_type: TensorType["num_cameras":..., 1]
times: Optional[TensorType["num_cameras", 1]]
camera_to_worlds: Float[Tensor, "*num_cameras 3 4"]
fx: Float[Tensor, "*num_cameras 1"]
fy: Float[Tensor, "*num_cameras 1"]
cx: Float[Tensor, "*num_cameras 1"]
cy: Float[Tensor, "*num_cameras 1"]
width: Shaped[Tensor, "*num_cameras 1"]
height: Shaped[Tensor, "*num_cameras 1"]
distortion_params: Optional[Float[Tensor, "*num_cameras 6"]]
camera_type: Int[Tensor, "*num_cameras 1"]
times: Optional[Float[Tensor, "num_cameras 1"]]
metadata: Optional[Dict]
def __init__(
self,
camera_to_worlds: TensorType["batch_c2ws":..., 3, 4],
fx: Union[TensorType["batch_fxs":..., 1], float],
fy: Union[TensorType["batch_fys":..., 1], float],
cx: Union[TensorType["batch_cxs":..., 1], float],
cy: Union[TensorType["batch_cys":..., 1], float],
width: Optional[Union[TensorType["batch_ws":..., 1], int]] = None,
height: Optional[Union[TensorType["batch_hs":..., 1], int]] = None,
distortion_params: Optional[TensorType["batch_dist_params":..., 6]] = None,
camera_to_worlds: Float[Tensor, "*batch_c2ws 3 4"],
fx: Union[Float[Tensor, "*batch_fxs 1"], float],
fy: Union[Float[Tensor, "*batch_fys 1"], float],
cx: Union[Float[Tensor, "*batch_cxs 1"], float],
cy: Union[Float[Tensor, "*batch_cys 1"], float],
width: Optional[Union[Shaped[Tensor, "*batch_ws 1"], int]] = None,
height: Optional[Union[Shaped[Tensor, "*batch_hs 1"], int]] = None,
distortion_params: Optional[Float[Tensor, "*batch_dist_params 6"]] = None,
camera_type: Optional[
Union[
TensorType["batch_cam_types":..., 1],
Int[Tensor, "*batch_cam_types 1"],
int,
List[CameraType],
CameraType,
]
] = CameraType.PERSPECTIVE,
times: Optional[TensorType["num_cameras"]] = None,
times: Optional[Float[Tensor, "num_cameras"]] = None,
metadata: Optional[Dict] = None,
) -> None:
"""Initializes the Cameras object.
Note on Input Tensor Dimensions: All of these tensors have items of dimensions TensorType[3, 4]
(in the case of the c2w matrices), TensorType[6] (in the case of distortion params), or
TensorType[1] (in the case of the rest of the elements). The dimensions before that are
Note on Input Tensor Dimensions: All of these tensors have items of dimensions Shaped[Tensor, "3 4"]
(in the case of the c2w matrices), Shaped[Tensor, "6"] (in the case of distortion params), or
Shaped[Tensor, "1"] (in the case of the rest of the elements). The dimensions before that are
considered the batch dimension of that tensor (batch_c2ws, batch_fxs, etc.). We will broadcast
all the tensors to be the same batch dimension. This means you can use any combination of the
input types in the function signature and it won't break. Your batch size for all tensors
@@ -172,9 +173,9 @@ class Cameras(TensorDataclass):
def _init_get_camera_type(
self,
camera_type: Union[
TensorType["batch_cam_types":..., 1], TensorType["batch_cam_types":...], int, List[CameraType], CameraType
Int[Tensor, "*batch_cam_types 1"], Int[Tensor, "*batch_cam_types"], int, List[CameraType], CameraType
],
) -> TensorType["num_cameras":..., 1]:
) -> Int[Tensor, "*num_cameras 1"]:
"""
Parses the __init__() argument camera_type
@@ -213,9 +214,9 @@ class Cameras(TensorDataclass):
def _init_get_height_width(
self,
h_w: Union[TensorType["batch_hws":..., 1], TensorType["batch_hws":...], int, None],
c_x_y: TensorType["batch_cxys":...],
) -> TensorType["num_cameras":..., 1]:
h_w: Union[Shaped[Tensor, "*batch_hws 1"], Shaped[Tensor, "*batch_hws"], int, None],
c_x_y: Shaped[Tensor, "*batch_cxys"],
) -> Shaped[Tensor, "*num_cameras 1"]:
"""
Parses the __init__() argument for height or width
@@ -260,12 +261,12 @@ class Cameras(TensorDataclass):
return self.camera_to_worlds.device
@property
def image_height(self) -> TensorType["num_cameras":..., 1]:
def image_height(self) -> Shaped[Tensor, "*num_cameras 1"]:
"""Returns the height of the images."""
return self.height
@property
def image_width(self) -> TensorType["num_cameras":..., 1]:
def image_width(self) -> Shaped[Tensor, "*num_cameras 1"]:
"""Returns the height of the images."""
return self.width
@@ -281,7 +282,7 @@ class Cameras(TensorDataclass):
def get_image_coords(
self, pixel_offset: float = 0.5, index: Optional[Tuple] = None
) -> TensorType["height", "width", 2]:
) -> Float[Tensor, "height width 2"]:
"""This gets the image coordinates of one of the cameras in this object.
If no index is specified, it will return the maximum possible sized height / width image coordinate map,
@@ -309,10 +310,10 @@ class Cameras(TensorDataclass):
def generate_rays( # pylint: disable=too-many-statements
self,
camera_indices: Union[TensorType["num_rays":..., "num_cameras_batch_dims"], int],
coords: Optional[TensorType["num_rays":..., 2]] = None,
camera_opt_to_camera: Optional[TensorType["num_rays":..., 3, 4]] = None,
distortion_params_delta: Optional[TensorType["num_rays":..., 6]] = None,
camera_indices: Union[Int[Tensor, "*num_rays num_cameras_batch_dims"], int],
coords: Optional[Float[Tensor, "*num_rays 2"]] = None,
camera_opt_to_camera: Optional[Float[Tensor, "*num_rays 3 4"]] = None,
distortion_params_delta: Optional[Float[Tensor, "*num_rays 6"]] = None,
keep_shape: Optional[bool] = None,
disable_distortion: bool = False,
aabb_box: Optional[SceneBox] = None,
@@ -487,10 +488,10 @@ class Cameras(TensorDataclass):
# pylint: disable=too-many-statements
def _generate_rays_from_coords(
self,
camera_indices: TensorType["num_rays":..., "num_cameras_batch_dims"],
coords: TensorType["num_rays":..., 2],
camera_opt_to_camera: Optional[TensorType["num_rays":..., 3, 4]] = None,
distortion_params_delta: Optional[TensorType["num_rays":..., 6]] = None,
camera_indices: Int[Tensor, "*num_rays num_cameras_batch_dims"],
coords: Float[Tensor, "*num_rays 2"],
camera_opt_to_camera: Optional[Float[Tensor, "*num_rays 3 4"]] = None,
distortion_params_delta: Optional[Float[Tensor, "*num_rays 6"]] = None,
disable_distortion: bool = False,
) -> RayBundle:
"""Generates rays for the given camera indices and coords where self isn't jagged
@@ -734,7 +735,7 @@ class Cameras(TensorDataclass):
)
def to_json(
self, camera_idx: int, image: Optional[TensorType["height", "width", 2]] = None, max_size: Optional[int] = None
self, camera_idx: int, image: Optional[Float[Tensor, "height width 2"]] = None, max_size: Optional[int] = None
) -> Dict:
"""Convert a camera to a json dictionary.
@@ -768,7 +769,7 @@ class Cameras(TensorDataclass):
json_["image"] = str("data:image/jpeg;base64," + base64.b64encode(data).decode("ascii"))
return json_
def get_intrinsics_matrices(self) -> TensorType["num_cameras":..., 3, 3]:
def get_intrinsics_matrices(self) -> Float[Tensor, "*num_cameras 3 3"]:
"""Returns the intrinsic matrices for each camera.
Returns:
@@ -783,7 +784,7 @@ class Cameras(TensorDataclass):
return K
def rescale_output_resolution(
self, scaling_factor: Union[TensorType["num_cameras":...], TensorType["num_cameras":..., 1], float, int]
self, scaling_factor: Union[Shaped[Tensor, "*num_cameras"], Shaped[Tensor, "*num_cameras 1"], float, int]
) -> None:
"""Rescale the output resolution of the cameras.
+4 -3
View File
@@ -16,11 +16,12 @@
Helper for Lie group operations. Currently only used for pose optimization.
"""
import torch
from torchtyping import TensorType
from jaxtyping import Float
from torch import Tensor
# We make an exception on snake case conventions because SO3 != so3.
def exp_map_SO3xR3(tangent_vector: TensorType["b", 6]) -> TensorType["b", 3, 4]: # pylint: disable=invalid-name
def exp_map_SO3xR3(tangent_vector: Float[Tensor, "b 6"]) -> Float[Tensor, "b 3 4"]: # pylint: disable=invalid-name
"""Compute the exponential map of the direct product group `SO(3) x R^3`.
This can be used for learning pose deltas on SE(3), and is generally faster than `exp_map_SE3`.
@@ -58,7 +59,7 @@ def exp_map_SO3xR3(tangent_vector: TensorType["b", 6]) -> TensorType["b", 3, 4]:
return ret
def exp_map_SE3(tangent_vector: TensorType["b", 6]) -> TensorType["b", 3, 4]: # pylint: disable=invalid-name
def exp_map_SE3(tangent_vector: Float[Tensor, "b 6"]) -> Float[Tensor, "b 3 4"]: # pylint: disable=invalid-name
"""Compute the exponential map `se(3) -> SE(3)`.
This can be used for learning pose deltas on `SE(3)`.
+31 -30
View File
@@ -20,7 +20,8 @@ from dataclasses import dataclass
from typing import Callable, Dict, Optional, Tuple, Union
import torch
from torchtyping import TensorType
from jaxtyping import Float, Int, Shaped
from torch import Tensor
from nerfstudio.utils.math import Gaussians, conical_frustum_to_gaussian
from nerfstudio.utils.tensor_dataclass import TensorDataclass
@@ -32,20 +33,20 @@ TORCH_DEVICE = Union[str, torch.device] # pylint: disable=invalid-name
class Frustums(TensorDataclass):
"""Describes region of space as a frustum."""
origins: TensorType["bs":..., 3]
origins: Float[Tensor, "*bs 3"]
"""xyz coordinate for ray origin."""
directions: TensorType["bs":..., 3]
directions: Float[Tensor, "*bs 3"]
"""Direction of ray."""
starts: TensorType["bs":..., 1]
starts: Float[Tensor, "*bs 1"]
"""Where the frustum starts along a ray."""
ends: TensorType["bs":..., 1]
ends: Float[Tensor, "*bs 1"]
"""Where the frustum ends along a ray."""
pixel_area: TensorType["bs":..., 1]
pixel_area: Float[Tensor, "*bs 1"]
"""Projected area of pixel a distance 1 away from origin."""
offsets: Optional[TensorType["bs":..., 3]] = None
offsets: Optional[Float[Tensor, "*bs 3"]] = None
"""Offsets for each sample position"""
def get_positions(self) -> TensorType[..., 3]:
def get_positions(self) -> Float[Tensor, "*batch 3"]:
"""Calculates "center" position of frustum. Not weighted by mass.
Returns:
@@ -56,7 +57,7 @@ class Frustums(TensorDataclass):
pos = pos + self.offsets
return pos
def get_start_positions(self) -> TensorType[..., 3]:
def get_start_positions(self) -> Float[Tensor, "*batch 3"]:
"""Calculates "start" position of frustum.
Returns:
@@ -108,23 +109,23 @@ class RaySamples(TensorDataclass):
frustums: Frustums
"""Frustums along ray."""
camera_indices: Optional[TensorType["bs":..., 1]] = None
camera_indices: Optional[Int[Tensor, "*bs 1"]] = None
"""Camera index."""
deltas: Optional[TensorType["bs":..., 1]] = None
deltas: Optional[Float[Tensor, "*bs 1"]] = None
""""width" of each sample."""
spacing_starts: Optional[TensorType["bs":..., "num_samples", 1]] = None
spacing_starts: Optional[Float[Tensor, "*bs num_samples 1"]] = None
"""Start of normalized bin edges along ray [0,1], before warping is applied, ie. linear in disparity sampling."""
spacing_ends: Optional[TensorType["bs":..., "num_samples", 1]] = None
spacing_ends: Optional[Float[Tensor, "*bs num_samples 1"]] = None
"""Start of normalized bin edges along ray [0,1], before warping is applied, ie. linear in disparity sampling."""
spacing_to_euclidean_fn: Optional[Callable] = None
"""Function to convert bins to euclidean distance."""
metadata: Optional[Dict[str, TensorType["bs":..., "latent_dims"]]] = None
metadata: Optional[Dict[str, Shaped[Tensor, "*bs latent_dims"]]] = None
"""additional information relevant to generating ray samples"""
times: Optional[TensorType[..., 1]] = None
times: Optional[Float[Tensor, "*batch 1"]] = None
"""Times at which rays are sampled"""
def get_weights(self, densities: TensorType[..., "num_samples", 1]) -> TensorType[..., "num_samples", 1]:
def get_weights(self, densities: Float[Tensor, "*batch num_samples 1"]) -> Float[Tensor, "*batch num_samples 1"]:
"""Return weights based on predicted densities
Args:
@@ -150,8 +151,8 @@ class RaySamples(TensorDataclass):
@staticmethod
def get_weights_and_transmittance_from_alphas(
alphas: TensorType[..., "num_samples", 1], weights_only: bool = False
) -> Tuple[TensorType[..., "num_samples", 1], TensorType[..., "num_samples", 1]]:
alphas: Float[Tensor, "*batch num_samples 1"], weights_only: bool = False
) -> Tuple[Float[Tensor, "*batch num_samples 1"], Float[Tensor, "*batch num_samples 1"]]:
"""Return weights based on predicted alphas
Args:
alphas: Predicted alphas (maybe from sdf) for samples along ray
@@ -175,21 +176,21 @@ class RayBundle(TensorDataclass):
"""A bundle of ray parameters."""
# TODO(ethan): make sure the sizes with ... are correct
origins: TensorType[..., 3]
origins: Float[Tensor, "*batch 3"]
"""Ray origins (XYZ)"""
directions: TensorType[..., 3]
directions: Float[Tensor, "*batch 3"]
"""Unit ray direction vector"""
pixel_area: TensorType[..., 1]
pixel_area: Float[Tensor, "*batch 1"]
"""Projected area of pixel a distance 1 away from origin"""
camera_indices: Optional[TensorType[..., 1]] = None
camera_indices: Optional[Int[Tensor, "*batch 1"]] = None
"""Camera indices"""
nears: Optional[TensorType[..., 1]] = None
nears: Optional[Float[Tensor, "*batch 1"]] = None
"""Distance along ray to start sampling"""
fars: Optional[TensorType[..., 1]] = None
fars: Optional[Float[Tensor, "*batch 1"]] = None
"""Rays Distance along ray to stop sampling"""
metadata: Optional[Dict[str, TensorType["num_rays", "latent_dims"]]] = None
metadata: Optional[Dict[str, Shaped[Tensor, "num_rays latent_dims"]]] = None
"""Additional metadata or data needed for interpolation, will mimic shape of rays"""
times: Optional[TensorType[..., 1]] = None
times: Optional[Float[Tensor, "*batch 1"]] = None
"""Times at which rays are sampled"""
def set_camera_indices(self, camera_index: int) -> None:
@@ -232,10 +233,10 @@ class RayBundle(TensorDataclass):
def get_ray_samples(
self,
bin_starts: TensorType["bs":..., "num_samples", 1],
bin_ends: TensorType["bs":..., "num_samples", 1],
spacing_starts: Optional[TensorType["bs":..., "num_samples", 1]] = None,
spacing_ends: Optional[TensorType["bs":..., "num_samples", 1]] = None,
bin_starts: Float[Tensor, "*bs num_samples 1"],
bin_ends: Float[Tensor, "*bs num_samples 1"],
spacing_starts: Optional[Float[Tensor, "*bs num_samples 1"]] = None,
spacing_ends: Optional[Float[Tensor, "*bs num_samples 1"]] = None,
spacing_to_euclidean_fn: Optional[Callable] = None,
) -> RaySamples:
"""Produces samples for each ray by projection points along the ray direction. Currently samples uniformly.