Skip to content

Commit

Permalink
docstring fixes (#6507)
Browse files Browse the repository at this point in the history
### Types of changes
<!--- Put an `x` in all the boxes that apply, and remove the not
applicable items -->
- [x] Non-breaking change (fix or new feature that would not break
existing functionality).
- [ ] Breaking change (fix or new feature that would cause existing
functionality to change).
- [ ] New tests added to cover the changes.
- [ ] Integration tests passed locally by running `./runtests.sh -f -u
--net --coverage`.
- [ ] Quick tests passed locally by running `./runtests.sh --quick
--unittests --disttests`.
- [ ] In-line docstrings updated.
- [ ] Documentation updated, tested `make html` command in the `docs/`
folder.

---------

Signed-off-by: Wenqi Li <wenqil@nvidia.com>
  • Loading branch information
wyli authored May 11, 2023
1 parent 4e0b179 commit e5cf74a
Show file tree
Hide file tree
Showing 15 changed files with 40 additions and 41 deletions.
20 changes: 10 additions & 10 deletions monai/apps/auto3dseg/auto_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ class AutoRunner:
runner = AutoRunner(work_dir=work_dir, input=input, algos=algos)
runner.run()
- User can specify a a local folder with algorithms templates and run AutoRunner:
- User can specify a local folder with algorithms templates and run AutoRunner:
.. code-block:: python
Expand Down Expand Up @@ -414,23 +414,23 @@ def set_gpu_customization(
parameters for each bundleAlgo based on gpus. Custom parameters are obtained through dummy
training to simulate the actual model training process and hyperparameter optimization (HPO)
experiments.
gpu_customization_specs (optinal): the dictionary to enable users overwrite the HPO settings. user can
gpu_customization_specs (optional): the dictionary to enable users overwrite the HPO settings. user can
overwrite part of variables as follows or all of them. The structure is as follows.
.. code-block:: python
gpu_customization_specs = {
'ALOG': {
'ALGO': {
'num_trials': 6,
'range_num_images_per_batch': [1, 20],
'range_num_sw_batch_size': [1, 20]
}
}
ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'unversal' which
ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'universal' which
would apply changes to all algorithms. Possible options are
- {``"unversal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}.
- {``"universal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}.
num_trials: the number of HPO trials/experiments to run.
range_num_images_per_batch: the range of number of images per mini-batch.
Expand Down Expand Up @@ -468,7 +468,7 @@ def set_training_params(self, params: dict[str, Any] | None = None) -> None:
self.train_params = deepcopy(params) if params is not None else {}
if "CUDA_VISIBLE_DEVICES" in self.train_params:
warnings.warn(
"CUDA_VISIBLE_DEVICES is deprecated from 'set_training_params'. Use 'set_device_info' intead.",
"CUDA_VISIBLE_DEVICES is deprecated from 'set_training_params'. Use 'set_device_info' instead.",
DeprecationWarning,
)

Expand All @@ -483,7 +483,7 @@ def set_device_info(
Set the device related info
Args:
cuda_visible_device: define GPU ids for data analyzer, training, and ensembling.
cuda_visible_devices: define GPU ids for data analyzer, training, and ensembling.
List of GPU ids [0,1,2,3] or a string "0,1,2,3".
Default using env "CUDA_VISIBLE_DEVICES" or all devices available.
num_nodes: number of nodes for training and ensembling.
Expand All @@ -497,7 +497,7 @@ def set_device_info(
- single node multi-GPU running "torchrun --nnodes=1 --nproc_per_node=2 "
If user define this prefix, please make sure --nproc_per_node matches cuda_visible_device or
os.env['CUDA_VISIBLE_DEVICES]. Also always set --nnodes=1. Set num_nodes for multi-node.
os.env['CUDA_VISIBLE_DEVICES']. Also always set --nnodes=1. Set num_nodes for multi-node.
"""
self.device_setting: dict[str, Any] = {}
if cuda_visible_devices is None:
Expand Down Expand Up @@ -527,14 +527,14 @@ def set_device_info(
self.device_setting["CMD_PREFIX"] = cmd_prefix

if cmd_prefix is not None:
logger.info(f"Using user defined command running prefix {cmd_prefix}, will overide other settings")
logger.info(f"Using user defined command running prefix {cmd_prefix}, will override other settings")

def set_ensemble_method(self, ensemble_method_name: str = "AlgoEnsembleBestByFold", **kwargs: Any) -> None:
"""
Set the bundle ensemble method name and parameters for save image transform parameters.
Args:
params: the name of the ensemble method. Only two methods are supported "AlgoEnsembleBestN"
ensemble_method_name: the name of the ensemble method. Only two methods are supported "AlgoEnsembleBestN"
and "AlgoEnsembleBestByFold".
kwargs: the keyword arguments used to define the ensemble method. Currently only ``n_best`` for
``AlgoEnsembleBestN`` is supported.
Expand Down
10 changes: 5 additions & 5 deletions monai/apps/auto3dseg/bundle_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ def train(
Args:
train_params: training parameters
device_settings: device related settings, should follow the device_setting in auto_runner.set_device_info.
'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3'
device_setting: device related settings, should follow the device_setting in auto_runner.set_device_info.
'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3'
"""
if device_setting is not None:
self.device_setting.update(device_setting)
Expand Down Expand Up @@ -545,17 +545,17 @@ def generate(
.. code-block:: python
gpu_customization_specs = {
'ALOG': {
'ALGO': {
'num_trials': 6,
'range_num_images_per_batch': [1, 20],
'range_num_sw_batch_size': [1, 20]
}
}
ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'unversal' which
ALGO: the name of algorithm. It could be one of algorithm names (e.g., 'dints') or 'universal' which
would apply changes to all algorithms. Possible options are
- {``"unversal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}.
- {``"universal"``, ``"dints"``, ``"segresnet"``, ``"segresnet2d"``, ``"swinunetr"``}.
num_trials: the number of HPO trials/experiments to run.
range_num_images_per_batch: the range of number of images per mini-batch.
Expand Down
9 changes: 4 additions & 5 deletions monai/apps/auto3dseg/ensemble_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def set_infer_files(self, dataroot: str, data_list_or_path: str | list, data_key
Args:
dataroot: the path of the files
data_src_cfg_file: the data source file path
data_list_or_path: the data source file path
"""

self.infer_files = []
Expand Down Expand Up @@ -405,7 +405,7 @@ class EnsembleRunner:
work_dir: working directory to save the intermediate and final results. Default is `./work_dir`.
num_fold: number of fold. Default is 5.
ensemble_method_name: method to ensemble predictions from different model. Default is AlgoEnsembleBestByFold.
Suported methods: ["AlgoEnsembleBestN", "AlgoEnsembleBestByFold"].
Supported methods: ["AlgoEnsembleBestN", "AlgoEnsembleBestByFold"].
mgpu: if using multi-gpu. Default is True.
kwargs: additional image writing, ensembling parameters and prediction parameters for the ensemble inference.
- for image saving, please check the supported parameters in SaveImage transform.
Expand Down Expand Up @@ -606,9 +606,8 @@ def run(self, device_setting: dict | None = None) -> None:
algo_config.yaml file, which is pre-filled by the fill_template_config function in the same instance.
Args:
train_params: training parameters
device_settings: device related settings, should follow the device_setting in auto_runner.set_device_info.
'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3'
device_setting: device related settings, should follow the device_setting in auto_runner.set_device_info.
'CUDA_VISIBLE_DEVICES' should be a string e.g. '0,1,2,3'
"""
# device_setting set default value and sanity check, in case device_setting not from autorunner
if device_setting is not None:
Expand Down
2 changes: 1 addition & 1 deletion monai/apps/auto3dseg/hpo_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def __call__(
self, trial: Any, obj_filename: str, output_folder: str = ".", template_path: PathLike | None = None
) -> Any:
"""
Callabe that Optuna will use to optimize the hyper-parameters
Callable that Optuna will use to optimize the hyper-parameters
Args:
obj_filename: the pickle-exported Algo object.
Expand Down
2 changes: 1 addition & 1 deletion monai/auto3dseg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def algo_from_pickle(pkl_filename: str, template_path: PathLike | None = None, *
Raises:
ValueError if the pkl_filename does not contain a dict, or the dict does not contain `algo_bytes`.
ModuleNotFoundError if it is unable to instiante the Algo class.
ModuleNotFoundError if it is unable to instantiate the Algo class.
"""
with open(pkl_filename, "rb") as f_pi:
Expand Down
4 changes: 2 additions & 2 deletions monai/bundle/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ def run(
if other string, treat it as file path to load the tracking settings.
if `dict`, treat it as tracking settings.
will patch the target config content with `tracking handlers` and the top-level items of `configs`.
for detailed usage examples, plesae check the tutorial:
for detailed usage examples, please check the tutorial:
https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb.
args_file: a JSON or YAML file to provide default values for `runner_id`, `meta_file`,
`config_file`, `logging`, and override pairs. so that the command line inputs can be simplified.
Expand Down Expand Up @@ -699,7 +699,7 @@ def run(
def run_workflow(workflow: str | BundleWorkflow | None = None, args_file: str | None = None, **kwargs: Any) -> None:
"""
Specify `bundle workflow` to run monai bundle components and workflows.
The workflow should be suclass of `BundleWorkflow` and be available to import.
The workflow should be subclass of `BundleWorkflow` and be available to import.
It can be MONAI existing bundle workflows or user customized workflows.
Typical usage examples:
Expand Down
14 changes: 7 additions & 7 deletions monai/bundle/workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ def get_workflow_type(self):

def add_property(self, name: str, required: str, desc: str | None = None) -> None:
"""
Besides the default predefined properties, some 3rd party aplications may need the bundle
definition to provide additonal properties for the specific use cases, if the bundlle can't
Besides the default predefined properties, some 3rd party applications may need the bundle
definition to provide additional properties for the specific use cases, if the bundle can't
provide the property, means it can't work with the application.
This utility adds the property for the application requirements check and access.
Expand Down Expand Up @@ -183,7 +183,7 @@ class ConfigWorkflow(BundleWorkflow):
if other string, treat it as file path to load the tracking settings.
if `dict`, treat it as tracking settings.
will patch the target config content with `tracking handlers` and the top-level items of `configs`.
for detailed usage examples, plesae check the tutorial:
for detailed usage examples, please check the tutorial:
https://github.com/Project-MONAI/tutorials/blob/main/experiment_management/bundle_integrate_mlflow.ipynb.
workflow: specifies the workflow type: "train" or "training" for a training workflow,
or "infer", "inference", "eval", "evaluation" for a inference workflow,
Expand Down Expand Up @@ -271,8 +271,8 @@ def finalize(self) -> Any:
def check_properties(self) -> list[str] | None:
"""
Check whether the required properties are existing in the bundle workflow.
If the optional properties have reference in the config, will also check whether the properties are exising.
If no workflow type specified, return None, otherwise, return a list of required but missing properites.
If the optional properties have reference in the config, will also check whether the properties are existing.
If no workflow type specified, return None, otherwise, return a list of required but missing properties.
"""
ret = super().check_properties()
Expand Down Expand Up @@ -339,8 +339,8 @@ def add_property( # type: ignore[override]
self, name: str, required: str, config_id: str, desc: str | None = None
) -> None:
"""
Besides the default predefined properties, some 3rd party aplications may need the bundle
definition to provide additonal properties for the specific use cases, if the bundlle can't
Besides the default predefined properties, some 3rd party applications may need the bundle
definition to provide additional properties for the specific use cases, if the bundle can't
provide the property, means it can't work with the application.
This utility adds the property for the application requirements check and access.
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/blocks/text_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(
) -> None:
"""
Args:
out_channels: number of output channels, to control text-baesd embedding for classes.
out_channels: number of output channels, to control text-based embedding for classes.
spatial_dims: number of spatial dims.
text_dim: dimension of text embeddings.
hidden_size: dimension of hidden features, compatible to different vision feature dimensions.
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/nets/swin_unetr.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ def __init__(
downsample: module used for downsampling, available options are `"mergingv2"`, `"merging"` and a
user-specified `nn.Module` following the API defined in :py:class:`monai.networks.nets.PatchMerging`.
The default is currently `"merging"` (the original version defined in v0.9.0).
use_v2: using swinunetr_v2, which adds a residual convolution block at the beggining of each swin stage.
use_v2: using swinunetr_v2, which adds a residual convolution block at the beginning of each swin stage.
"""

super().__init__()
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,7 @@ def convert_to_onnx(
for r1, r2 in zip(torch_out, onnx_out):
if isinstance(r1, torch.Tensor):
assert_fn = torch.testing.assert_close if pytorch_after(1, 11) else torch.testing.assert_allclose
assert_fn(r1.cpu(), convert_to_tensor(r2, track_meta=False), rtol=rtol, atol=atol) # type: ignore
assert_fn(r1.cpu(), convert_to_tensor(r2, dtype=r1.dtype), rtol=rtol, atol=atol) # type: ignore

return onnx_model

Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/utility/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1653,9 +1653,9 @@ def _check_filter_format(self, filter: str | NdarrayOrTensor | nn.Module, filter

def _check_kwargs_are_present(self, filter, **kwargs):
if filter == "gauss" and "sigma" not in kwargs.keys():
raise KeyError("`filter='gauss', requires the additonal keyword argument `sigma`")
raise KeyError("`filter='gauss', requires the additional keyword argument `sigma`")
if filter == "savitzky_golay" and "order" not in kwargs.keys():
raise KeyError("`filter='savitzky_golay', requires the additonal keyword argument `order`")
raise KeyError("`filter='savitzky_golay', requires the additional keyword argument `order`")

def _get_filter_from_string(self, filter: str, size: int, ndim: int) -> nn.Module | Callable:
if filter == "mean":
Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1413,7 +1413,7 @@ def convert_applied_interp_mode(trans_info, mode: str = "nearest", align_corners


def reset_ops_id(data):
"""find MetaTensors in list or dict `data` and (in-place) set ``TraceKeys.ID`` to ``Tracekys.NONE``."""
"""find MetaTensors in list or dict `data` and (in-place) set ``TraceKeys.ID`` to ``Tracekeys.NONE``."""
if isinstance(data, (list, tuple)):
return [reset_ops_id(d) for d in data]
if isinstance(data, monai.data.MetaTensor):
Expand Down Expand Up @@ -1931,7 +1931,7 @@ def resolves_modes(
Args:
interp_mode: interpolation mode.
padding_mdoe: padding mode.
padding_mode: padding mode.
backend: optional backend of `TransformBackends`. If None, the backend will be decided from `interp_mode`.
kwargs: additional keyword arguments. currently support ``torch_interpolate_spatial_nd``, to provide
additional information to determine ``linear``, ``bilinear`` and ``trilinear``;
Expand Down
2 changes: 1 addition & 1 deletion monai/utils/dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def __init__(self, rank: int | None = None, filter_fn: Callable = lambda rank: r
self.rank: int = rank if rank is not None else dist.get_rank()
else:
warnings.warn(
"The torch.distributed is either unavailable and uninitiated when RankFilter is instiantiated. "
"The torch.distributed is either unavailable and uninitiated when RankFilter is instantiated. "
"If torch.distributed is used, please ensure that the RankFilter() is called "
"after torch.distributed.init_process_group() in the script."
)
Expand Down
2 changes: 1 addition & 1 deletion monai/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,7 @@ def check_kwargs_exist_in_class_init(cls, kwargs):
kwargs: kwargs to examine.
Returns:
a boolean inidicating if all keys exist.
a boolean indicating if all keys exist.
a set of extra keys that are not used in the __init__.
"""
init_signature = inspect.signature(cls.__init__)
Expand Down
2 changes: 1 addition & 1 deletion monai/visualize/gradient_based.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def __call__(self, x: torch.Tensor, index: torch.Tensor | int | None = None, **k
class GuidedBackpropGrad(VanillaGrad):
"""
Based on Springenberg and Dosovitskiy et al. https://arxiv.org/abs/1412.6806,
compute gradient-based saliency maps by backpropagating positive graidents and inputs (see ``_AutoGradReLU``).
compute gradient-based saliency maps by backpropagating positive gradients and inputs (see ``_AutoGradReLU``).
See also:
Expand Down

0 comments on commit e5cf74a

Please sign in to comment.