MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / copy_to_device

Function copy_to_device

monai/utils/misc.py:425–456  ·  view source on GitHub ↗

Copy object or tuple/list/dictionary of objects to ``device``. Args: obj: object or tuple/list/dictionary of objects to move to ``device``. device: move ``obj`` to this device. Can be a string (e.g., ``cpu``, ``cuda``, ``cuda:0``, etc.) or of type ``torch.device

(
    obj: Any, device: str | torch.device | None, non_blocking: bool = True, verbose: bool = False
)

Source from the content-addressed store, hash-verified

423
424
425def copy_to_device(
426 obj: Any, device: str | torch.device | None, non_blocking: bool = True, verbose: bool = False
427) -> Any:
428 """
429 Copy object or tuple/list/dictionary of objects to ``device``.
430
431 Args:
432 obj: object or tuple/list/dictionary of objects to move to ``device``.
433 device: move ``obj`` to this device. Can be a string (e.g., ``cpu``, ``cuda``,
434 ``cuda:0``, etc.) or of type ``torch.device``.
435 non_blocking: when `True`, moves data to device asynchronously if
436 possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.
437 verbose: when `True`, will print a warning for any elements of incompatible type
438 not copied to ``device``.
439 Returns:
440 Same as input, copied to ``device`` where possible. Original input will be
441 unchanged.
442 """
443
444 if hasattr(obj, "to"):
445 return obj.to(device, non_blocking=non_blocking)
446 if isinstance(obj, tuple):
447 return tuple(copy_to_device(o, device, non_blocking) for o in obj)
448 if isinstance(obj, list):
449 return [copy_to_device(o, device, non_blocking) for o in obj]
450 if isinstance(obj, dict):
451 return {k: copy_to_device(o, device, non_blocking) for k, o in obj.items()}
452 if verbose:
453 fn_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name
454 warnings.warn(f"{fn_name} called with incompatible type: " + f"{type(obj)}. Data will be returned unchanged.")
455
456 return obj
457
458
459def str2bool(value: str | bool, default: bool = False, raise_exc: bool = True) -> bool:

Callers 2

_train_batchMethod · 0.90
_validateMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…