Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix max_depth recursion crash in AsynchronousLoader #191

Merged
merged 5 commits into from
Sep 11, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion pl_bolts/datamodules/async_dataloader.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from queue import Queue
from threading import Thread

import re

import torch
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from torch._six import container_abcs, string_classes, int_classes


class AsynchronousLoader(object):
Expand Down Expand Up @@ -46,6 +49,8 @@ def __init__(self, data, device=torch.device('cuda', 0), q_size=10, num_batches=

self.idx = 0

self.np_str_obj_array_pattern = re.compile(r'[SaUO]')

def load_loop(self): # The loop that will load into the queue in the background
for i, sample in enumerate(self.dataloader):
self.queue.put(self.load_instance(sample))
Expand All @@ -54,14 +59,28 @@ def load_loop(self): # The loop that will load into the queue in the background

# Recursive loading for each instance based on torch.utils.data.default_collate
def load_instance(self, sample):
elem_type = type(sample)

if torch.is_tensor(sample):
with torch.cuda.stream(self.load_stream):
# Can only do asynchronous transfer if we use pin_memory
if not sample.is_pinned():
sample = sample.pin_memory()
return sample.to(self.device, non_blocking=True)
else:
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
and elem_type.__name__ != 'string_':
if elem_type.__name__ == 'ndarray' \
and self.np_str_obj_array_pattern.search(sample.dtype.str) is not None:
return self.load_instance(sample)
return self.load_instance(torch.as_tensor(sample))
elif isinstance(sample, container_abcs.Mapping):
return {key: self.load_instance(sample[key]) for key in sample}
elif isinstance(sample, tuple) and hasattr(sample, '_fields'): # namedtuple
return elem_type(*(self.load_instance(d) for d in sample))
elif isinstance(sample, container_abcs.Sequence) and not isinstance(sample, string_classes):
return [self.load_instance(s) for s in sample]
else:
return sample

def __iter__(self):
# We don't want to run the thread more than once
Expand Down