[wip] dynamic batch size for instant ngp (#501)

* starting dynamic batch size branch

* dynamic batch pipeline code
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-09-21 14:07:04 -07:00
1 parent 0c43e7c4b2
commit 7b5a251a30
19 files changed
+351 -221

No files matched your search

+34 -14
View File
@@ -19,8 +19,9 @@ from __future__ import annotations
import typing
from abc import abstractmethod
from dataclasses import dataclass, field
from time import time
from typing import Any, Dict, List, Optional, Union, cast
from typing import Any, Dict, List, Optional, Type, Union, cast
import torch
import torch.distributed as dist
@@ -35,9 +36,14 @@ from torch import nn
from torch.nn import Parameter
from torch.nn.parallel import DistributedDataParallel as DDP
# from nerfactory.configs.base import InstantiateConfig
from nerfactory.configs import base as cfg
from nerfactory.datamanagers.base import DataManager, VanillaDataManager
from nerfactory.models.base import Model
from nerfactory.datamanagers.base import (
DataManager,
VanillaDataManager,
VanillaDataManagerConfig,
)
from nerfactory.models.base import Model, ModelConfig
from nerfactory.utils import profiler
from nerfactory.utils.callbacks import TrainingCallback, TrainingCallbackAttributes
@@ -81,7 +87,9 @@ class Pipeline(nn.Module):
self.model: The model that will be used
"""
datamanager: DataManager
# pylint: disable=abstract-method
datamanger: DataManager
model: Model
@property
@@ -142,10 +150,6 @@ class Pipeline(nn.Module):
def get_average_eval_image_metrics(self, step: Optional[int] = None):
"""Iterate over all the images in the eval dataset and get the average."""
@abstractmethod
def log_test_image_outputs(self) -> None:
"""Log the test image outputs"""
def load_pipeline(self, loaded_state: Dict[str, Any]) -> None:
"""Load the checkpoint from the given path
@@ -166,6 +170,18 @@ class Pipeline(nn.Module):
"""
@dataclass
class VanillaPipelineConfig(cfg.InstantiateConfig):
"""Configuration for pipeline instantiation"""
_target: Type = field(default_factory=lambda: VanillaPipeline)
"""target class to instantiate"""
datamanager: VanillaDataManagerConfig = VanillaDataManagerConfig()
"""specifies the datamanager config"""
model: ModelConfig = ModelConfig()
"""specifies the model config"""
class VanillaPipeline(Pipeline):
"""The pipeline class for the vanilla nerf setup of multiple cameras for one or a few scenes.
@@ -182,20 +198,21 @@ class VanillaPipeline(Pipeline):
def __init__(
self,
config: cfg.VanillaPipelineConfig,
config: VanillaPipelineConfig,
device: str,
test_mode: bool = False,
world_size: int = 1,
local_rank: int = 0,
):
super().__init__()
self.config = config
self.datamanager: VanillaDataManager = config.datamanager.setup(
device=device, test_mode=test_mode, world_size=world_size, local_rank=local_rank
)
self.datamanager.to(device)
# TODO(ethan): get rid of scene_bounds from the model
assert self.datamanager.train_input_dataset is not None, "Missing input dataset"
self.model: Model = config.model.setup(
self.model = config.model.setup(
scene_bounds=self.datamanager.train_input_dataset.dataset_inputs.scene_bounds,
num_train_data=len(self.datamanager.train_input_dataset),
)
@@ -213,7 +230,6 @@ class VanillaPipeline(Pipeline):
"""Returns the device that the model is on."""
return module_wrapper(self.model).device
@abstractmethod
@profiler.time_function
def get_train_loss_dict(self, step: int):
"""This function gets your training loss dict. This will be responsible for
@@ -230,7 +246,13 @@ class VanillaPipeline(Pipeline):
return model_outputs, loss_dict, metrics_dict
@abstractmethod
def forward(self):
"""Blank forward method
This is an nn.Module, and so requires a forward() method normally, although in our case
we do not need a forward() method"""
raise NotImplementedError
@profiler.time_function
def get_eval_loss_dict(self, step: int):
"""This function gets your evaluation loss dict. It needs to get the data
@@ -247,7 +269,6 @@ class VanillaPipeline(Pipeline):
self.train()
return model_outputs, loss_dict, metrics_dict
@abstractmethod
@profiler.time_function
def get_eval_image_metrics_and_images(self, step: int):
"""This function gets your evaluation loss dict. It needs to get the data
@@ -267,7 +288,6 @@ class VanillaPipeline(Pipeline):
self.train()
return metrics_dict, images_dict
@abstractmethod
@profiler.time_function
def get_average_eval_image_metrics(self, step: Optional[int] = None):
"""Iterate over all the images in the eval dataset and get the average.
+101
View File
@@ -0,0 +1,101 @@
# 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.
"""
A pipeline that dynamically chooses the number of rays to sample.
"""
from dataclasses import dataclass, field
from typing import Type
import torch
from nerfactory.datamanagers.base import VanillaDataManager
from nerfactory.pipelines.base import VanillaPipeline, VanillaPipelineConfig
@dataclass
class DynamicBatchPipelineConfig(VanillaPipelineConfig):
"""Dynamic Batch Pipeline Config"""
_target: Type = field(default_factory=lambda: DynamicBatchPipeline)
target_num_samples: int = 262144 # 1 << 18
"""The target number of samples to use for an entire batch of rays."""
max_num_samples_per_ray: int = 1024 # 1 << 10
"""The maximum number of samples to be placed along a ray."""
class DynamicBatchPipeline(VanillaPipeline):
"""Pipeline with logic for changing the number of rays per batch."""
# pylint: disable=abstract-method
config: DynamicBatchPipelineConfig
datamanger: VanillaDataManager
dynamic_num_rays_per_batch: int
def __init__(
self,
config: DynamicBatchPipelineConfig,
device: str,
test_mode: bool = False,
world_size: int = 1,
local_rank: int = 0,
):
super().__init__(config, device, test_mode, world_size, local_rank)
assert isinstance(
self.datamanager, VanillaDataManager
), "DynamicBatchPipeline only works with VanillaDataManager."
self.dynamic_num_rays_per_batch = self.config.target_num_samples // self.config.max_num_samples_per_ray
self._update_pixel_samplers()
def _update_pixel_samplers(self):
"""Update the pixel samplers for train and eval with the dynamic number of rays per batch."""
self.datamanager.train_pixel_sampler.set_num_rays_per_batch(self.dynamic_num_rays_per_batch)
self.datamanager.eval_pixel_sampler.set_num_rays_per_batch(self.dynamic_num_rays_per_batch)
def _update_dynamic_num_rays_per_batch(self, num_samples_per_batch: int):
"""Updates the dynamic number of rays per batch variable,
based on the total number of samples in the last batch of rays."""
self.dynamic_num_rays_per_batch = int(
self.dynamic_num_rays_per_batch * (self.config.target_num_samples / num_samples_per_batch)
)
def get_train_loss_dict(self, step: int):
model_outputs, loss_dict, metrics_dict = super().get_train_loss_dict(step)
# update the number of rays for the next step
if "num_samples_per_batch" not in metrics_dict:
raise ValueError(
"'num_samples_per_batch' is not in metrics_dict."
"Please return 'num_samples_per_batch' in the models get_metrics_dict function to use this method."
)
self._update_dynamic_num_rays_per_batch(metrics_dict["num_samples_per_batch"])
self._update_pixel_samplers()
# add the number of rays
assert "num_rays_per_batch" not in metrics_dict
metrics_dict["num_rays_per_batch"] = torch.tensor(self.datamanager.train_pixel_sampler.num_rays_per_batch)
return model_outputs, loss_dict, metrics_dict
def get_eval_loss_dict(self, step: int):
model_outputs, loss_dict, metrics_dict = super().get_eval_loss_dict(step)
# add the number of rays
assert "num_rays_per_batch" not in metrics_dict
metrics_dict["num_rays_per_batch"] = torch.tensor(self.datamanager.eval_pixel_sampler.num_rays_per_batch)
return model_outputs, loss_dict, metrics_dict