pylint and test cases for dataloader

This commit is contained in:
Ethan Weber committed 2022-04-23 19:45:53 +00:00
1 parent 391803759e
commit 80ad17700c
10 files changed
+94 -69

No files matched your search

+7 -2
View File
@@ -2,14 +2,15 @@
Classes to help with caching data while training.
"""
from typing import Callable
import torch
import random
from typing import Callable
import torch
from torch.utils.data import default_collate
def collate_batch_size_one(batch_list):
"""Use the default collate function but then squeze to avoid the batch dimension being added."""
assert len(batch_list) == 1
collated_batch = default_collate(batch_list)
for key in collated_batch:
@@ -41,7 +42,11 @@ class CollateIterDataset(torch.utils.data.IterableDataset):
self.num_repeated = self.num_times_to_repeat # starting value
self.cached_batch_list = None
def __getitem__(self, idx):
return self.dataset.__getitem__(idx)
def get_batch_list(self):
"""Returns a list of batches from the dataset attribute."""
# sampling without replacement. TODO(ethan): don't use 'random'
indices = random.sample(range(len(self.dataset)), k=self.num_samples_to_collate)
batch_list = [self.dataset.__getitem__(idx) for idx in indices]
+3 -1
View File
@@ -32,9 +32,11 @@ def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False)
assert pixels.shape == (num_rays_per_batch, 3), pixels.shape
# Needed to correct the random indices to their actual camera idx locations.
local_indices = indices.clone()
indices[:, 0] = batch["image_idx"][c]
collated_batch = {
"indices": indices,
"local_indices": local_indices, # local to the batch returned
"indices": indices, # with the abs camera indices
"pixels": pixels,
"mask": mask,
}
+2 -3
View File
@@ -1,8 +1,7 @@
"""
Multi Layer Perceptron
"""
from tkinter import X
from typing import List, Optional
from typing import Tuple, Optional
import torch
from torch import nn
@@ -20,7 +19,7 @@ class MLP(FieldModule):
out_dim: int,
num_layers: int,
layer_width: int = None,
skip_connections: List[int] = [],
skip_connections: Tuple[int] = (),
activation: Optional[nn.Module] = nn.ReLU(),
out_activation: Optional[nn.Module] = None,
) -> None:
+1 -1
View File
@@ -34,7 +34,7 @@ class Node:
class Graph(nn.Module):
"""_summary_"""
def __init__(self, intrinsics=None, camera_to_world=None, **kwargs) -> None:
def __init__(self, intrinsics=None, camera_to_world=None) -> None:
super().__init__()
self.intrinsics = intrinsics
self.camera_to_world = camera_to_world
+4 -3
View File
@@ -3,7 +3,7 @@ Implementation of vanilla nerf.
"""
from typing import Dict, List
from typing import Dict, List, Tuple
import torch
from torch import nn
@@ -17,14 +17,14 @@ 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 PDFSampler, UniformSampler
from mattport.nerf.sampler import PDFSampler, UniformSampler # pylint: disable=unused-import
from mattport.structures.rays import RaySamples
class NeRFField(nn.Module):
"""NeRF module"""
def __init__(self, num_layers=8, layer_width=256, skip_connections=[4]) -> None:
def __init__(self, num_layers=8, layer_width=256, skip_connections: Tuple = (4)) -> None:
super().__init__()
self.num_layers = num_layers
self.layer_width = layer_width
@@ -99,6 +99,7 @@ class NeRFGraph(Graph):
self.sampler_uniform = UniformSampler(
near_plane=self.near_plane, far_plane=self.far_plane, num_samples=self.num_coarse_samples
)
# TODO: this needs to be corrected
# self.sampler_pdf = PDFSampler(num_samples=self.num_importance_samples)
self.sampler_pdf = UniformSampler(
near_plane=self.near_plane, far_plane=self.far_plane, num_samples=self.num_importance_samples
+3 -4
View File
@@ -56,11 +56,10 @@ class Optimizers:
def optimizer_step_all(self):
"""Run step for all optimizers."""
# logging.info("optimizer_step_all")
for param_name, optimizer in self.optimizers.items():
for _, optimizer in self.optimizers.items():
# note that they key is the parameter name
optimizer.step()
def scheduler_step_all(self, step):
"""Run step for all schedulers."""
# logging.info("optimizer_step_all")
pass
# TODO: this needs to be implemented
+7 -9
View File
@@ -5,6 +5,7 @@ import datetime
import logging
import os
from time import time
from typing import Dict
import torch
import torch.distributed as dist
@@ -32,6 +33,7 @@ class Trainer:
self.local_rank = local_rank
self.world_size = world_size
# dataset variables
self.train_image_dataset = None
self.train_dataset = None
self.train_dataloader = None
self.test_dataset = None
@@ -66,7 +68,7 @@ class Trainer:
self.train_dataset,
batch_size=1,
num_workers=self.config.dataloader.num_workers,
collate_fn=lambda batch_list: collate_batch_size_one(batch_list),
collate_fn=collate_batch_size_one,
pin_memory=True,
)
# TODO(ethan): implement the test dataset
@@ -160,14 +162,10 @@ class Trainer:
mssg += f"{k}: {v} | "
print(mssg, end="\r")
def get_aggregated_loss(self, losses):
"""_summary_
Args:
losses (_type_): _description_
Returns:
_type_: _description_
@classmethod
def get_aggregated_loss(cls, losses: Dict[str, torch.tensor]):
"""Returns the aggregated losses and the scalar for calling .backwards() on.
# TODO: move this out to another file/class/etc.
"""
loss_sum = 0.0
loss_dict = {}
+5
View File
@@ -1,3 +1,8 @@
"""
Miscellaneous helper code.
"""
class DotDict(dict):
"""
dot.notation access to dictionary attributes