Fix typing errors (#229)

This commit is contained in:
Matthew Tancik authored and GitHub committed 2022-07-29 14:17:38 -07:00
1 parent be001e8ebe
commit 58212543f5
30 files changed
+236 -147

No files matched your search

+2 -3
View File
@@ -25,7 +25,6 @@ from torchtyping import TensorType
from nerfactory.cameras.rays import Frustums, RaySamples
from nerfactory.fields.modules.field_heads import FieldHeadNames
from nerfactory.utils.misc import is_not_none
class Field(nn.Module):
@@ -79,7 +78,7 @@ class Field(nn.Module):
"""
valid_mask = ray_samples.valid_mask
if is_not_none(valid_mask):
if valid_mask is not None:
# Hacky handling of empty masks. Tests on a single ray but doesn't use results
if not valid_mask.any():
ray_samples = RaySamples(frustums=Frustums.get_mock_frustum().to(valid_mask.device))
@@ -105,5 +104,5 @@ class Field(nn.Module):
density, density_embedding = self.get_density(ray_samples)
field_outputs = self.get_outputs(ray_samples, density_embedding=density_embedding)
field_outputs[FieldHeadNames.DENSITY] = density
field_outputs[FieldHeadNames.DENSITY] = density # type: ignore
return field_outputs
@@ -0,0 +1,13 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
@@ -51,8 +51,10 @@ class DensityGrid(nn.Module):
on the scale but all shares the same center.
For example:
- `center=0`, `base_scale=3`, `num_cascades=1` would create one grid (lvl=0) covers the aabb [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]].
- `center=0`, `base_scale=3`, `num_cascades=2` would create one grid (lvl=0) covers the aabb [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]],
- `center=0`, `base_scale=3`, `num_cascades=1` would create one grid (lvl=0) covers
the aabb [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]].
- `center=0`, `base_scale=3`, `num_cascades=2` would create one grid (lvl=0) covers
the aabb [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]],
and one more grid (lvl=1) covers the aabb [[-3, -3, -3], [3, 3, 3]].
Normally you can simply set the `center` to the scene center, and `base_scale` to be the scene scale, and use
@@ -225,6 +227,6 @@ class DensityGrid(nn.Module):
densities = densities.view(*positions.shape[:-1], 1)
return densities
def forward(self, x):
def forward(self, x): # pylint: disable=no-self-use
"""Not implemented."""
raise RuntimeError("Shouldn't be called!")
+8 -3
View File
@@ -17,10 +17,11 @@ Instant-NGP field implementations using tiny-cuda-nn, torch, ....
"""
from typing import Tuple
from typing import Optional, Tuple
import torch
from torch.nn.parameter import Parameter
from torchtyping import TensorType
from nerfactory.cameras.rays import RaySamples
from nerfactory.data.structs import SceneBounds
@@ -110,13 +111,17 @@ class TCNNInstantNGPField(Field):
density = trunc_exp(density_before_activation.to(positions))
return density, base_mlp_out
def get_outputs(self, ray_samples: RaySamples, density_embedding=None):
def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
# TODO: add valid_mask masking!
# tcnn requires directions in the range [0,1]
directions = get_normalized_directions(ray_samples.frustums.directions)
directions_flat = directions.view(-1, 3)
d = self.direction_encoding(directions_flat)
h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim)], dim=-1)
if density_embedding is None:
positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb)
h = torch.cat([d, positions.view(-1, 3)], dim=-1)
else:
h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim)], dim=-1)
rgb = self.mlp_head(h).view(*ray_samples.frustums.directions.shape[:-1], -1).to(directions)
return {FieldHeadNames.RGB: rgb}
+2 -1
View File
@@ -16,6 +16,7 @@
The field module baseclass.
"""
from abc import abstractmethod
from typing import Optional
from torch import nn
from torchtyping import TensorType
@@ -29,7 +30,7 @@ class FieldModule(nn.Module):
out_dim (int, optional): Ouput dimension to module.
"""
def __init__(self, in_dim: int = None, out_dim: int = None) -> None:
def __init__(self, in_dim: Optional[int] = None, out_dim: Optional[int] = None) -> None:
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
+8
View File
@@ -50,6 +50,8 @@ class Identity(Encoding):
"""Identity encoding (Does not modify input)"""
def get_out_dim(self) -> int:
if self.in_dim is None:
raise ValueError("Input dimension has not been set")
return self.in_dim
def forward(self, in_tensor: TensorType["bs":..., "input_dim"]) -> TensorType["bs":..., "output_dim"]:
@@ -72,6 +74,8 @@ class ScalingAndOffset(Encoding):
self.offset = offset
def get_out_dim(self) -> int:
if self.in_dim is None:
raise ValueError("Input dimension has not been set")
return self.in_dim
def forward(self, in_tensor: TensorType["bs":..., "input_dim"]) -> TensorType["bs":..., "output_dim"]:
@@ -101,6 +105,8 @@ class NeRFEncoding(Encoding):
self.include_input = include_input
def get_out_dim(self) -> int:
if self.in_dim is None:
raise ValueError("Input dimension has not been set")
out_dim = self.in_dim * self.num_frequencies * 2
if self.include_input:
out_dim += self.in_dim
@@ -156,6 +162,8 @@ class RFFEncoding(Encoding):
if not scale > 0:
raise ValueError("RFF encoding scale should be greater than zero")
self.scale = scale
if self.in_dim is None:
raise ValueError("Input dimension has not been set")
b_matrix = torch.normal(mean=0, std=self.scale, size=(self.in_dim, self.num_frequencies))
self.register_buffer(name="b_matrix", tensor=b_matrix)
self.include_input = include_input
+5 -4
View File
@@ -42,7 +42,7 @@ class MLP(FieldModule):
num_layers: int,
layer_width: int,
out_dim: Optional[int] = None,
skip_connections: Tuple[int] = (),
skip_connections: Optional[Tuple[int]] = None,
activation: Optional[nn.Module] = nn.ReLU(),
out_activation: Optional[nn.Module] = None,
) -> None:
@@ -67,9 +67,10 @@ class MLP(FieldModule):
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."
if self.skip_connections is not None:
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:
elif self.skip_connections is not None and 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))
@@ -87,7 +88,7 @@ class MLP(FieldModule):
"""
x = in_tensor
for i, layer in enumerate(self.layers):
if i in self.skip_connections:
if self.skip_connections is not None and i in self.skip_connections:
x = torch.cat([in_tensor, x], -1)
x = layer(x)
if self.activation: