diff --git a/.github/workflows/code_checks.yml b/.github/workflows/code_checks.yml index 7ea8b9b98..af536cb09 100644 --- a/.github/workflows/code_checks.yml +++ b/.github/workflows/code_checks.yml @@ -33,8 +33,9 @@ jobs: pylint mattport tests \ --max-line-length=120 \ --generated-members=numpy.*,torch.*,cv2.*,cv.* \ - --good-names=e,c,i,j,x,y,lr,K,fx,fy,cx,cy,H,W,ts \ + --good-names=e,c,i,j,x,y,lr,K,fx,fy,cx,cy,H,W,ts,t,u \ --disable=too-many-arguments \ + --disable=too-many-locals \ --disable=fixme - name: Test with pytest run: | diff --git a/.vscode/settings.json b/.vscode/settings.json index cea078e23..ab9efac9c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -29,8 +29,9 @@ "python.linting.pylintArgs": [ "--generated-members=numpy.*,torch.*,cv2.*,cv.*", "--max-line-length=120", - "--good-names=e,c,i,j,x,y,lr,K,fx,fy,cx,cy,H,W,ts", + "--good-names=e,c,i,j,x,y,lr,K,fx,fy,cx,cy,H,W,ts,t,u", "--disable=too-many-arguments", - "--disable=fixme" + "--disable=fixme", + "--disable=too-many-locals" ], } \ No newline at end of file diff --git a/mattport/nerf/field_modules/field_heads.py b/mattport/nerf/field_modules/field_heads.py index b1cf6839e..50598117c 100644 --- a/mattport/nerf/field_modules/field_heads.py +++ b/mattport/nerf/field_modules/field_heads.py @@ -21,16 +21,20 @@ class FieldHeadOutputs: class FieldHead(FieldModule): """Base field output""" - def __init__(self, in_dim: int, out_dim: int, activation: Optional[nn.Module] = None) -> None: + def __init__( + self, in_dim: int, out_dim: int, field_quantity_name: str, activation: Optional[nn.Module] = None + ) -> None: """ Args: in_dim (int): input dimension out_dim (int): output dimension for renderer + field_quantity_name (srt): name of field head activation (Optional[nn.Module]): output head activation """ super().__init__() self.in_dim = in_dim self.out_dim = out_dim + self.field_quantity_name = field_quantity_name self.activation = activation self.net = None self.build_nn_modules() @@ -41,7 +45,7 @@ class FieldHead(FieldModule): layers.append(self.activation) self.net = nn.Sequential(*layers) - def forward(self, in_tensor: TensorType[..., "in_dim"]) -> TensorType[..., "out_dim"]: + def forward(self, in_tensor: TensorType[..., "in_dim"]) -> FieldHeadOutputs: """Process network output for renderer Args: @@ -64,13 +68,11 @@ class DensityFieldHead(FieldHead): """Density output""" def __init__(self, in_dim: int, activation: Optional[nn.Module] = nn.Softplus()) -> None: - super().__init__(in_dim, 1, activation) - self.field_quantity_name = "density" + super().__init__(in_dim, out_dim=1, field_quantity_name="density", activation=activation) class RGBFieldHead(FieldHead): """RGB output""" def __init__(self, in_dim: int, activation: Optional[nn.Module] = nn.Sigmoid()) -> None: - super().__init__(in_dim, 3, activation) - self.field_quantity_name = "rgb" + super().__init__(in_dim, out_dim=3, field_quantity_name="rgb", activation=activation) diff --git a/mattport/nerf/graph/nerf.py b/mattport/nerf/graph/nerf.py index 700683fd9..4c2598704 100644 --- a/mattport/nerf/graph/nerf.py +++ b/mattport/nerf/graph/nerf.py @@ -10,7 +10,7 @@ from mattport.nerf.field_modules.ray_generator import RayGenerator from mattport.nerf.graph.base import Graph from mattport.nerf.loss import MSELoss from mattport.nerf.renderers import RGBRenderer -from mattport.nerf.sampler import UniformSampler +from mattport.nerf.sampler import PDFSampler, UniformSampler class NeRFGraph(Graph): @@ -29,7 +29,7 @@ class NeRFGraph(Graph): # samplers self.sampler_uniform = UniformSampler(near_plane=0.1, far_plane=4.0, num_samples=64) - self.sampler_pdf = UniformSampler(near_plane=0.1, far_plane=4.0, num_samples=64) + self.sampler_pdf = PDFSampler(num_samples=64) # field self.field_coarse = NeRFField() @@ -52,7 +52,7 @@ class NeRFGraph(Graph): rgb=coarse_field_outputs.rgb, density=coarse_field_outputs.density, deltas=uniform_ray_samples.deltas ) # RendererOutputs # fine network: - pdf_ray_samples = self.sampler_uniform(ray_bundle) # RaySamples + pdf_ray_samples = self.sampler_pdf(ray_bundle, uniform_ray_samples, coarse_field_outputs.density) # RaySamples fine_field_outputs = self.field_fine(pdf_ray_samples) # FieldOutputs fine_renderer_outputs = self.renderer_rgb( rgb=fine_field_outputs.rgb, density=fine_field_outputs.density, deltas=pdf_ray_samples.deltas diff --git a/mattport/nerf/sampler.py b/mattport/nerf/sampler.py index 439e09a7f..c86dc8458 100644 --- a/mattport/nerf/sampler.py +++ b/mattport/nerf/sampler.py @@ -2,6 +2,7 @@ Collection of sampling strategies """ +from typing import Optional import torch from torch import nn from torchtyping import TensorType @@ -9,12 +10,11 @@ from torchtyping import TensorType from mattport.structures.rays import RayBundle, RaySamples -class Sampler(nn.Module): - """Base Sampler. Intended to be subclassed""" +class UniformSampler(nn.Module): + """Sample uniformly along a ray""" def __init__(self, near_plane: float, far_plane: float, num_samples: int) -> None: - """Inialize sampler - + """ Args: near_plane (float): Minimum distance along ray to sample far_plane (float): Maximum distance along ray to sample @@ -26,44 +26,21 @@ class Sampler(nn.Module): self.far_plane = far_plane self.num_samples = num_samples - def generate_samples( - self, ray_bundle: RayBundle, near_plane: float, far_plane: float, num_samples: int + def forward( + self, + ray_bundle: RayBundle, + near_plane: Optional[float] = None, + far_plane: Optional[float] = None, + num_samples: Optional[int] = None, ) -> RaySamples: - """Encodes an input tensor. + """Generates position samples uniformly. Args: - camera_rays (cameras.Rays): Rays to generate samples for + ray_bundle (RayBundle): Rays to generate samples for TensorType[..., "output_dim"]: A encoded input tensor - near_plane (float): Minimum distance along ray to sample - far_plane (float): Maximum distance along ray to sample - num_samples (int): Number of samples per ray - - Returns: - RaySamples: Positions and deltas for samples along a ray - """ - raise NotImplementedError - - def forward(self, ray_bundle: RayBundle) -> TensorType[..., "num_samples", 3]: - """Call forward""" - return self.generate_samples( - ray_bundle, near_plane=self.near_plane, far_plane=self.far_plane, num_samples=self.num_samples - ) - - -class UniformSampler(Sampler): - """Base Sampler. Intended to be subclassed""" - - def generate_samples( - self, ray_bundle: RayBundle, near_plane: float, far_plane: float, num_samples: int - ) -> RaySamples: - """Encodes an input tensor. - - Args: - camera_rays (cameras.Rays): Rays to generate samples for - TensorType[..., "output_dim"]: A encoded input tensor - near_plane (float): Minimum distance along ray to sample - far_plane (float): Maximum distance along ray to sample - num_samples (int): Number of samples per ray + 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 @@ -72,13 +49,103 @@ class UniformSampler(Sampler): far_plane = far_plane or self.far_plane num_samples = num_samples or self.num_samples - bins = torch.linspace(near_plane, far_plane, num_samples + 1).to(ray_bundle.origins.device) # (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 = bins.unsqueeze(0).repeat(num_rays, 1) # (num_rays, num_samples+1) + ray_samples = RaySamples( - t_min=torch.ones_like(ray_bundle.origins[:, 0]) * near_plane, - t_max=torch.ones_like(ray_bundle.origins[:, 0]) * far_plane, - ts=bins.unsqueeze(0).repeat(num_rays, 1), # (num_rays, num_samples) + bins=bins, ray_bundle=ray_bundle, ) + + return ray_samples + + +class PDFSampler(nn.Module): + """Sample based on probability distribution""" + + def __init__(self, num_samples: int) -> None: + """ + Args: + num_samples (int): Number of samples per ray + """ + super().__init__() + + self.num_samples = num_samples + + def forward( + self, + ray_bundle: RayBundle, + coarse_ray_samples: RaySamples, + density: TensorType[..., "num_samples", 1], + num_samples: Optional[int] = None, + randomized: bool = True, + eps: float = 1e-5, + ) -> RaySamples: + """Generates position samples given a distribution. + + Args: + ray_bundle (RayBundle): Rays to generate samples for + TensorType[..., "output_dim"]: A encoded input tensor + bins (TensorType[..., "num_samples"]): Ray bins + weights: (TensorType[..., "num_samples"]): Weights for each bin + num_samples (Optional[int]): Number of samples per ray + randomized: boolean: Randomize location within each bin. Defaults to True + eps: float: Small value to prevent numerical issues. Defaults to 1e-5 + + Returns: + RaySamples: Positions and deltas for samples along a ray + """ + + num_samples = num_samples or self.num_samples + + # Calculate weight contributions along ray + # Todo(matt): This computation is duplicated + delta_density = coarse_ray_samples.deltas * density[..., 0] + alphas = 1 - torch.exp(-delta_density) + + transmittance = torch.cumsum(delta_density[..., :-1], dim=-1) + transmittance = torch.cat( + [torch.zeros((*transmittance.shape[:1], 1)).to(density.device), transmittance], axis=-1 + ) + transmittance = torch.exp(-transmittance) # [..., "num_samples"] + weights = alphas * transmittance # [..., "num_samples"] + + # Add small offset to rays with zero weight to prevent NaNs + weights_sum = torch.sum(weights, dim=-1, keepdim=True) + padding = torch.relu(eps - weights_sum) + weights += padding / weights.shape[-1] + weights_sum += padding + + pdf = weights / weights_sum + cdf = torch.min(torch.ones_like(pdf), torch.cumsum(pdf, dim=-1)) + cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], dim=-1) + + if randomized: + u = torch.rand(size=(*cdf.shape[:-1], num_samples), device=cdf.device) + else: + u = torch.linspace(0.0, 1.0, steps=num_samples, device=cdf.device) + u = torch.expand(size=(*cdf.shape[:-1], num_samples)) + + # u = u.contiguous() + indicies = torch.searchsorted(cdf, u, right=True) + below = torch.max(torch.zeros_like(indicies), indicies - 1) + above = torch.min(cdf.shape[-1] - torch.ones_like(indicies), indicies) + + indicies_g = torch.stack([below, above], -1) + matched_shape = (indicies_g.shape[0], indicies_g.shape[1], cdf.shape[-1]) + cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), dim=2, index=indicies_g) + bins_g = torch.gather(coarse_ray_samples.bins.unsqueeze(1).expand(matched_shape), dim=2, index=indicies_g) + + denom = cdf_g[..., 1] - cdf_g[..., 0] + denom = torch.where(denom < eps, torch.ones_like(denom), denom) + t = (u - cdf_g[..., 0]) / denom + samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0]) + + ray_samples = RaySamples( + bins=samples, # TODO(matt) These are not bins! + ray_bundle=ray_bundle, + ) + return ray_samples diff --git a/mattport/nerf/trainer.py b/mattport/nerf/trainer.py index bb4e39d64..129c81fdf 100644 --- a/mattport/nerf/trainer.py +++ b/mattport/nerf/trainer.py @@ -60,7 +60,7 @@ class Trainer: ).to(f"cuda:{self.local_rank}") ## TODO(): we need to call load_checkpoint here if need be (before we wrap it in DDP) - + if self.world_size > 1: self.graph = DDP(self.graph, device_ids=[self.local_rank]) dist.barrier(device_ids=[self.local_rank]) @@ -116,7 +116,7 @@ class Trainer: def train_epoch(self): """_summary_""" num_iters = 100 - for step in tqdm(range(num_iters)): + for _ in tqdm(range(num_iters)): batch = next(iter(self.train_dataloader)) self.train_iteration(batch) # TODO(): proper saving with the correct directory path and such diff --git a/mattport/structures/rays.py b/mattport/structures/rays.py index 4b72a860d..3ab16f782 100644 --- a/mattport/structures/rays.py +++ b/mattport/structures/rays.py @@ -72,14 +72,10 @@ class RaySamples: def __init__( self, - t_min: TensorType["num_rays"], - t_max: TensorType["num_rays"], - ts: TensorType["num_rays", "num_samples+1"], + bins: TensorType["num_rays", "num_samples+1"], ray_bundle: RayBundle, ) -> None: - self.t_min = t_min - self.t_max = t_max - self.ts = ts + self.bins = bins self.positions = self.get_positions(ray_bundle) self.directions = ray_bundle.directions.unsqueeze(1).repeat(1, self.positions.shape[1], 1) self.deltas = self.get_deltas() @@ -87,11 +83,11 @@ class RaySamples: def get_positions(self, ray_bundle: RayBundle) -> TensorType["num_rays", "num_samples", 3]: """Returns positions.""" # TODO(ethan): check with Matt about this - t_mid = (self.ts[:, 1:] + self.ts[:, :-1]) / 2 # (num_rays, num_samples) + t_mid = (self.bins[:, 1:] + self.bins[:, :-1]) / 2 # (num_rays, num_samples) return ray_bundle.origins[:, None] + t_mid[:, :, None] * ray_bundle.directions[:, None] - def get_deltas(self) -> TensorType["num_samples"]: + def get_deltas(self) -> TensorType[..., "num_samples"]: """Returns deltas.""" - deltas = self.ts[..., 1:] - self.ts[..., :-1] + deltas = self.bins[..., 1:] - self.bins[..., :-1] # TODO(ethan): check this with Matt return deltas diff --git a/tests/nerf/field_modules/test_field_outputs.py b/tests/nerf/field_modules/test_field_outputs.py index 353bf075b..d6303ffca 100644 --- a/tests/nerf/field_modules/test_field_outputs.py +++ b/tests/nerf/field_modules/test_field_outputs.py @@ -1,7 +1,6 @@ """ Field output tests """ -import pytest import torch from torch import nn @@ -13,17 +12,13 @@ def test_field_output(): in_dim = 6 out_dim = 4 activation = nn.ReLU() - render_head = field_heads.FieldHead(in_dim=in_dim, out_dim=out_dim, activation=activation) + render_head = field_heads.FieldHead( + in_dim=in_dim, out_dim=out_dim, field_quantity_name="rgb", activation=activation + ) assert render_head.get_out_dim() == out_dim x = torch.ones((9, in_dim)) - - with pytest.raises(SystemError): - render_head(x) - render_head.build_nn_modules() - y = render_head(x) - - assert y.shape[-1] == out_dim + render_head(x) def test_density_output(): @@ -33,12 +28,7 @@ def test_density_output(): assert density_head.get_out_dim() == 1 x = torch.ones((9, in_dim)) - with pytest.raises(SystemError): - density_head(x) - density_head.build_nn_modules() - y = density_head(x) - - assert y.shape[-1] == 1 + density_head(x) def test_rgb_output(): @@ -48,9 +38,4 @@ def test_rgb_output(): assert rgb_head.get_out_dim() == 3 x = torch.ones((9, in_dim)) - with pytest.raises(SystemError): - rgb_head(x) - rgb_head.build_nn_modules() - y = rgb_head(x) - - assert y.shape[-1] == 3 + rgb_head(x) diff --git a/tests/nerf/graph/test_graph.py b/tests/nerf/graph/test_graph.py deleted file mode 100644 index b4a3e6f71..000000000 --- a/tests/nerf/graph/test_graph.py +++ /dev/null @@ -1,128 +0,0 @@ -""" -Tests of graph construction -""" -import numpy as np -from hydra import compose, initialize -from omegaconf import open_dict - -from mattport.nerf.graph.base import Graph, Node - -CONFIG_DIR = "configs" - - -def check_consistency(root: Node, targets: list): - """rudimentary check on predicted graph versus expected target ordering""" - curr_pointer = root - for i, (target_name, target_children) in enumerate(targets): - assert curr_pointer.name == target_name - assert len(curr_pointer.children) == target_children - if len(curr_pointer.children) > 0: - assert targets[i + 1][0] in curr_pointer.children - curr_pointer = curr_pointer.children[targets[i + 1][0]] - - -def instantiate_graph(config_name: str) -> Graph: - """load correct graph given hydra config""" - with initialize(config_path=CONFIG_DIR): - cfg = compose(config_name=config_name) - test_graph = Graph(cfg.network) - return test_graph, cfg - - -def test_graph_init(): - """test field modules dictionary is instantiated properly""" - test_graph, _ = instantiate_graph("test_basic_graph") - assert test_graph is not None - assert type(test_graph["encoder_0"]).__name__ == "ScalingAndOffset" - assert type(test_graph["mlp_0"]).__name__ == "MLP" - assert type(test_graph["mlp_1"]).__name__ == "MLP" - - -def test_input_dimension(): - """test field module input dimension calculation""" - test_graph, _ = instantiate_graph("test_repeat_graph") - assert test_graph["mlp_0"].in_dim == 16 - assert test_graph["mlp_1"].in_dim == 1 - - -def test_construct_graph_basic(): - """test construction of dependency graph: ensure correct ordering""" - test_graph, _ = instantiate_graph("test_basic_graph") - roots = test_graph.construct_graph() - assert len(roots) == 1 - roots = list(roots) - targets = [("encoder_0", 1), ("mlp_0", 1), ("mlp_1", 0)] - check_consistency(roots[0], targets) - - -def test_construct_graph_repeat(): - """test construction of dependency graph: ensure duplicate nodes are ok""" - test_graph, cfg = instantiate_graph("test_repeat_graph") - roots = test_graph.construct_graph() - assert len(roots) == 1 - roots = list(roots) - targets = [("encoder_0", 1), ("mlp_0", 1), ("mlp_1", 0)] - check_consistency(roots[0], targets) - - with open_dict(cfg): - cfg.network.mlp_0.inputs[1] = "encoder_1" - cfg.network.encoder_1 = { - "class_name": "ScalingAndOffset", - "inputs": ["x"], - "meta_data": {"in_dim": 8}, - } - test_graph = Graph(cfg.network) - roots = test_graph.construct_graph() - assert len(roots) == 2 - - -def test_construct_graph_complex(): - """test construction of dependency graph: ensure different depths are ok""" - test_graph, _ = instantiate_graph("test_complex_graph") - roots = test_graph.construct_graph() - assert len(roots) == 1 - roots = list(roots) - targets_p0 = [("encoder_0", 3), ("mlp_0", 2), ("mlp_3", 0)] - check_consistency(roots[0], targets_p0) - - targets_p1 = [("encoder_0", 3), ("mlp_0", 2), ("mlp_2", 0)] - check_consistency(roots[0], targets_p1) - - targets_p2 = [("encoder_0", 3), ("mlp_1", 0)] - check_consistency(roots[0], targets_p2) - - targets_p3 = [("encoder_0", 3), ("mlp_2", 0)] - check_consistency(roots[0], targets_p3) - - -def test_ordering(): - """test dependency ordering of constructed graph""" - test_basic_graph, _ = instantiate_graph("test_basic_graph") - _ = test_basic_graph.construct_graph() - order = test_basic_graph.module_order - target = ["encoder_0", "mlp_0", "mlp_1"] - assert np.array_equal(target, order) - - test_repeated_graph, cfg = instantiate_graph("test_repeat_graph") - _ = test_repeated_graph.construct_graph() - order = test_repeated_graph.module_order - target = ["encoder_0", "mlp_0", "mlp_1"] - assert np.array_equal(target, order) - - with open_dict(cfg): - cfg.network.mlp_0.inputs[1] = "encoder_1" - cfg.network.encoder_1 = { - "class_name": "ScalingAndOffset", - "inputs": ["x"], - "meta_data": {"in_dim": 16}, - } - test_repeated_graph = Graph(cfg.network) - order = test_repeated_graph.module_order - assert order.index("mlp_0") > order.index("encoder_0") and order.index("mlp_0") > order.index("encoder_1") - - test_complex_graph, _ = instantiate_graph("test_complex_graph") - _ = test_complex_graph.construct_graph() - order = test_complex_graph.module_order - assert order.index("mlp_2") > order.index("mlp_0") - assert order.index("mlp_2") > order.index("encoder_0") - assert order.index("mlp_3") > order.index("encoder_0") diff --git a/tests/nerf/test_renderers.py b/tests/nerf/test_renderers.py index e6897dad9..7e2cd8c95 100644 --- a/tests/nerf/test_renderers.py +++ b/tests/nerf/test_renderers.py @@ -9,29 +9,24 @@ from mattport.nerf import renderers def test_rgb_renderer(): """Test RGB volumetric rendering""" - rgb_name = "rgb" - density_name = "density" num_samples = 10 rgb = torch.ones((3, num_samples, 3)) densities = torch.ones((3, num_samples, 1)) deltas = torch.ones((3, num_samples)) - rgb_renderer = renderers.RGB(rgb_name, density_name) + rgb_renderer = renderers.RGBRenderer() assert rgb_renderer.required_field_outputs is not None - field_output_dict = {rgb_name: rgb, density_name: densities} - out = rgb_renderer(field_output_dict, deltas) - assert torch.max(out) > 0.9 + out = rgb_renderer(rgb=rgb, density=densities, deltas=deltas) + assert torch.max(out.rgb) > 0.9 - field_output_dict = {rgb_name: rgb * 0, density_name: densities} - out = rgb_renderer(field_output_dict, deltas) - assert torch.max(out) == pytest.approx(0) + out = rgb_renderer(rgb=rgb * 0, density=densities, deltas=deltas) + assert torch.max(out.rgb) == pytest.approx(0) - field_output_dict = {rgb_name: rgb, density_name: densities * 0} - out = rgb_renderer(field_output_dict, deltas) - assert torch.max(out) == pytest.approx(0) + out = rgb_renderer(rgb=rgb, density=densities * 0, deltas=deltas) + assert torch.max(out.rgb) == pytest.approx(0) # TODO Tancik: Add more precise tests diff --git a/tests/nerf/test_sampler.py b/tests/nerf/test_sampler.py new file mode 100644 index 000000000..bda6d2785 --- /dev/null +++ b/tests/nerf/test_sampler.py @@ -0,0 +1,52 @@ +""" +Test samplers +""" +import torch +from mattport.nerf.sampler import PDFSampler, UniformSampler + +from mattport.structures.rays import RayBundle + + +def test_uniform_sampler(): + """Test uniform sampler""" + near_plane = 2 + far_plane = 4 + num_samples = 15 + sampler = UniformSampler(near_plane=near_plane, far_plane=far_plane, num_samples=num_samples) + + origins = torch.zeros((10, 3)) + directions = torch.ones_like(origins) + ray_bundle = RayBundle(origins=origins, directions=directions) + + ray_samples = sampler(ray_bundle) + + assert ray_samples.bins.shape[-1] == num_samples + 1 + + # TODO Tancik: Add more precise tests + + +def test_pdf_sampler(): + """Test pdf sampler""" + near_plane = 2 + far_plane = 4 + num_samples = 15 + + origins = torch.zeros((10, 3)) + directions = torch.ones_like(origins) + ray_bundle = RayBundle(origins=origins, directions=directions) + + density = torch.ones((10, num_samples, 1)) + + uniform_sampler = UniformSampler(near_plane=near_plane, far_plane=far_plane, num_samples=num_samples) + coarse_ray_samples = uniform_sampler(ray_bundle) + + # Just check that it doesn't crash. Need to add some actual tests. + pdf_sampler = PDFSampler(num_samples) + pdf_sampler(ray_bundle, coarse_ray_samples, density, num_samples) + + # TODO Tancik: Add more precise tests + + +if __name__ == "__main__": + test_uniform_sampler() + test_pdf_sampler()