added caching for dataloader

This commit is contained in:
Ethan Weber committed 2022-04-23 17:36:57 +00:00
1 parent 5f1baa5a7b
commit 4c7d07116e
5 files changed
+134 -56

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
"""
Classes to help with caching data while training.
"""
from typing import Callable
import torch
import random
from torch.utils.data import default_collate
def collate_batch_size_one(batch_list):
assert len(batch_list) == 1
collated_batch = default_collate(batch_list)
for key in collated_batch:
assert collated_batch[key].shape[0] == 1
collated_batch[key] = collated_batch[key].squeeze(0)
return collated_batch
class CollateIterDataset(torch.utils.data.IterableDataset):
"""Collated image dataset that implements caching of images.
Args:
torch (_type_): _description_
"""
def __init__(
self,
dataset: torch.utils.data.Dataset,
collate_fn: Callable,
num_samples_to_collate: int,
num_times_to_repeat: int = 0,
):
super().__init__()
self.dataset = dataset
self.collate_fn = collate_fn
self.num_samples_to_collate = num_samples_to_collate
self.num_times_to_repeat = num_times_to_repeat
self.num_repeated = self.num_times_to_repeat # starting value
self.cached_batch_list = None
def get_batch_list(self):
# 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]
return batch_list
def __iter__(self):
while True:
if self.num_repeated >= self.num_times_to_repeat:
# trigger a reset
self.num_repeated = 0
batch_list = self.get_batch_list()
# possibly save a cached item
self.cached_batch_list = batch_list if self.num_times_to_repeat != 0 else None
else:
batch_list = self.cached_batch_list
self.num_repeated += 1
collated_batch = self.collate_fn(batch_list)
yield collated_batch
+34 -38
View File
@@ -10,7 +10,38 @@ import PIL
from PIL import Image
from torch.utils.data import default_collate
from mattport.utils.misc import DotDict
def collate_batch(batch_list, num_rays_per_batch, keep_full_image: bool = False):
"""_summary_
Args:
batch (_type_): _description_
"""
# TODO(ethan): handle sampling even when in different processes
# we don't want the same samples for all spawned processed when
# using distributed training
batch = default_collate(batch_list)
num_images, image_height, image_width, _ = batch["image"].shape
indices = torch.floor(
torch.rand((num_rays_per_batch, 3)) * torch.tensor([num_images, image_height, image_width])
).long()
c, y, x = [i.flatten() for i in torch.split(indices, 1, dim=-1)]
pixels = batch["image"][c, y, x]
mask = batch["mask"][c, y, x]
assert pixels.shape == (num_rays_per_batch, 3), pixels.shape
# Needed to correct the random indices to their actual camera idx locations.
indices[:, 0] = batch["image_idx"][c]
collated_batch = {
"indices": indices,
"pixels": pixels,
"mask": mask,
}
if keep_full_image:
collated_batch["image"] = batch["image"]
return collated_batch
class ImageDataset(torch.utils.data.Dataset):
@@ -55,9 +86,6 @@ class ImageDataset(torch.utils.data.Dataset):
return image
def __getitem__(self, image_idx):
# TODO(ethan): we should add code to deal with varying resolution and/or having a maximum pixel resolution
# e.g., we should be able to downscale the images or set a max height, width, etc.
# the image might be RGB or RGBA, so we separate it
original_image = torch.from_numpy(self.get_image(image_idx).astype("float32") / 255.0)
image = original_image[:, :, :3]
@@ -69,41 +97,9 @@ class ImageDataset(torch.utils.data.Dataset):
else:
raise ValueError(f"Image shape of {image.shape} is in correct.")
return {
data = {
"image_idx": image_idx,
"image": image, # the pixels
"mask": mask,
}
def collate_batch(batch, num_rays_per_batch, keep_full_image: bool = False):
"""_summary_
Args:
batch (_type_): _description_
"""
# TODO(ethan): handle sampling even when in different processes
# we don't want the same samples for all spawned processed when
# using distributed training
batch = default_collate(batch)
num_images, image_height, image_width, _ = batch["image"].shape
indices = torch.floor(
torch.rand((num_rays_per_batch, 3)) * torch.tensor([num_images, image_height, image_width])
).long()
c, y, x = [i.flatten() for i in torch.split(indices, 1, dim=-1)]
pixels = batch["image"][c, y, x]
mask = batch["mask"][c, y, x]
assert pixels.shape == (num_rays_per_batch, 3), pixels.shape
indices[:, 0] = batch["image_idx"][c]
collated_batch = {
"indices": indices,
"pixels": pixels,
"mask": mask,
}
if keep_full_image:
collated_batch["image"] = batch["image"]
return DotDict(collated_batch)
return data