Skip to content
Open
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
6 changes: 3 additions & 3 deletions monai/engines/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,8 @@ def __call__(
`kwargs` supports other args for `Tensor.to()` API.
"""
image, label = default_prepare_batch(batchdata, device, non_blocking, **kwargs)
args_ = list()
kwargs_ = dict()
args_ = []
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here this might make a slight improvement since this method is called a lot, but I would suggest the following would be more efficient still (You'd have to test this):

def __call__(
    self,
    batchdata: dict[str, torch.Tensor],
    device: str | torch.device | None = None,
    non_blocking: bool = False,
    **kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor, tuple, dict]:
    """
    Args `batchdata`, `device`, `non_blocking` refer to the ignite API:
    https://pytorch.org/ignite/v0.4.8/generated/ignite.engine.create_supervised_trainer.html.
    `kwargs` supports other args for `Tensor.to()` API.
    """
    image, label = default_prepare_batch(batchdata, device, non_blocking, **kwargs)
    args_ = ()
    kwargs_ = {}

    def _get_data(key: str) -> torch.Tensor:
        data = batchdata[key]

        if isinstance(data, torch.Tensor):
            data = data.to(device=device, non_blocking=non_blocking, **kwargs)

        return data

    if isinstance(self.extra_keys, (str, list, tuple)):
        args_ = tuple(_get_data(k) for k in ensure_tuple(self.extra_keys))
    elif isinstance(self.extra_keys, dict):
        kwargs_ = {k: _get_data(v) for k, v in self.extra_keys.items()}

    return cast(torch.Tensor, image), cast(torch.Tensor, label), args_, kwargs_

kwargs_ = {}

def _get_data(key: str) -> torch.Tensor:
data = batchdata[key]
Expand All @@ -235,7 +235,7 @@ def _get_data(key: str) -> torch.Tensor:
args_.append(_get_data(k))
elif isinstance(self.extra_keys, dict):
for k, v in self.extra_keys.items():
kwargs_.update({k: _get_data(v)})
kwargs_[k] = _get_data(v)

return cast(torch.Tensor, image), cast(torch.Tensor, label), tuple(args_), kwargs_

Expand Down
Loading