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

simplify list_data_collate and collate_meta_tensor #7165

Merged
merged 9 commits into from
Oct 26, 2023
Merged
Changes from 4 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
39 changes: 28 additions & 11 deletions monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@
issequenceiterable,
look_up_option,
optional_import,
pytorch_after,
)

if pytorch_after(1, 13):
from torch.utils.data._utils.collate import collate_tensor_fn, default_collate_fn_map
wyli marked this conversation as resolved.
Show resolved Hide resolved
pd, _ = optional_import("pandas")
DataFrame, _ = optional_import("pandas", name="DataFrame")
nib, _ = optional_import("nibabel")
Expand Down Expand Up @@ -444,22 +447,30 @@ def pickle_operations(data, key=PICKLE_KEY_SUFFIX, is_encode: bool = True):
return data


def collate_meta_tensor_fn(batch, *, collate_fn_map=None):
"""
Collate a sequence of meta tensor into a single batched metatensor. This is called by `collage_meta_tensor` and so should not be used as a collate function directly in dataloaders.
"""
collate_fn = collate_tensor_fn if pytorch_after(1, 13) else default_collate
collated = collate_fn(batch) # type: ignore
meta_dicts = [i.meta or TraceKeys.NONE for i in batch]
common_ = set.intersection(*[set(d.keys()) for d in meta_dicts if isinstance(d, dict)])
if common_:
meta_dicts = [{k: d[k] for k in common_} if isinstance(d, dict) else TraceKeys.NONE for d in meta_dicts]
collated.meta = default_collate(meta_dicts)
collated.applied_operations = [i.applied_operations or TraceKeys.NONE for i in batch]
collated.is_batch = True
return collated


def collate_meta_tensor(batch):
"""collate a sequence of meta tensor sequences/dictionaries into
a single batched metatensor or a dictionary of batched metatensor"""
if not isinstance(batch, Sequence):
raise NotImplementedError()
elem_0 = first(batch)
if isinstance(elem_0, MetaObj):
collated = default_collate(batch)
meta_dicts = [i.meta or TraceKeys.NONE for i in batch]
common_ = set.intersection(*[set(d.keys()) for d in meta_dicts if isinstance(d, dict)])
if common_:
meta_dicts = [{k: d[k] for k in common_} if isinstance(d, dict) else TraceKeys.NONE for d in meta_dicts]
collated.meta = default_collate(meta_dicts)
collated.applied_operations = [i.applied_operations or TraceKeys.NONE for i in batch]
collated.is_batch = True
return collated
return collate_meta_tensor_fn(batch)
if isinstance(elem_0, Mapping):
return {k: collate_meta_tensor([d[k] for d in batch]) for k in elem_0}
if isinstance(elem_0, (tuple, list)):
Expand All @@ -479,9 +490,15 @@ def list_data_collate(batch: Sequence):
Need to use this collate if apply some transforms that can generate batch data.

"""

if pytorch_after(1, 13):
wyli marked this conversation as resolved.
Show resolved Hide resolved
from monai.data.meta_tensor import MetaTensor

default_collate_fn_map.update({MetaTensor: collate_meta_tensor_fn})
elem = batch[0]
data = [i for k in batch for i in k] if isinstance(elem, list) else batch
key = None
collate_fn = default_collate if pytorch_after(1, 13) else collate_meta_tensor
try:
if config.USE_META_DICT:
data = pickle_operations(data) # bc 0.9.0
Expand All @@ -490,9 +507,9 @@ def list_data_collate(batch: Sequence):
for k in elem:
key = k
data_for_batch = [d[key] for d in data]
ret[key] = collate_meta_tensor(data_for_batch)
ret[key] = collate_fn(data_for_batch)
else:
ret = collate_meta_tensor(data)
ret = collate_fn(data)
return ret
except RuntimeError as re:
re_str = str(re)
Expand Down
Loading