Get system info as an ordered dictionary.

Return type


monai.config.deviceconfig.print_config(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print the package versions to file.


fileprint() text stream file. Defaults to sys.stdout.

monai.config.deviceconfig.print_debug_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print config (installed dependencies, etc.) and system info for debugging.


fileprint() text stream file. Defaults to sys.stdout.

Return type


monai.config.deviceconfig.print_gpu_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print GPU info to file.


fileprint() text stream file. Defaults to sys.stdout.

Return type


monai.config.deviceconfig.print_system_info(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Print system info to file. Requires the optional library, psutil.


fileprint() text stream file. Defaults to sys.stdout.

Return type


Module utils

exception monai.utils.module.InvalidPyTorchVersionError(required_version, name)[source]

Raised when called function or method requires a more recent PyTorch version than that installed.

exception monai.utils.module.OptionalImportError[source]

Could not import APIs from an optional dependency.

monai.utils.module.exact_version(the_module, version_str='')[source]

Returns True if the module’s __version__ matches version_str

Return type



Make the decorated object a member of the named module. This will also add the object under its aliases if it has a __aliases__ member, thus this decorator should be before the alias decorator to pick up those names. Alias names which conflict with package names or existing members will be ignored.

monai.utils.module.get_package_version(dep_name, default='NOT INSTALLED or UNKNOWN VERSION.')[source]

Try to load package and get version. If not found, return default.


tuple of ints represents the pytorch major/minor version.

monai.utils.module.has_option(obj, keywords)[source]

Return a boolean indicating whether the given callable obj has the keywords in its signature.

Return type


monai.utils.module.load_submodules(basemod, load_all=True, exclude_pattern='(.*[tT]est.*)|(_.*)')[source]

Traverse the source of the module structure starting with module basemod, loading all packages plus all files if load_all is True, excluding anything whose name matches exclude_pattern.

monai.utils.module.min_version(the_module, min_version_str='')[source]

Convert version strings into tuples of int and compare them.

Returns True if the module’s version is greater or equal to the ‘min_version’. When min_version_str is not provided, it always returns True.

Return type


monai.utils.module.optional_import(module, version='', version_checker=<function min_version>, name='', descriptor='{}', version_args=None, allow_namespace_pkg=False)[source]

Imports an optional module specified by module string. Any importing related exceptions will be stored, and exceptions raise lazily when attempting to use the failed-to-import module.

  • module (str) – name of the module to be imported.

  • version (str) – version string used by the version_checker.

  • version_checker (Callable[…, bool]) – a callable to check the module version, Defaults to monai.utils.min_version.

  • name (str) – a non-module attribute (such as method/class) to import from the imported module.

  • descriptor (str) – a format string for the final error message when using a not imported module.

  • version_args – additional parameters to the version checker.

  • allow_namespace_pkg (bool) – whether importing a namespace package is allowed. Defaults to False.

Return type

Tuple[Any, bool]


The imported module and a boolean flag indicating whether the import is successful.


>>> torch, flag = optional_import('torch', '1.1')
>>> print(torch, flag)
<module 'torch' from 'python/lib/python3.6/site-packages/torch/__init__.py'> True

>>> the_module, flag = optional_import('unknown_module')
>>> print(flag)
>>> the_module.method  # trying to access a module which is not imported
OptionalImportError: import unknown_module (No module named 'unknown_module').

>>> torch, flag = optional_import('torch', '42', exact_version)
>>> torch.nn  # trying to access a module for which there isn't a proper version imported
OptionalImportError: import torch (requires version '42' by 'exact_version').

>>> conv, flag = optional_import('torch.nn.functional', '1.0', name='conv1d')
>>> print(conv)
<built-in method conv1d of type object at 0x11a49eac0>

>>> conv, flag = optional_import('torch.nn.functional', '42', name='conv1d')
>>> conv()  # trying to use a function from the not successfully imported module (due to unmatched version)
OptionalImportError: from torch.nn.functional import conv1d (requires version '42' by 'min_version').


This module is written for configurable workflow, not currently in use.


Stores the decorated function or class in the global aliases table under the given names and as the __aliases__ member of the decorated object. This new member will contain all alias names declared for that object.


Search for the declaration (function or class) with the given name. This will first search the list of aliases to see if it was declared with this aliased name, then search treating name as a fully qualified name, then search the loaded modules for one having a declaration with the given name. If no declaration is found, raise ValueError.

  • ValueError – When the module is not found.

  • ValueError – When the module does not have the specified member.

  • ValueError – When multiple modules with the declaration name are found.

  • ValueError – When no module with the specified member is found.


class monai.utils.misc.ImageMetaKey[source]

Common key names in the meta data header of images

monai.utils.misc.copy_to_device(obj, device, non_blocking=True, verbose=False)[source]

Copy object or tuple/list/dictionary of objects to device.

  • obj (Any) – object or tuple/list/dictionary of objects to move to device.

  • device (Union[str, device, None]) – move obj to this device. Can be a string (e.g., cpu, cuda, cuda:0, etc.) or of type torch.device.

  • non_blocking_transfer – when True, moves data to device asynchronously if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

  • verbose (bool) – when True, will print a warning for any elements of incompatible type not copied to device.

Return type



Same as input, copied to device where possible. Original input will be



Convert a numpy dtype to its torch equivalent.


Convert a torch dtype to its numpy equivalent.


Returns a tuple of vals.

Return type

Tuple[Any, …]

monai.utils.misc.ensure_tuple_rep(tup, dim)[source]

Returns a copy of tup with dim values by either shortened or duplicated input.


ValueError – When tup is a sequence and tup length is not dim.


>>> ensure_tuple_rep(1, 3)
(1, 1, 1)
>>> ensure_tuple_rep(None, 3)
(None, None, None)
>>> ensure_tuple_rep('test', 3)
('test', 'test', 'test')
>>> ensure_tuple_rep([1, 2, 3], 3)
(1, 2, 3)
>>> ensure_tuple_rep(range(3), 3)
(0, 1, 2)
>>> ensure_tuple_rep([1, 2], 3)
ValueError: Sequence must have length 3, got length 2.
Return type

Tuple[Any, …]

monai.utils.misc.ensure_tuple_size(tup, dim, pad_val=0)[source]

Returns a copy of tup with dim values by either shortened or padded with pad_val as necessary.

Return type

Tuple[Any, …]

monai.utils.misc.evenly_divisible_all_gather(data, concat=True)[source]

Utility function for distributed data parallel to pad at first dim to make it evenly divisible and all_gather. The input data of every rank should have the same number of dimensions, only the first dim can be different.

  • data (Tensor) – source tensor to pad and execute all_gather in distributed data parallel.

  • concat (bool) – whether to concat the gathered list to be a Tensor, if False, return a list of Tensors, similar behavior as torch.distributed.all_gather(). default to True.


The input data on different ranks must have exactly same dtype.

monai.utils.misc.fall_back_tuple(user_provided, default, func=<function <lambda>>)[source]

Refine user_provided according to the default, and returns as a validated tuple.

The validation is done for each element in user_provided using func. If func(user_provided[idx]) returns False, the corresponding default[idx] will be used as the fallback.

Typically used when user_provided is a tuple of window size provided by the user, default is defined by data, this function returns an updated user_provided with its non-positive components replaced by the corresponding components from default.

  • user_provided (Any) – item to be validated.

  • default (Union[Sequence, ndarray]) – a sequence used to provided the fallbacks.

  • func (Callable) – a Callable to validate every components of user_provided.


>>> fall_back_tuple((1, 2), (32, 32))
(1, 2)
>>> fall_back_tuple(None, (32, 32))
(32, 32)
>>> fall_back_tuple((-1, 10), (32, 32))
(32, 10)
>>> fall_back_tuple((-1, None), (32, 32))
(32, 32)
>>> fall_back_tuple((1, None), (32, 32))
(1, 32)
>>> fall_back_tuple(0, (32, 32))
(32, 32)
>>> fall_back_tuple(range(3), (32, 64, 48))
(32, 1, 2)
>>> fall_back_tuple([0], (32, 32))
ValueError: Sequence must have length 2, got length 1.
Return type

Tuple[Any, …]

monai.utils.misc.first(iterable, default=None)[source]

Returns the first item in the given iterable or default if empty, meaningful mostly with ‘for’ expressions.


Get the expected target device in the distributed data parallel. For NCCL backend, return GPU device of current process. For GLOO backend, return CPU. For any other backends, return None as the default, tensor.to(None) will not change the device.


Determine if the object is an iterable sequence and is not a string.

Return type



To convert a list of “key=value” pairs into a dictionary. For examples: items: [“a=1”, “b=2”, “c=3”], return: {“a”: “1”, “b”: “2”, “c”: “3”}. If no “=” in the pair, use None as the value, for example: [“a”], return: {“a”: None}. Note that it will remove the blanks around keys and values.

monai.utils.misc.progress_bar(index, count, desc=None, bar_len=30, newline=False)[source]

print a progress bar to track some time consuming task.

  • index (int) – current status in progress.

  • count (int) – total steps of the progress.

  • desc (Optional[str]) – description of the progress bar, if not None, show before the progress bar.

  • bar_len (int) – the total length of the bar on screen, default is 30 char.

  • newline (bool) – whether to print in a new line for every index.

Return type


monai.utils.misc.set_determinism(seed=4294967295, additional_settings=None)[source]

Set random seed for modules to enable or disable deterministic training.

  • seed (Optional[int]) – the random seed to use, default is np.iinfo(np.int32).max. It is recommended to set a large seed, i.e. a number that has a good balance of 0 and 1 bits. Avoid having many 0 bits in the seed. if set to None, will disable deterministic training.

  • additional_settings (Union[Sequence[Callable[[int], Any]], Callable[[int], Any], None]) – additional settings that need to set random seed.

Return type


monai.utils.misc.star_zip_with(op, *vals)[source]

Use starmap as the mapping function in zipWith.

monai.utils.misc.string_list_all_gather(strings, delimiter='\\t')[source]

Utility function for distributed data parallel to all gather a list of strings. Refer to the idea of ignite all_gather(string): https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py#L346.

  • strings (List[str]) – a list of strings to all gather.

  • delimiter (str) – use the delimiter to join the string list to be a long string, then all gather across ranks and split to a list. default to ” “.

Return type


monai.utils.misc.zip_with(op, *vals, mapfunc=<class 'map'>)[source]

Map op, using mapfunc, to each tuple derived from zipping the iterables in vals.


class monai.utils.profiling.PerfContext[source]

Context manager for tracking how much time is spent within context blocks. This uses time.perf_counter to accumulate the total amount of time in seconds in the attribute total_time over however many context blocks the object is used in.


A decorator which will run the torch profiler for the decorated function, printing the results in full. Note: Enforces a gpu sync point which could slow down pipelines.


A decorator which measures the execution time of both the CPU and GPU components of the decorated function, printing both results. Note: Enforces a gpu sync point which could slow down pipelines.


A decorator which measures the total execution time from when the decorated function is called to when the last cuda operation finishes, printing the result. Note: Enforces a gpu sync point which could slow down pipelines.


exception monai.utils.deprecated.DeprecatedError[source]
monai.utils.deprecated.deprecated(since=None, removed=None, msg_suffix='', version_val='0.5.3+75.g2464199.dirty')[source]

Marks a function or class as deprecated. If since is given this should be a version at or earlier than the current version and states at what version of the definition was marked as deprecated. If removed is given this can be any version and marks when the definition was removed. When the decorated definition is called, that is when the function is called or the class instantiated, a warning is issued if since is given and the current version is at or later than that given. An exception is instead raised if removed is given and the current version is at or later than that, or if neither since nor removed is provided.

  • since (Optional[str]) – version at which the definition was marked deprecated but not removed

  • removed (Optional[str]) – version at which the definition was removed and no longer usable

  • msg_suffix (str) – message appended to warning/exception detailing reasons for deprecation and what to use instead

  • version_val – (used for testing) version to compare since and removed against, default is MONAI version


Decorated definition which warns or raises exception when used

monai.utils.deprecated.deprecated_arg(name, since=None, removed=None, msg_suffix='', version_val='0.5.3+75.g2464199.dirty')[source]

Marks a particular named argument of a callable as deprecated. The same conditions for since and removed as described in the deprecated decorator.

  • name – name of position or keyword argument to mark as deprecated

  • since (Optional[str]) – version at which the argument was marked deprecated but not removed

  • removed (Optional[str]) – version at which the argument was removed and no longer usable

  • msg_suffix (str) – message appended to warning/exception detailing reasons for deprecation and what to use instead

  • version_val – (used for testing) version to compare since and removed against, default is MONAI version


Decorated callable which warns or raises exception when deprecated argument used