Config restructure (#283)

* starting docs for pipelines

* working on an example

* clearing output

* starting to implement config changes and add documentation

* wip: removed cicular imports; porting basic config into python; todo: get python setups workin

* circular imports again

* wip: pausing at dataloader sort of working

* break for today

* running vanilla

* wip need to get all the config docs working

* laptop about to die

* instant ngp working

* added all configs for all methods; not tested yet: [mipnerf360, nerfw, semantic_nerf]

* unpacking later

* done with pylinting

* mostly done. just need to do docs and one test

* added import order to docs

* fixing near/far plane and other config things

* making loggers also instantiable via configs

* docs

* lint

* making --help work with dcargs

* moving configs back into flat

* convert list to tuples; fixed post init function with mutable params

* lint

* made run_eval and benchmarking scripts compatible with new config/dcargs

* lint

* added option to load configs from presaved config

Co-authored-by: evonneng <evonne_ng@berkeley.edu>
This commit is contained in:
Ethan Weberandevonneng authored and GitHub committed 2022-08-26 17:25:10 -07:00
1 parent e0856e3afc
commit 7e9a56fac4
46 files changed
+987 -916

No files matched your search

-161
View File
@@ -1,161 +0,0 @@
# 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.
"""Structured config classes"""
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from omegaconf import MISSING, DictConfig
@dataclass
class MachineConfig:
"""Configuration of machine setup"""
seed: int = MISSING
num_gpus: int = MISSING
num_machines: int = MISSING
machine_rank: int = MISSING
dist_url: str = MISSING
@dataclass
class LoggingConfig:
"""Configuration of loggers and profilers"""
steps_per_log: int = MISSING
max_buffer_size: int = MISSING
writer: Dict[str, Any] = MISSING
enable_profiler: bool = MISSING
@dataclass
class ResumeTrainConfig:
"""Configuration for loading previous checkpoints"""
load_dir: Optional[str] = None
load_step: Optional[int] = None
@dataclass
class TrainerConfig:
"""Configuration for training regimen"""
model_dir: str = MISSING
steps_per_save: int = MISSING
steps_per_test: int = MISSING
max_num_iterations: int = MISSING
mixed_precision: bool = MISSING
resume_train: ResumeTrainConfig = MISSING
@dataclass
class DataloaderConfig:
"""Configuration for train/eval datasets"""
_target_: str = MISSING
image_dataset_type: Optional[str] = "rgb"
train_dataset: Dict[str, Any] = MISSING
train_num_rays_per_batch: int = MISSING
train_num_images_to_sample_from: int = MISSING
eval_dataset: Optional[Dict[str, Any]] = None
eval_image_indices: Optional[List[int]] = None
eval_num_rays_per_chunk: int = MISSING
@dataclass
class ModelConfig:
"""Configuration for graph instantiation"""
_target_: str = MISSING
enable_collider: Optional[bool] = True
collider_config: Dict[str, Any] = MISSING
num_coarse_samples: int = MISSING
num_importance_samples: int = MISSING
loss_coefficients: Dict[str, Any] = MISSING
# additional optional parameters here
field_implementation: Optional[str] = "torch"
enable_density_field: Optional[bool] = False
density_field_config: Dict[str, Any] = MISSING
@dataclass
class PipelineConfig:
"""Configuration for pipeline instantiation"""
_target_: str = MISSING
dataloader: DataloaderConfig = MISSING
model: ModelConfig = MISSING
@dataclass
class ViewerConfig:
"""Configuration for viewer instantiation"""
enable: bool = MISSING
zmq_url: str = MISSING
min_render_image_height: int = MISSING
max_render_image_height: int = MISSING
num_rays_per_chunk: int = MISSING
@dataclass
class Config:
"""Full config contents"""
machine: MachineConfig = MISSING
logging: LoggingConfig = MISSING
trainer: TrainerConfig = MISSING
experiment_name: str = MISSING
method_name: str = MISSING
optimizers: Dict[str, Any] = MISSING
viewer: ViewerConfig = MISSING
pipeline: PipelineConfig = MISSING
# additional optional parameters here
hydra: Optional[Dict[str, Any]] = None
def setup_config(config: DictConfig) -> Config:
"""helper that creates a typed config from the DictConfig
Args:
config (DictConfig): configuration to convert
Returns:
Config: typed version of the input configuration
"""
machine = MachineConfig(**config.machine)
logging = LoggingConfig(**config.logging)
trainer = TrainerConfig(**config.trainer)
experiment_name = config.experiment_name
method_name = config.method_name
dataloader = DataloaderConfig(**config.pipeline.dataloader)
model = ModelConfig(**config.pipeline.model)
pipeline = PipelineConfig(
_target_=config.pipeline._target_, dataloader=dataloader, model=model # pylint:disable=protected-access
)
optimizers = config.optimizers
viewer = ViewerConfig(**config.viewer)
return Config(
machine=machine,
logging=logging,
trainer=trainer,
experiment_name=experiment_name,
method_name=method_name,
pipeline=pipeline,
optimizers=optimizers,
viewer=viewer,
)
+1 -32
View File
@@ -19,23 +19,9 @@ Miscellaneous helper code.
import hashlib
import json
from math import floor, log
from pydoc import locate
from typing import Any, Callable, Dict, Union
import torch
from omegaconf import DictConfig
class DotDict(dict):
"""
dot.notation access to dictionary attributes
"""
def __getattr__(self, attr):
return self[attr]
__setattr__ = dict.__setitem__ # type: ignore
__delattr__ = dict.__delitem__ # type: ignore
def get_dict_to_torch(stuff, device: Union[torch.device, str] = "cpu"):
@@ -74,23 +60,6 @@ def get_masked_dict(d, mask):
return masked_dict
def instantiate_from_dict_config(dict_config: Any, **kwargs):
"""Our version of hydra's instantiate function.
Args:
dict_config: DictConfig object to instantiate. It can be a dataclass or a dict but must have a `_target_` field.
"""
dict_config_kwargs = {k: v for k, v in dict_config.items() if k != "_target_"}
uninstantiated_class = locate(dict_config._target_) # pylint: disable=protected-access
assert (
uninstantiated_class is not None
), f"Could not find class {dict_config._target_}" # pylint: disable=protected-access
all_kwargs = dict_config_kwargs
all_kwargs.update(kwargs)
instantiated_class = uninstantiated_class(**all_kwargs) # type: ignore
return instantiated_class
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"""
@@ -150,7 +119,7 @@ def human_format(num):
return f"{(num / k**magnitude):.2f} {units[magnitude]}"
def scale_dict(dictionary: Dict[Any, Any], coefficients: DictConfig) -> Dict[Any, Any]:
def scale_dict(dictionary: Dict[Any, Any], coefficients: Dict[str, float]) -> Dict[Any, Any]:
"""Scale a dictionary in-place given a coefficients dictionary.
Args:
+6 -4
View File
@@ -15,12 +15,14 @@
"""
Profiler base class and functionality
"""
from __future__ import annotations
import logging
import time
from typing import Callable
from nerfactory.configs import base as cfg
from nerfactory.utils import comms
from nerfactory.utils.config import LoggingConfig
from nerfactory.utils.decorators import (
check_main_thread,
check_profiler_enabled,
@@ -44,13 +46,13 @@ def time_function(func: Callable) -> Callable:
return wrapper
def flush_profiler(config: LoggingConfig):
def flush_profiler(config: cfg.LoggingConfig):
"""Method that checks if profiler is enabled before flushing"""
if config.enable_profiler and PROFILER:
PROFILER[0].print_profile()
def setup_profiler(config: LoggingConfig):
def setup_profiler(config: cfg.LoggingConfig):
"""Initialization of profilers"""
if comms.is_main_process():
PROFILER.append(Profiler(config))
@@ -60,7 +62,7 @@ def setup_profiler(config: LoggingConfig):
class Profiler:
"""Profiler class"""
def __init__(self, config: LoggingConfig):
def __init__(self, config: cfg.LoggingConfig):
self.config = config
self.profiler_dict = {}
+24 -28
View File
@@ -15,24 +15,23 @@
"""
Generic Writer class
"""
from __future__ import annotations
import enum
import os
import sys
import logging
from abc import abstractmethod
from pathlib import Path
from time import time
from typing import Dict
from typing import Dict, Optional
import imageio
import numpy as np
import torch
import wandb
from omegaconf import ListConfig
from torch.utils.tensorboard import SummaryWriter
from torchtyping import TensorType
from nerfactory.utils.config import LoggingConfig
from nerfactory.configs import base as cfg
from nerfactory.utils.decorators import check_main_thread, decorate_all
from nerfactory.utils.misc import human_format
@@ -138,16 +137,13 @@ def write_out_storage():
@check_main_thread
def setup_event_writers(config: LoggingConfig, max_iter: int) -> None:
def setup_event_writers(config: cfg.LoggingConfig, max_iter: int) -> None:
"""Initialization of all event writers specified in config"""
for writer_type in config.writer:
writer_class = getattr(sys.modules[__name__], writer_type)
writer_config = config.writer[writer_type]
if writer_type == "LocalWriter":
curr_writer = writer_class(writer_config.log_dir, writer_config.stats_to_track, writer_config.max_log_size)
else:
curr_writer = writer_class(writer_config.log_dir)
EVENT_WRITERS.append(curr_writer)
for writer_type_config in config.writer:
if writer_type_config.enable:
curr_writer = writer_type_config.setup()
EVENT_WRITERS.append(curr_writer)
logging.info("logging info to: %s", writer_type_config.log_dir)
## configure all the global buffer basic information
GLOBAL_BUFFER["max_iter"] = max_iter
@@ -159,7 +155,7 @@ def setup_event_writers(config: LoggingConfig, max_iter: int) -> None:
class Writer:
"""Writer class"""
def __init__(self, log_dir: str):
def __init__(self, log_dir: Optional[Path]):
self.log_dir = log_dir
@abstractmethod
@@ -228,9 +224,9 @@ class TimeWriter:
class WandbWriter(Writer):
"""WandDB Writer Class"""
def __init__(self, log_dir: str):
super().__init__(log_dir)
wandb.init(dir=log_dir)
def __init__(self, config: cfg.WandbWriterConfig):
super().__init__(config.log_dir)
wandb.init(dir=config.log_dir)
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
"""_summary_
@@ -256,9 +252,9 @@ class WandbWriter(Writer):
class TensorboardWriter(Writer):
"""Tensorboard Writer Class"""
def __init__(self, log_dir: str):
super().__init__(log_dir)
self.tb_writer = SummaryWriter(log_dir=self.log_dir)
def __init__(self, config: cfg.TensorboardWriterConfig):
super().__init__(config.log_dir)
self.tb_writer = SummaryWriter(log_dir=config.log_dir)
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
"""_summary_
@@ -313,23 +309,23 @@ def _format_time(seconds):
class LocalWriter(Writer):
"""Local Writer Class"""
def __init__(self, log_dir: str, stats_to_track: ListConfig, max_log_size: int = 0):
def __init__(self, config: cfg.LocalWriterConfig):
"""
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__(log_dir)
self.stats_to_track = [EventName[name].value for name in stats_to_track]
self.max_log_size = max_log_size
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
self.keys = set()
self.past_mssgs = ["", ""]
self.has_printed = False
def write_image(self, name: str, image: TensorType["H", "W", "C"], step: int) -> None:
if name in self.stats_to_track:
if name in self.stats_to_track and self.log_dir:
image = to8b(image)
image_path = os.path.join(self.log_dir, f"{name}.jpg")
image_path = self.log_dir / f"{name}.jpg"
imageio.imwrite(image_path, np.uint8(image.cpu().numpy() * 255.0))
def write_scalar(self, name: str, scalar: float, step: int) -> None: