From 5c94edd3e8936829e6e2c21e7c0740d4ce69c22d Mon Sep 17 00:00:00 2001 From: jirka Date: Tue, 28 Oct 2025 20:33:24 +0100 Subject: [PATCH 01/12] Replace `pyupgrade` with builtin Ruff's UP rule Signed-off-by: jirka --- .pre-commit-config.yaml | 16 ++++------------ pyproject.toml | 1 + 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9621a1fe95..86c01b09dc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,22 +30,14 @@ repos: rev: v0.7.0 hooks: - id: ruff - args: - - --fix - - - repo: https://github.com/asottile/pyupgrade - rev: v3.19.0 - hooks: - - id: pyupgrade - args: [--py39-plus, --keep-runtime-typing] - name: Upgrade code with exceptions + args: ["--fix"] exclude: | (?x)( ^versioneer.py| ^monai/_version.py| - ^monai/networks/| # avoid typing rewrites - ^monai/apps/detection/utils/anchor_utils.py| # avoid typing rewrites - ^tests/test_compute_panoptic_quality.py # avoid typing rewrites + ^monai/networks/| # todo: avoid typing rewrites + ^monai/apps/detection/utils/anchor_utils.py| # todo: avoid typing rewrites + ^tests/test_compute_panoptic_quality.py # todo: avoid typing rewrites ) - repo: https://github.com/asottile/yesqa diff --git a/pyproject.toml b/pyproject.toml index 76b26731bf..ed8c2a32dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ target-version = "py39" select = [ "E", "F", "W", # flake8 "NPY", # NumPy specific rules + "UP", # pyupgrade ] extend-ignore = [ "E741", # ambiguous variable name From f0a3e6ab057087c6ca4254771a5a8b18d7a2b6c2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 28 Oct 2025 19:35:03 +0000 Subject: [PATCH 02/12] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Signed-off-by: jirka --- monai/apps/deepgrow/dataset.py | 18 ++---------------- monai/handlers/stats_handler.py | 4 ++-- monai/handlers/tensorboard_handlers.py | 4 ++-- monai/metrics/utils.py | 4 ++-- tests/profile_subclass/profiling.py | 4 +--- 5 files changed, 9 insertions(+), 25 deletions(-) diff --git a/monai/apps/deepgrow/dataset.py b/monai/apps/deepgrow/dataset.py index 802d86e0c7..9609390cb3 100644 --- a/monai/apps/deepgrow/dataset.py +++ b/monai/apps/deepgrow/dataset.py @@ -201,14 +201,7 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.") logging.info( - "{} => Image Shape: {} => {}; Label Shape: {} => {}; Unique Labels: {}".format( - vol_idx, - vol_image.shape, - image_count, - vol_label.shape if vol_label is not None else None, - label_count, - unique_labels_count, - ) + f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count}; Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count}; Unique Labels: {unique_labels_count}" ) return data_list @@ -259,13 +252,6 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.") logging.info( - "{} => Image Shape: {} => {}; Label Shape: {} => {}; Unique Labels: {}".format( - vol_idx, - vol_image.shape, - image_count, - vol_label.shape if vol_label is not None else None, - label_count, - unique_labels_count, - ) + f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count}; Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count}; Unique Labels: {unique_labels_count}" ) return data_list diff --git a/monai/handlers/stats_handler.py b/monai/handlers/stats_handler.py index 214872fef4..1dafde0f54 100644 --- a/monai/handlers/stats_handler.py +++ b/monai/handlers/stats_handler.py @@ -260,7 +260,7 @@ def _default_iteration_print(self, engine: Engine) -> None: "ignoring non-scalar output in StatsHandler," " make sure `output_transform(engine.state.output)` returns" " a scalar or dictionary of key and scalar pairs to avoid this warning." - " {}:{}".format(name, type(value)) + f" {name}:{type(value)}" ) continue # not printing multi dimensional output out_str += self.key_var_format.format(name, value.item() if isinstance(value, torch.Tensor) else value) @@ -273,7 +273,7 @@ def _default_iteration_print(self, engine: Engine) -> None: "ignoring non-scalar output in StatsHandler," " make sure `output_transform(engine.state.output)` returns" " a scalar or a dictionary of key and scalar pairs to avoid this warning." - " {}".format(type(loss)) + f" {type(loss)}" ) if not out_str: diff --git a/monai/handlers/tensorboard_handlers.py b/monai/handlers/tensorboard_handlers.py index 44a03710de..20e2d74c8c 100644 --- a/monai/handlers/tensorboard_handlers.py +++ b/monai/handlers/tensorboard_handlers.py @@ -257,7 +257,7 @@ def _default_iteration_writer(self, engine: Engine, writer: SummaryWriter | Summ "ignoring non-scalar output in TensorBoardStatsHandler," " make sure `output_transform(engine.state.output)` returns" " a scalar or dictionary of key and scalar pairs to avoid this warning." - " {}:{}".format(name, type(value)) + f" {name}:{type(value)}" ) continue # not plot multi dimensional output self._write_scalar( @@ -280,7 +280,7 @@ def _default_iteration_writer(self, engine: Engine, writer: SummaryWriter | Summ "ignoring non-scalar output in TensorBoardStatsHandler," " make sure `output_transform(engine.state.output)` returns" " a scalar or a dictionary of key and scalar pairs to avoid this warning." - " {}".format(type(loss)) + f" {type(loss)}" ) writer.flush() diff --git a/monai/metrics/utils.py b/monai/metrics/utils.py index 972ec0061e..606a54669b 100644 --- a/monai/metrics/utils.py +++ b/monai/metrics/utils.py @@ -13,7 +13,7 @@ import warnings from collections.abc import Iterable, Sequence -from functools import lru_cache, partial +from functools import partial, cache from types import ModuleType from typing import Any @@ -465,7 +465,7 @@ def prepare_spacing( ENCODING_KERNEL = {2: [[8, 4], [2, 1]], 3: [[[128, 64], [32, 16]], [[8, 4], [2, 1]]]} -@lru_cache(maxsize=None) +@cache def _get_neighbour_code_to_normals_table(device=None): """ returns a lookup table. For every binary neighbour code (2x2x2 neighbourhood = 8 neighbours = 8 bits = 256 codes) diff --git a/tests/profile_subclass/profiling.py b/tests/profile_subclass/profiling.py index ffa6a8b17d..3e1d99e920 100644 --- a/tests/profile_subclass/profiling.py +++ b/tests/profile_subclass/profiling.py @@ -63,9 +63,7 @@ def main(): b_min, b_avg, b_med, b_std = bench(tensor_1, tensor_2) print( - "Type {} time (microseconds): min: {}, avg: {}, median: {}, and std {}.".format( - t.__name__, (10**6 * b_min), (10**6) * b_avg, (10**6) * b_med, (10**6) * b_std - ) + f"Type {t.__name__} time (microseconds): min: {10**6 * b_min}, avg: {(10**6) * b_avg}, median: {(10**6) * b_med}, and std {(10**6) * b_std}." ) From b249b2f814c26d9199280a807950a247feb91618 Mon Sep 17 00:00:00 2001 From: jirka Date: Tue, 28 Oct 2025 20:37:51 +0100 Subject: [PATCH 03/12] --unsafe-fixes Signed-off-by: jirka --- monai/apps/deepgrow/dataset.py | 8 ++++++-- monai/apps/nnunet/nnunet_bundle.py | 18 +++++++++--------- monai/losses/adversarial_loss.py | 3 +-- monai/losses/dice.py | 2 +- monai/losses/ds_loss.py | 3 +-- monai/losses/focal_loss.py | 7 +++---- monai/losses/perceptual.py | 3 +-- monai/losses/spatial_mask.py | 4 ++-- monai/losses/sure_loss.py | 16 ++++++++-------- monai/transforms/utility/array.py | 6 +++--- tests/profile_subclass/profiling.py | 3 ++- 11 files changed, 37 insertions(+), 36 deletions(-) diff --git a/monai/apps/deepgrow/dataset.py b/monai/apps/deepgrow/dataset.py index 9609390cb3..e597188e74 100644 --- a/monai/apps/deepgrow/dataset.py +++ b/monai/apps/deepgrow/dataset.py @@ -201,7 +201,9 @@ def _save_data_2d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.") logging.info( - f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count}; Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count}; Unique Labels: {unique_labels_count}" + f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count};" + f" Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count};" + f" Unique Labels: {unique_labels_count}" ) return data_list @@ -252,6 +254,8 @@ def _save_data_3d(vol_idx, vol_image, vol_label, dataset_dir, relative_path): logging.warning(f"Unique labels {unique_labels_count} exceeds 20. Please check if this is correct.") logging.info( - f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count}; Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count}; Unique Labels: {unique_labels_count}" + f"{vol_idx} => Image Shape: {vol_image.shape} => {image_count};" + f" Label Shape: {vol_label.shape if vol_label is not None else None} => {label_count};" + f" Unique Labels: {unique_labels_count}" ) return data_list diff --git a/monai/apps/nnunet/nnunet_bundle.py b/monai/apps/nnunet/nnunet_bundle.py index df8f09bf4b..47a0755ddf 100644 --- a/monai/apps/nnunet/nnunet_bundle.py +++ b/monai/apps/nnunet/nnunet_bundle.py @@ -13,7 +13,7 @@ import os import shutil from pathlib import Path -from typing import Any, Optional, Union +from typing import Any import numpy as np import torch @@ -36,9 +36,9 @@ def get_nnunet_trainer( - dataset_name_or_id: Union[str, int], + dataset_name_or_id: str | int, configuration: str, - fold: Union[int, str], + fold: int | str, trainer_class_name: str = "nnUNetTrainer", plans_identifier: str = "nnUNetPlans", use_compressed_data: bool = False, @@ -46,7 +46,7 @@ def get_nnunet_trainer( only_run_validation: bool = False, disable_checkpointing: bool = False, device: str = "cuda", - pretrained_model: Optional[str] = None, + pretrained_model: str | None = None, ) -> Any: # type: ignore """ Get the nnUNet trainer instance based on the provided configuration. @@ -166,7 +166,7 @@ class ModelnnUNetWrapper(torch.nn.Module): restoring network architecture, and setting up the predictor for inference. """ - def __init__(self, predictor: object, model_folder: Union[str, Path], model_name: str = "model.pt"): # type: ignore + def __init__(self, predictor: object, model_folder: str | Path, model_name: str = "model.pt"): # type: ignore super().__init__() self.predictor = predictor @@ -294,7 +294,7 @@ def forward(self, x: MetaTensor) -> MetaTensor: return MetaTensor(out_tensor, meta=x.meta) -def get_nnunet_monai_predictor(model_folder: Union[str, Path], model_name: str = "model.pt") -> ModelnnUNetWrapper: +def get_nnunet_monai_predictor(model_folder: str | Path, model_name: str = "model.pt") -> ModelnnUNetWrapper: """ Initializes and returns a `nnUNetMONAIModelWrapper` containing the corresponding `nnUNetPredictor`. The model folder should contain the following files, created during training: @@ -426,9 +426,9 @@ def get_network_from_nnunet_plans( plans_file: str, dataset_file: str, configuration: str, - model_ckpt: Optional[str] = None, + model_ckpt: str | None = None, model_key_in_ckpt: str = "model", -) -> Union[torch.nn.Module, Any]: +) -> torch.nn.Module | Any: """ Load and initialize a nnUNet network based on nnUNet plans and configuration. @@ -518,7 +518,7 @@ def convert_monai_bundle_to_nnunet(nnunet_config: dict, bundle_root_folder: str, from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name def subfiles( - folder: Union[str, Path], prefix: Optional[str] = None, suffix: Optional[str] = None, sort: bool = True + folder: str | Path, prefix: str | None = None, suffix: str | None = None, sort: bool = True ) -> list[str]: res = [ i.name diff --git a/monai/losses/adversarial_loss.py b/monai/losses/adversarial_loss.py index c7be79243f..3f7dc80098 100644 --- a/monai/losses/adversarial_loss.py +++ b/monai/losses/adversarial_loss.py @@ -57,8 +57,7 @@ def __init__( if criterion.lower() not in list(AdversarialCriterions): raise ValueError( - "Unrecognised criterion entered for Adversarial Loss. Must be one in: %s" - % ", ".join(AdversarialCriterions) + "Unrecognised criterion entered for Adversarial Loss. Must be one in: {}".format(", ".join(AdversarialCriterions)) ) # Depending on the criterion, a different activation layer is used. diff --git a/monai/losses/dice.py b/monai/losses/dice.py index ed88100edd..99baa34286 100644 --- a/monai/losses/dice.py +++ b/monai/losses/dice.py @@ -494,7 +494,7 @@ def __init__( raise ValueError(f"dist_matrix must be C x C, got {dist_matrix.shape[0]} x {dist_matrix.shape[1]}.") if weighting_mode not in ["default", "GDL"]: - raise ValueError("weighting_mode must be either 'default' or 'GDL, got %s." % weighting_mode) + raise ValueError(f"weighting_mode must be either 'default' or 'GDL, got {weighting_mode}.") self.m = dist_matrix if isinstance(self.m, np.ndarray): diff --git a/monai/losses/ds_loss.py b/monai/losses/ds_loss.py index 6a604aa22d..ef359bcfd0 100644 --- a/monai/losses/ds_loss.py +++ b/monai/losses/ds_loss.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Union import torch import torch.nn.functional as F @@ -70,7 +69,7 @@ def get_loss(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: target = F.interpolate(target, size=input.shape[2:], mode=self.interp_mode) return self.loss(input, target) # type: ignore[no-any-return] - def forward(self, input: Union[None, torch.Tensor, list[torch.Tensor]], target: torch.Tensor) -> torch.Tensor: + def forward(self, input: None | torch.Tensor | list[torch.Tensor], target: torch.Tensor) -> torch.Tensor: if isinstance(input, (list, tuple)): weights = self.get_weights(levels=len(input)) loss = torch.tensor(0, dtype=torch.float, device=target.device) diff --git a/monai/losses/focal_loss.py b/monai/losses/focal_loss.py index 28d1c0cdc9..a1145c521e 100644 --- a/monai/losses/focal_loss.py +++ b/monai/losses/focal_loss.py @@ -13,7 +13,6 @@ import warnings from collections.abc import Sequence -from typing import Optional import torch import torch.nn.functional as F @@ -153,7 +152,7 @@ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: if target.shape != input.shape: raise ValueError(f"ground truth has different shape ({target.shape}) from input ({input.shape})") - loss: Optional[torch.Tensor] = None + loss: torch.Tensor | None = None input = input.float() target = target.float() if self.use_softmax: @@ -203,7 +202,7 @@ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: def softmax_focal_loss( - input: torch.Tensor, target: torch.Tensor, gamma: float = 2.0, alpha: Optional[float] = None + input: torch.Tensor, target: torch.Tensor, gamma: float = 2.0, alpha: float | None = None ) -> torch.Tensor: """ FL(pt) = -alpha * (1 - pt)**gamma * log(pt) @@ -225,7 +224,7 @@ def softmax_focal_loss( def sigmoid_focal_loss( - input: torch.Tensor, target: torch.Tensor, gamma: float = 2.0, alpha: Optional[float] = None + input: torch.Tensor, target: torch.Tensor, gamma: float = 2.0, alpha: float | None = None ) -> torch.Tensor: """ FL(pt) = -alpha * (1 - pt)**gamma * log(pt) diff --git a/monai/losses/perceptual.py b/monai/losses/perceptual.py index 2ae03bc8dc..b818d497c1 100644 --- a/monai/losses/perceptual.py +++ b/monai/losses/perceptual.py @@ -95,8 +95,7 @@ def __init__( if network_type.lower() not in list(PercetualNetworkType): raise ValueError( - "Unrecognised criterion entered for Adversarial Loss. Must be one in: %s" - % ", ".join(PercetualNetworkType) + "Unrecognised criterion entered for Adversarial Loss. Must be one in: {}".format(", ".join(PercetualNetworkType)) ) if cache_dir: diff --git a/monai/losses/spatial_mask.py b/monai/losses/spatial_mask.py index a4c16236a2..0f823410dd 100644 --- a/monai/losses/spatial_mask.py +++ b/monai/losses/spatial_mask.py @@ -14,7 +14,7 @@ import inspect import warnings from collections.abc import Callable -from typing import Any, Optional +from typing import Any import torch from torch.nn.modules.loss import _Loss @@ -47,7 +47,7 @@ def __init__( if not callable(self.loss): raise ValueError("The loss function is not callable.") - def forward(self, input: torch.Tensor, target: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: + def forward(self, input: torch.Tensor, target: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor: """ Args: input: the shape should be BNH[WD]. diff --git a/monai/losses/sure_loss.py b/monai/losses/sure_loss.py index fa8820885d..5d0e1c28c5 100644 --- a/monai/losses/sure_loss.py +++ b/monai/losses/sure_loss.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Callable, Optional +from typing import Callable import torch import torch.nn as nn @@ -42,10 +42,10 @@ def sure_loss_function( operator: Callable, x: torch.Tensor, y_pseudo_gt: torch.Tensor, - y_ref: Optional[torch.Tensor] = None, - eps: Optional[float] = -1.0, - perturb_noise: Optional[torch.Tensor] = None, - complex_input: Optional[bool] = False, + y_ref: torch.Tensor | None = None, + eps: float | None = -1.0, + perturb_noise: torch.Tensor | None = None, + complex_input: bool | None = False, ) -> torch.Tensor: """ Args: @@ -131,7 +131,7 @@ class SURELoss(_Loss): (https://arxiv.org/pdf/2310.01799.pdf) """ - def __init__(self, perturb_noise: Optional[torch.Tensor] = None, eps: Optional[float] = None) -> None: + def __init__(self, perturb_noise: torch.Tensor | None = None, eps: float | None = None) -> None: """ Args: perturb_noise (torch.Tensor, optional): The noise vector of shape @@ -149,8 +149,8 @@ def forward( operator: Callable, x: torch.Tensor, y_pseudo_gt: torch.Tensor, - y_ref: Optional[torch.Tensor] = None, - complex_input: Optional[bool] = False, + y_ref: torch.Tensor | None = None, + complex_input: bool | None = False, ) -> torch.Tensor: """ Args: diff --git a/monai/transforms/utility/array.py b/monai/transforms/utility/array.py index 18a0f7f32f..e322852962 100644 --- a/monai/transforms/utility/array.py +++ b/monai/transforms/utility/array.py @@ -21,7 +21,7 @@ from collections.abc import Hashable, Mapping, Sequence from copy import deepcopy from functools import partial -from typing import Any, Callable, Union +from typing import Any, Callable import numpy as np import torch @@ -1216,7 +1216,7 @@ def __init__(self, name: str, *args, **kwargs) -> None: transform, _ = optional_import("torchio.transforms", "0.18.0", min_version, name=name) self.trans = transform(*args, **kwargs) - def __call__(self, img: Union[NdarrayOrTensor, Mapping[Hashable, NdarrayOrTensor]]): + def __call__(self, img: NdarrayOrTensor | Mapping[Hashable, NdarrayOrTensor]): """ Args: img: an instance of torchio.Subject, torchio.Image, numpy.ndarray, torch.Tensor, SimpleITK.Image, @@ -1248,7 +1248,7 @@ def __init__(self, name: str, *args, **kwargs) -> None: transform, _ = optional_import("torchio.transforms", "0.18.0", min_version, name=name) self.trans = transform(*args, **kwargs) - def __call__(self, img: Union[NdarrayOrTensor, Mapping[Hashable, NdarrayOrTensor]]): + def __call__(self, img: NdarrayOrTensor | Mapping[Hashable, NdarrayOrTensor]): """ Args: img: an instance of torchio.Subject, torchio.Image, numpy.ndarray, torch.Tensor, SimpleITK.Image, diff --git a/tests/profile_subclass/profiling.py b/tests/profile_subclass/profiling.py index 3e1d99e920..18aecea2fb 100644 --- a/tests/profile_subclass/profiling.py +++ b/tests/profile_subclass/profiling.py @@ -63,7 +63,8 @@ def main(): b_min, b_avg, b_med, b_std = bench(tensor_1, tensor_2) print( - f"Type {t.__name__} time (microseconds): min: {10**6 * b_min}, avg: {(10**6) * b_avg}, median: {(10**6) * b_med}, and std {(10**6) * b_std}." + f"Type {t.__name__} time (microseconds):" + f" min: {10**6 * b_min}, avg: {(10**6) * b_avg}, median: {(10**6) * b_med}, and std {(10**6) * b_std}." ) From b2d430d42af0e88f1cc4e00fdc0d5a17e1668be7 Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Tue, 28 Oct 2025 20:41:42 +0100 Subject: [PATCH 04/12] Apply suggestions from code review Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/dice.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/dice.py b/monai/losses/dice.py index 99baa34286..948749606b 100644 --- a/monai/losses/dice.py +++ b/monai/losses/dice.py @@ -494,7 +494,7 @@ def __init__( raise ValueError(f"dist_matrix must be C x C, got {dist_matrix.shape[0]} x {dist_matrix.shape[1]}.") if weighting_mode not in ["default", "GDL"]: - raise ValueError(f"weighting_mode must be either 'default' or 'GDL, got {weighting_mode}.") + raise ValueError(f"weighting_mode must be either 'default' or 'GDL', got {weighting_mode}.") self.m = dist_matrix if isinstance(self.m, np.ndarray): From cb6797f15c56cc1f117d64125d3dad58ebe82e1d Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:06:51 +0100 Subject: [PATCH 05/12] Update monai/losses/perceptual.py Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/perceptual.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/perceptual.py b/monai/losses/perceptual.py index b818d497c1..7774c39f10 100644 --- a/monai/losses/perceptual.py +++ b/monai/losses/perceptual.py @@ -95,7 +95,7 @@ def __init__( if network_type.lower() not in list(PercetualNetworkType): raise ValueError( - "Unrecognised criterion entered for Adversarial Loss. Must be one in: {}".format(", ".join(PercetualNetworkType)) + "Unrecognised criterion entered for Perceptual Loss. Must be one in: {}".format(", ".join(PercetualNetworkType)) ) if cache_dir: From ef4667e62b5956cdb8d7843264a39121a053693c Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:13:14 +0100 Subject: [PATCH 06/12] Update monai/losses/sure_loss.py Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/sure_loss.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/sure_loss.py b/monai/losses/sure_loss.py index 5d0e1c28c5..39ef5b234a 100644 --- a/monai/losses/sure_loss.py +++ b/monai/losses/sure_loss.py @@ -43,7 +43,7 @@ def sure_loss_function( x: torch.Tensor, y_pseudo_gt: torch.Tensor, y_ref: torch.Tensor | None = None, - eps: float | None = -1.0, + eps: float = -1.0, perturb_noise: torch.Tensor | None = None, complex_input: bool | None = False, ) -> torch.Tensor: From fba765049e4ae0bdea9c8cae8608d0db004756c3 Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:13:26 +0100 Subject: [PATCH 07/12] Update monai/losses/sure_loss.py Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/sure_loss.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/sure_loss.py b/monai/losses/sure_loss.py index 39ef5b234a..a06b06dbda 100644 --- a/monai/losses/sure_loss.py +++ b/monai/losses/sure_loss.py @@ -45,7 +45,7 @@ def sure_loss_function( y_ref: torch.Tensor | None = None, eps: float = -1.0, perturb_noise: torch.Tensor | None = None, - complex_input: bool | None = False, + complex_input: bool = False, ) -> torch.Tensor: """ Args: From c0adfc35e4d37e12e4a1389a4401467729fbed6b Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:13:54 +0100 Subject: [PATCH 08/12] Update monai/losses/sure_loss.py Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/sure_loss.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/sure_loss.py b/monai/losses/sure_loss.py index a06b06dbda..30aed2a4dc 100644 --- a/monai/losses/sure_loss.py +++ b/monai/losses/sure_loss.py @@ -150,7 +150,7 @@ def forward( x: torch.Tensor, y_pseudo_gt: torch.Tensor, y_ref: torch.Tensor | None = None, - complex_input: bool | None = False, + complex_input: bool = False, ) -> torch.Tensor: """ Args: From 58caa349d4e0a3657001b537cf685f41d8039de0 Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:15:33 +0100 Subject: [PATCH 09/12] Update monai/losses/adversarial_loss.py Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- monai/losses/adversarial_loss.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monai/losses/adversarial_loss.py b/monai/losses/adversarial_loss.py index 3f7dc80098..b2c27a41ee 100644 --- a/monai/losses/adversarial_loss.py +++ b/monai/losses/adversarial_loss.py @@ -57,7 +57,7 @@ def __init__( if criterion.lower() not in list(AdversarialCriterions): raise ValueError( - "Unrecognised criterion entered for Adversarial Loss. Must be one in: {}".format(", ".join(AdversarialCriterions)) + f"Unrecognised criterion entered for Adversarial Loss. Must be one in: {', '.join(AdversarialCriterions)}" ) # Depending on the criterion, a different activation layer is used. From 8a7eeed260be01ae41274ff814d2a054d1a2ada0 Mon Sep 17 00:00:00 2001 From: Jirka Borovec <6035284+Borda@users.noreply.github.com> Date: Sun, 9 Nov 2025 10:11:42 +0100 Subject: [PATCH 10/12] Apply suggestions from code review Signed-off-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> --- .pre-commit-config.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 86c01b09dc..271980fd7a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -35,9 +35,9 @@ repos: (?x)( ^versioneer.py| ^monai/_version.py| - ^monai/networks/| # todo: avoid typing rewrites - ^monai/apps/detection/utils/anchor_utils.py| # todo: avoid typing rewrites - ^tests/test_compute_panoptic_quality.py # todo: avoid typing rewrites + ^monai/networks/| # avoid typing rewrites + ^monai/apps/detection/utils/anchor_utils.py| # avoid typing rewrites + ^tests/test_compute_panoptic_quality.py # avoid typing rewrites ) - repo: https://github.com/asottile/yesqa From d8bae00d444a837e9f43b68cdde7bfea046091f7 Mon Sep 17 00:00:00 2001 From: jirka Date: Sun, 9 Nov 2025 10:15:49 +0100 Subject: [PATCH 11/12] --unsafe-fixes Signed-off-by: jirka --- .pre-commit-config.yaml | 5 +---- monai/apps/detection/utils/anchor_utils.py | 6 +++--- monai/networks/blocks/attention_utils.py | 3 +-- monai/networks/blocks/crossattention.py | 9 ++++----- monai/networks/blocks/denseblock.py | 2 +- monai/networks/blocks/mlp.py | 5 ++--- monai/networks/blocks/patchembedding.py | 3 +-- monai/networks/blocks/pos_embed_utils.py | 5 ++--- monai/networks/blocks/rel_pos_embedding.py | 4 ++-- monai/networks/blocks/selfattention.py | 15 +++++++-------- monai/networks/blocks/spatialattention.py | 3 +-- monai/networks/blocks/transformerblock.py | 3 +-- monai/networks/layers/simplelayers.py | 2 +- monai/networks/layers/utils.py | 3 +-- monai/networks/layers/vector_quantizer.py | 8 ++++---- monai/networks/nets/ahnet.py | 3 +-- monai/networks/nets/autoencoderkl.py | 5 ++--- monai/networks/nets/basic_unet.py | 3 +-- monai/networks/nets/dints.py | 12 +++++------- monai/networks/nets/dynunet.py | 17 +++++++++-------- monai/networks/nets/netadapter.py | 4 ++-- monai/networks/nets/quicknat.py | 10 +++++----- monai/networks/nets/resnet.py | 2 +- monai/networks/nets/segresnet_ds.py | 7 +++---- monai/networks/nets/senet.py | 2 +- monai/networks/nets/spade_network.py | 6 +++--- monai/networks/nets/swin_unetr.py | 2 +- monai/networks/nets/vista3d.py | 13 +++++++------ monai/networks/nets/vqvae.py | 9 ++++----- monai/networks/schedulers/rectified_flow.py | 3 +-- monai/networks/trt_compiler.py | 16 ++++++++-------- monai/networks/utils.py | 3 ++- 32 files changed, 88 insertions(+), 105 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 271980fd7a..db2d0f7534 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,10 +34,7 @@ repos: exclude: | (?x)( ^versioneer.py| - ^monai/_version.py| - ^monai/networks/| # avoid typing rewrites - ^monai/apps/detection/utils/anchor_utils.py| # avoid typing rewrites - ^tests/test_compute_panoptic_quality.py # avoid typing rewrites + ^monai/_version.py ) - repo: https://github.com/asottile/yesqa diff --git a/monai/apps/detection/utils/anchor_utils.py b/monai/apps/detection/utils/anchor_utils.py index cbde3ebae9..b750fe0de8 100644 --- a/monai/apps/detection/utils/anchor_utils.py +++ b/monai/apps/detection/utils/anchor_utils.py @@ -39,7 +39,7 @@ from __future__ import annotations -from typing import List, Sequence +from collections.abc import Sequence import torch from torch import Tensor, nn @@ -106,7 +106,7 @@ class AnchorGenerator(nn.Module): anchor_generator = AnchorGenerator(sizes, aspect_ratios) """ - __annotations__ = {"cell_anchors": List[torch.Tensor]} + __annotations__ = {"cell_anchors": list[torch.Tensor]} def __init__( self, @@ -364,7 +364,7 @@ class AnchorGeneratorWithAnchorShape(AnchorGenerator): anchor_generator = AnchorGeneratorWithAnchorShape(feature_map_scales, base_anchor_shapes) """ - __annotations__ = {"cell_anchors": List[torch.Tensor]} + __annotations__ = {"cell_anchors": list[torch.Tensor]} def __init__( self, diff --git a/monai/networks/blocks/attention_utils.py b/monai/networks/blocks/attention_utils.py index 8c9002a16e..c5666d7728 100644 --- a/monai/networks/blocks/attention_utils.py +++ b/monai/networks/blocks/attention_utils.py @@ -9,7 +9,6 @@ from __future__ import annotations -from typing import Tuple import torch import torch.nn.functional as F @@ -50,7 +49,7 @@ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor def add_decomposed_rel_pos( - attn: torch.Tensor, q: torch.Tensor, rel_pos_lst: nn.ParameterList, q_size: Tuple, k_size: Tuple + attn: torch.Tensor, q: torch.Tensor, rel_pos_lst: nn.ParameterList, q_size: tuple, k_size: tuple ) -> torch.Tensor: r""" Calculate decomposed Relative Positional Embeddings from mvitv2 implementation: diff --git a/monai/networks/blocks/crossattention.py b/monai/networks/blocks/crossattention.py index be31d2d8fb..e00ff406b6 100644 --- a/monai/networks/blocks/crossattention.py +++ b/monai/networks/blocks/crossattention.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Optional, Tuple import torch import torch.nn as nn @@ -41,9 +40,9 @@ def __init__( save_attn: bool = False, causal: bool = False, sequence_length: int | None = None, - rel_pos_embedding: Optional[str] = None, - input_size: Optional[Tuple] = None, - attention_dtype: Optional[torch.dtype] = None, + rel_pos_embedding: str | None = None, + input_size: tuple | None = None, + attention_dtype: torch.dtype | None = None, use_flash_attention: bool = False, ) -> None: """ @@ -134,7 +133,7 @@ def __init__( ) self.input_size = input_size - def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None): + def forward(self, x: torch.Tensor, context: torch.Tensor | None = None): """ Args: x (torch.Tensor): input tensor. B x (s_dim_1 * ... * s_dim_n) x C diff --git a/monai/networks/blocks/denseblock.py b/monai/networks/blocks/denseblock.py index 8c67584f5f..ecccab9d5a 100644 --- a/monai/networks/blocks/denseblock.py +++ b/monai/networks/blocks/denseblock.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Sequence +from collections.abc import Sequence import torch import torch.nn as nn diff --git a/monai/networks/blocks/mlp.py b/monai/networks/blocks/mlp.py index 8771711d25..aee76846e3 100644 --- a/monai/networks/blocks/mlp.py +++ b/monai/networks/blocks/mlp.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Union import torch.nn as nn @@ -56,8 +55,8 @@ def __init__( self.linear2 = nn.Linear(mlp_dim, hidden_size) self.fn = get_act_layer(act) # Use Union[nn.Dropout, nn.Identity] for type annotations - self.drop1: Union[nn.Dropout, nn.Identity] - self.drop2: Union[nn.Dropout, nn.Identity] + self.drop1: nn.Dropout | nn.Identity + self.drop2: nn.Dropout | nn.Identity dropout_opt = look_up_option(dropout_mode, SUPPORTED_DROPOUT_MODE) if dropout_opt == "vit": diff --git a/monai/networks/blocks/patchembedding.py b/monai/networks/blocks/patchembedding.py index 4e8a6a0463..2a05ef964c 100644 --- a/monai/networks/blocks/patchembedding.py +++ b/monai/networks/blocks/patchembedding.py @@ -12,7 +12,6 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Optional import numpy as np import torch @@ -54,7 +53,7 @@ def __init__( pos_embed_type: str = "learnable", dropout_rate: float = 0.0, spatial_dims: int = 3, - pos_embed_kwargs: Optional[dict] = None, + pos_embed_kwargs: dict | None = None, ) -> None: """ Args: diff --git a/monai/networks/blocks/pos_embed_utils.py b/monai/networks/blocks/pos_embed_utils.py index 266be5e28c..0612a02c28 100644 --- a/monai/networks/blocks/pos_embed_utils.py +++ b/monai/networks/blocks/pos_embed_utils.py @@ -13,7 +13,6 @@ import collections.abc from itertools import repeat -from typing import List, Union import torch import torch.nn as nn @@ -33,7 +32,7 @@ def parse(x): def build_fourier_position_embedding( - grid_size: Union[int, List[int]], embed_dim: int, spatial_dims: int = 3, scales: Union[float, List[float]] = 1.0 + grid_size: int | list[int], embed_dim: int, spatial_dims: int = 3, scales: float | list[float] = 1.0 ) -> torch.nn.Parameter: """ Builds a (Anistropic) Fourier feature position embedding based on the given grid size, embed dimension, @@ -86,7 +85,7 @@ def build_fourier_position_embedding( def build_sincos_position_embedding( - grid_size: Union[int, List[int]], embed_dim: int, spatial_dims: int = 3, temperature: float = 10000.0 + grid_size: int | list[int], embed_dim: int, spatial_dims: int = 3, temperature: float = 10000.0 ) -> torch.nn.Parameter: """ Builds a sin-cos position embedding based on the given grid size, embed dimension, spatial dimensions, and temperature. diff --git a/monai/networks/blocks/rel_pos_embedding.py b/monai/networks/blocks/rel_pos_embedding.py index e53e5841b0..995e179c6e 100644 --- a/monai/networks/blocks/rel_pos_embedding.py +++ b/monai/networks/blocks/rel_pos_embedding.py @@ -9,7 +9,7 @@ from __future__ import annotations -from typing import Iterable, Tuple +from collections.abc import Iterable import torch from torch import nn @@ -19,7 +19,7 @@ class DecomposedRelativePosEmbedding(nn.Module): - def __init__(self, s_input_dims: Tuple[int, int] | Tuple[int, int, int], c_dim: int, num_heads: int) -> None: + def __init__(self, s_input_dims: tuple[int, int] | tuple[int, int, int], c_dim: int, num_heads: int) -> None: """ Args: s_input_dims (Tuple): input spatial dimension. (H, W) or (H, W, D) diff --git a/monai/networks/blocks/selfattention.py b/monai/networks/blocks/selfattention.py index dac7e5c5da..0bca6a24bd 100644 --- a/monai/networks/blocks/selfattention.py +++ b/monai/networks/blocks/selfattention.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Optional, Tuple, Union import torch import torch.nn as nn @@ -41,7 +40,7 @@ def __init__( causal: bool = False, sequence_length: int | None = None, rel_pos_embedding: str | None = None, - input_size: Tuple | None = None, + input_size: tuple | None = None, attention_dtype: torch.dtype | None = None, include_fc: bool = True, use_combined_linear: bool = True, @@ -101,16 +100,16 @@ def __init__( self.num_heads = num_heads self.hidden_input_size = hidden_input_size if hidden_input_size else hidden_size - self.out_proj: Union[nn.Linear, nn.Identity] + self.out_proj: nn.Linear | nn.Identity if include_fc: self.out_proj = nn.Linear(self.inner_dim, self.hidden_input_size) else: self.out_proj = nn.Identity() - self.qkv: Union[nn.Linear, nn.Identity] - self.to_q: Union[nn.Linear, nn.Identity] - self.to_k: Union[nn.Linear, nn.Identity] - self.to_v: Union[nn.Linear, nn.Identity] + self.qkv: nn.Linear | nn.Identity + self.to_q: nn.Linear | nn.Identity + self.to_k: nn.Linear | nn.Identity + self.to_v: nn.Linear | nn.Identity if use_combined_linear: self.qkv = nn.Linear(self.hidden_input_size, self.inner_dim * 3, bias=qkv_bias) @@ -153,7 +152,7 @@ def __init__( ) self.input_size = input_size - def forward(self, x, attn_mask: Optional[torch.Tensor] = None): + def forward(self, x, attn_mask: torch.Tensor | None = None): """ Args: x (torch.Tensor): input tensor. B x (s_dim_1 * ... * s_dim_n) x C diff --git a/monai/networks/blocks/spatialattention.py b/monai/networks/blocks/spatialattention.py index 60a89a7840..52513c961b 100644 --- a/monai/networks/blocks/spatialattention.py +++ b/monai/networks/blocks/spatialattention.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Optional import torch import torch.nn as nn @@ -46,7 +45,7 @@ def __init__( num_head_channels: int | None = None, norm_num_groups: int = 32, norm_eps: float = 1e-6, - attention_dtype: Optional[torch.dtype] = None, + attention_dtype: torch.dtype | None = None, include_fc: bool = True, use_combined_linear: bool = False, use_flash_attention: bool = False, diff --git a/monai/networks/blocks/transformerblock.py b/monai/networks/blocks/transformerblock.py index 6f0da73e7b..0fd656b2b6 100644 --- a/monai/networks/blocks/transformerblock.py +++ b/monai/networks/blocks/transformerblock.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Optional import torch import torch.nn as nn @@ -91,7 +90,7 @@ def __init__( ) def forward( - self, x: torch.Tensor, context: Optional[torch.Tensor] = None, attn_mask: Optional[torch.Tensor] = None + self, x: torch.Tensor, context: torch.Tensor | None = None, attn_mask: torch.Tensor | None = None ) -> torch.Tensor: x = x + self.attn(self.norm1(x), attn_mask=attn_mask) if self.with_cross_attention: diff --git a/monai/networks/layers/simplelayers.py b/monai/networks/layers/simplelayers.py index 6d34c3fa77..ab5cad2b92 100644 --- a/monai/networks/layers/simplelayers.py +++ b/monai/networks/layers/simplelayers.py @@ -13,7 +13,7 @@ import math from copy import deepcopy -from typing import Sequence +from collections.abc import Sequence import torch import torch.nn.functional as F diff --git a/monai/networks/layers/utils.py b/monai/networks/layers/utils.py index 8676f74638..c76eab934b 100644 --- a/monai/networks/layers/utils.py +++ b/monai/networks/layers/utils.py @@ -11,7 +11,6 @@ from __future__ import annotations -from typing import Optional import torch.nn @@ -128,7 +127,7 @@ def get_pool_layer(name: tuple | str, spatial_dims: int | None = 1): return pool_type(**pool_args) -def get_rel_pos_embedding_layer(name: tuple | str, s_input_dims: Optional[tuple], c_dim: int, num_heads: int): +def get_rel_pos_embedding_layer(name: tuple | str, s_input_dims: tuple | None, c_dim: int, num_heads: int): embedding_name, embedding_args = split_args(name) embedding_type = RelPosEmbedding[embedding_name] # create a dictionary with the default values which can be overridden by embedding_args diff --git a/monai/networks/layers/vector_quantizer.py b/monai/networks/layers/vector_quantizer.py index 0ff7143b69..388f93fe2d 100644 --- a/monai/networks/layers/vector_quantizer.py +++ b/monai/networks/layers/vector_quantizer.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Sequence, Tuple +from collections.abc import Sequence import torch from torch import nn @@ -87,7 +87,7 @@ def __init__( range(1, self.spatial_dims + 1) ) - def quantize(self, inputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + def quantize(self, inputs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Given an input it projects it to the quantized space and returns additional tensors needed for EMA loss. @@ -164,7 +164,7 @@ def distributed_synchronization(self, encodings_sum: torch.Tensor, dw: torch.Ten else: pass - def forward(self, inputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + def forward(self, inputs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: flat_input, encodings, encoding_indices = self.quantize(inputs) quantized = self.embed(encoding_indices) @@ -211,7 +211,7 @@ def __init__(self, quantizer: EMAQuantizer): self.perplexity: torch.Tensor = torch.rand(1) - def forward(self, inputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + def forward(self, inputs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: quantized, loss, encoding_indices = self.quantizer(inputs) # Perplexity calculations avg_probs = ( diff --git a/monai/networks/nets/ahnet.py b/monai/networks/nets/ahnet.py index 5e280d7f24..bdacfd23a0 100644 --- a/monai/networks/nets/ahnet.py +++ b/monai/networks/nets/ahnet.py @@ -13,7 +13,6 @@ import math from collections.abc import Sequence -from typing import Union import torch import torch.nn as nn @@ -286,7 +285,7 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: else: for project_module, pool_module in zip(self.project_modules, self.pool_modules): interpolate_size = x.shape[2:] - align_corners: Union[bool, None] = None + align_corners: bool | None = None if self.upsample_mode in ["trilinear", "bilinear"]: align_corners = True output = F.interpolate( diff --git a/monai/networks/nets/autoencoderkl.py b/monai/networks/nets/autoencoderkl.py index f9cec5800e..b5a282a340 100644 --- a/monai/networks/nets/autoencoderkl.py +++ b/monai/networks/nets/autoencoderkl.py @@ -12,7 +12,6 @@ from __future__ import annotations from collections.abc import Sequence -from typing import List import torch import torch.nn as nn @@ -188,7 +187,7 @@ def __init__( self.norm_eps = norm_eps self.attention_levels = attention_levels - blocks: List[nn.Module] = [] + blocks: list[nn.Module] = [] # Initial convolution blocks.append( Convolution( @@ -338,7 +337,7 @@ def __init__( reversed_block_out_channels = list(reversed(channels)) - blocks: List[nn.Module] = [] + blocks: list[nn.Module] = [] # Initial convolution blocks.append( diff --git a/monai/networks/nets/basic_unet.py b/monai/networks/nets/basic_unet.py index b9970d4113..d2a655f981 100644 --- a/monai/networks/nets/basic_unet.py +++ b/monai/networks/nets/basic_unet.py @@ -12,7 +12,6 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Optional import torch import torch.nn as nn @@ -150,7 +149,7 @@ def __init__( self.convs = TwoConv(spatial_dims, cat_chns + up_chns, out_chns, act, norm, bias, dropout) self.is_pad = is_pad - def forward(self, x: torch.Tensor, x_e: Optional[torch.Tensor]): + def forward(self, x: torch.Tensor, x_e: torch.Tensor | None): """ Args: diff --git a/monai/networks/nets/dints.py b/monai/networks/nets/dints.py index 43c0cd031b..18e24373a0 100644 --- a/monai/networks/nets/dints.py +++ b/monai/networks/nets/dints.py @@ -13,7 +13,6 @@ import datetime import warnings -from typing import Optional import numpy as np import torch @@ -41,7 +40,7 @@ class CellInterface(torch.nn.Module): """interface for torchscriptable Cell""" - def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor]) -> torch.Tensor: # type: ignore + def forward(self, x: torch.Tensor, weight: torch.Tensor | None) -> torch.Tensor: # type: ignore pass @@ -175,7 +174,7 @@ def __init__(self, c: int, ops: dict, arch_code_c=None): if arch_c > 0: self.ops.append(ops[op_name](c)) - def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor] = None): + def forward(self, x: torch.Tensor, weight: torch.Tensor | None = None): """ Args: x: input tensor. @@ -303,7 +302,7 @@ def __init__( self.op = MixedOp(c, self.OPS, arch_code_c) - def forward(self, x: torch.Tensor, weight: Optional[torch.Tensor]) -> torch.Tensor: + def forward(self, x: torch.Tensor, weight: torch.Tensor | None) -> torch.Tensor: """ Args: x: input tensor @@ -574,9 +573,8 @@ def __init__( self.num_blocks = num_blocks self.num_depths = num_depths print( - "{} - Length of input patch is recommended to be a multiple of {:d}.".format( - datetime.datetime.now(), 2 ** (num_depths + int(use_downsample)) - ) + f"{datetime.datetime.now()}" + f" - Length of input patch is recommended to be a multiple of {2 ** (num_depths + int(use_downsample)):d}." ) self._spatial_dims = spatial_dims diff --git a/monai/networks/nets/dynunet.py b/monai/networks/nets/dynunet.py index 59e1e4a758..c5b7efd22c 100644 --- a/monai/networks/nets/dynunet.py +++ b/monai/networks/nets/dynunet.py @@ -11,7 +11,8 @@ # isort: dont-add-import: from __future__ import annotations -from typing import List, Optional, Sequence, Tuple, Union +from typing import Optional, Union +from collections.abc import Sequence import torch import torch.nn as nn @@ -32,7 +33,7 @@ class DynUNetSkipLayer(nn.Module): forward passes of the network. """ - heads: Optional[List[torch.Tensor]] + heads: Optional[list[torch.Tensor]] def __init__(self, index, downsample, upsample, next_layer, heads=None, super_head=None): super().__init__() @@ -136,9 +137,9 @@ def __init__( strides: Sequence[Union[Sequence[int], int]], upsample_kernel_size: Sequence[Union[Sequence[int], int]], filters: Optional[Sequence[int]] = None, - dropout: Optional[Union[Tuple, str, float]] = None, - norm_name: Union[Tuple, str] = ("INSTANCE", {"affine": True}), - act_name: Union[Tuple, str] = ("leakyrelu", {"inplace": True, "negative_slope": 0.01}), + dropout: Optional[Union[tuple, str, float]] = None, + norm_name: Union[tuple, str] = ("INSTANCE", {"affine": True}), + act_name: Union[tuple, str] = ("leakyrelu", {"inplace": True, "negative_slope": 0.01}), deep_supervision: bool = False, deep_supr_num: int = 1, res_block: bool = False, @@ -169,7 +170,7 @@ def __init__( self.deep_supervision = deep_supervision self.deep_supr_num = deep_supr_num # initialize the typed list of supervision head outputs so that Torchscript can recognize what's going on - self.heads: List[torch.Tensor] = [torch.rand(1)] * self.deep_supr_num + self.heads: list[torch.Tensor] = [torch.rand(1)] * self.deep_supr_num if self.deep_supervision: self.deep_supervision_heads = self.get_deep_supervision_heads() self.check_deep_supr_num() @@ -323,8 +324,8 @@ def get_upsamples(self): def get_module_list( self, - in_channels: List[int], - out_channels: List[int], + in_channels: list[int], + out_channels: list[int], kernel_size: Sequence[Union[Sequence[int], int]], strides: Sequence[Union[Sequence[int], int]], conv_block: nn.Module, diff --git a/monai/networks/nets/netadapter.py b/monai/networks/nets/netadapter.py index 452c31be37..f87120ba21 100644 --- a/monai/networks/nets/netadapter.py +++ b/monai/networks/nets/netadapter.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Any, Dict +from typing import Any import torch @@ -109,7 +109,7 @@ def forward(self, x): x = self.features(x) if isinstance(x, tuple): x = x[0] # it might be a namedtuple such as torchvision.model.InceptionOutputs - elif torch.jit.isinstance(x, Dict[str, torch.Tensor]): + elif torch.jit.isinstance(x, dict[str, torch.Tensor]): x = x[self.node_name] # torchvision create_feature_extractor if self.pool is not None: x = self.pool(x) diff --git a/monai/networks/nets/quicknat.py b/monai/networks/nets/quicknat.py index 7e0f9c6b38..f82e3d7e78 100644 --- a/monai/networks/nets/quicknat.py +++ b/monai/networks/nets/quicknat.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Optional, Sequence, Tuple, Union +from collections.abc import Sequence import torch import torch.nn as nn @@ -123,8 +123,8 @@ class ConvConcatDenseBlock(ConvDenseBlock): def __init__( self, in_channels: int, - se_layer: Optional[nn.Module] = None, - dropout_layer: Optional[nn.Dropout2d] = None, + se_layer: nn.Module | None = None, + dropout_layer: nn.Dropout2d | None = None, kernel_size: Sequence[int] | int = 5, num_filters: int = 64, ): @@ -360,8 +360,8 @@ def __init__( # Valid options : NONE, CSE, SSE, CSSE se_block: str = "None", drop_out: float = 0, - act: Union[Tuple, str] = Act.PRELU, - norm: Union[Tuple, str] = Norm.INSTANCE, + act: tuple | str = Act.PRELU, + norm: tuple | str = Norm.INSTANCE, adn_ordering: str = "NA", ) -> None: self.act = act diff --git a/monai/networks/nets/resnet.py b/monai/networks/nets/resnet.py index d24b86d27d..9142116ae4 100644 --- a/monai/networks/nets/resnet.py +++ b/monai/networks/nets/resnet.py @@ -240,7 +240,7 @@ def __init__( elif block == "bottleneck": block = ResNetBottleneck else: - raise ValueError("Unknown block '%s', use basic or bottleneck" % block) + raise ValueError(f"Unknown block '{block}', use basic or bottleneck") conv_type: type[nn.Conv1d | nn.Conv2d | nn.Conv3d] = Conv[Conv.CONV, spatial_dims] pool_type: type[nn.MaxPool1d | nn.MaxPool2d | nn.MaxPool3d] = Pool[Pool.MAX, spatial_dims] diff --git a/monai/networks/nets/segresnet_ds.py b/monai/networks/nets/segresnet_ds.py index 8f575f4793..9dda6821d5 100644 --- a/monai/networks/nets/segresnet_ds.py +++ b/monai/networks/nets/segresnet_ds.py @@ -13,7 +13,6 @@ import copy from collections.abc import Callable -from typing import Union import numpy as np import torch @@ -388,7 +387,7 @@ def is_valid_shape(self, x): a = [i % j == 0 for i, j in zip(x.shape[2:], self.shape_factor())] return all(a) - def _forward(self, x: torch.Tensor) -> Union[None, torch.Tensor, list[torch.Tensor]]: + def _forward(self, x: torch.Tensor) -> None | torch.Tensor | list[torch.Tensor]: if self.preprocess is not None: x = self.preprocess(x) @@ -424,7 +423,7 @@ def _forward(self, x: torch.Tensor) -> Union[None, torch.Tensor, list[torch.Tens # return a list of DS outputs return outputs - def forward(self, x: torch.Tensor) -> Union[None, torch.Tensor, list[torch.Tensor]]: + def forward(self, x: torch.Tensor) -> None | torch.Tensor | list[torch.Tensor]: return self._forward(x) @@ -485,7 +484,7 @@ def __init__( def forward( # type: ignore self, x: torch.Tensor, with_point: bool = True, with_label: bool = True - ) -> tuple[Union[None, torch.Tensor, list[torch.Tensor]], Union[None, torch.Tensor, list[torch.Tensor]]]: + ) -> tuple[None | torch.Tensor | list[torch.Tensor], None | torch.Tensor | list[torch.Tensor]]: """ Args: x: input tensor. diff --git a/monai/networks/nets/senet.py b/monai/networks/nets/senet.py index c14118ad20..4c7dd0f0c2 100644 --- a/monai/networks/nets/senet.py +++ b/monai/networks/nets/senet.py @@ -119,7 +119,7 @@ def __init__( block = SEResNeXtBottleneck else: raise ValueError( - "Unknown block '%s', use se_bottleneck, se_resnet_bottleneck or se_resnetxt_bottleneck" % block + f"Unknown block '{block}', use se_bottleneck, se_resnet_bottleneck or se_resnetxt_bottleneck" ) relu_type: type[nn.ReLU] = Act[Act.RELU] diff --git a/monai/networks/nets/spade_network.py b/monai/networks/nets/spade_network.py index 9164541f27..a4707e89eb 100644 --- a/monai/networks/nets/spade_network.py +++ b/monai/networks/nets/spade_network.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Sequence +from collections.abc import Sequence import numpy as np import torch @@ -156,7 +156,7 @@ def __init__( self.z_dim = z_dim self.channels = channels if len(input_shape) != spatial_dims: - raise ValueError("Length of parameter input shape must match spatial_dims; got %s" % (input_shape)) + raise ValueError(f"Length of parameter input shape must match spatial_dims; got {input_shape}") for s_ind, s_ in enumerate(input_shape): if s_ / (2 ** len(channels)) != s_ // (2 ** len(channels)): raise ValueError( @@ -255,7 +255,7 @@ def __init__( self.label_nc = label_nc self.num_channels = channels if len(input_shape) != spatial_dims: - raise ValueError("Length of parameter input shape must match spatial_dims; got %s" % (input_shape)) + raise ValueError(f"Length of parameter input shape must match spatial_dims; got {input_shape}") for s_ind, s_ in enumerate(input_shape): if s_ / (2 ** len(channels)) != s_ // (2 ** len(channels)): raise ValueError( diff --git a/monai/networks/nets/swin_unetr.py b/monai/networks/nets/swin_unetr.py index 4566a96856..b4d93c9afe 100644 --- a/monai/networks/nets/swin_unetr.py +++ b/monai/networks/nets/swin_unetr.py @@ -811,7 +811,7 @@ def compute_mask(dims, window_size, shift_size, device): mask_windows = window_partition(img_mask, window_size) mask_windows = mask_windows.squeeze(-1) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) - attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0) return attn_mask diff --git a/monai/networks/nets/vista3d.py b/monai/networks/nets/vista3d.py index a5c2cc13ef..55d84afe28 100644 --- a/monai/networks/nets/vista3d.py +++ b/monai/networks/nets/vista3d.py @@ -12,7 +12,8 @@ from __future__ import annotations import math -from typing import Any, Callable, Optional, Sequence, Tuple +from typing import Any, Callable +from collections.abc import Sequence import numpy as np import torch @@ -691,7 +692,7 @@ def __init__( def forward( self, image_embedding: torch.Tensor, image_pe: torch.Tensor, point_embedding: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: + ) -> tuple[torch.Tensor, torch.Tensor]: """ Args: image_embedding: image to attend to. Should be shape @@ -768,7 +769,7 @@ def __init__( def forward( self, queries: torch.Tensor, keys: torch.Tensor, query_pe: torch.Tensor, key_pe: torch.Tensor - ) -> Tuple[torch.Tensor, torch.Tensor]: + ) -> tuple[torch.Tensor, torch.Tensor]: # Self attention block if self.skip_first_layer_pe: queries = self.self_attn(q=queries, k=queries, v=queries) @@ -872,7 +873,7 @@ class PositionEmbeddingRandom(nn.Module): scale: the scale of the positional encoding. """ - def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + def __init__(self, num_pos_feats: int = 64, scale: float | None = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 @@ -890,7 +891,7 @@ def _pe_encoding(self, coords: torch.torch.Tensor) -> torch.torch.Tensor: # [bs=1, N=2, 128+128=256] return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) - def forward(self, size: Tuple[int, int, int]) -> torch.torch.Tensor: + def forward(self, size: tuple[int, int, int]) -> torch.torch.Tensor: """Generate positional encoding for a grid of the specified size.""" h, w, d = size device: Any = self.positional_encoding_gaussian_matrix.device @@ -906,7 +907,7 @@ def forward(self, size: Tuple[int, int, int]) -> torch.torch.Tensor: return pe.permute(3, 0, 1, 2) def forward_with_coords( - self, coords_input: torch.torch.Tensor, image_size: Tuple[int, int, int] + self, coords_input: torch.torch.Tensor, image_size: tuple[int, int, int] ) -> torch.torch.Tensor: """Positionally encode points that are not normalized to [0,1].""" coords = coords_input.clone() diff --git a/monai/networks/nets/vqvae.py b/monai/networks/nets/vqvae.py index f198bfbb2b..43ba48585c 100644 --- a/monai/networks/nets/vqvae.py +++ b/monai/networks/nets/vqvae.py @@ -12,7 +12,6 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Tuple import torch import torch.nn as nn @@ -107,7 +106,7 @@ def __init__( channels: Sequence[int], num_res_layers: int, num_res_channels: Sequence[int], - downsample_parameters: Sequence[Tuple[int, int, int, int]], + downsample_parameters: Sequence[tuple[int, int, int, int]], dropout: float, act: tuple | str | None, ) -> None: @@ -198,7 +197,7 @@ def __init__( channels: Sequence[int], num_res_layers: int, num_res_channels: Sequence[int], - upsample_parameters: Sequence[Tuple[int, int, int, int, int]], + upsample_parameters: Sequence[tuple[int, int, int, int, int]], dropout: float, act: tuple | str | None, output_act: tuple | str | None, @@ -312,12 +311,12 @@ def __init__( channels: Sequence[int] = (96, 96, 192), num_res_layers: int = 3, num_res_channels: Sequence[int] | int = (96, 96, 192), - downsample_parameters: Sequence[Tuple[int, int, int, int]] | Tuple[int, int, int, int] = ( + downsample_parameters: Sequence[tuple[int, int, int, int]] | tuple[int, int, int, int] = ( (2, 4, 1, 1), (2, 4, 1, 1), (2, 4, 1, 1), ), - upsample_parameters: Sequence[Tuple[int, int, int, int, int]] | Tuple[int, int, int, int, int] = ( + upsample_parameters: Sequence[tuple[int, int, int, int, int]] | tuple[int, int, int, int, int] = ( (2, 4, 1, 1, 0), (2, 4, 1, 1, 0), (2, 4, 1, 1, 0), diff --git a/monai/networks/schedulers/rectified_flow.py b/monai/networks/schedulers/rectified_flow.py index e660a1abb6..bd0a715f2b 100644 --- a/monai/networks/schedulers/rectified_flow.py +++ b/monai/networks/schedulers/rectified_flow.py @@ -28,7 +28,6 @@ from __future__ import annotations -from typing import Union import numpy as np import torch @@ -283,7 +282,7 @@ def sample_timesteps(self, x_start): return t def step( - self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: Union[int, None] = None + self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor, next_timestep: int | None = None ) -> tuple[torch.Tensor, torch.Tensor]: """ Predicts the next sample in the diffusion process. diff --git a/monai/networks/trt_compiler.py b/monai/networks/trt_compiler.py index d96b712003..2df7189ad4 100644 --- a/monai/networks/trt_compiler.py +++ b/monai/networks/trt_compiler.py @@ -18,7 +18,7 @@ from collections import OrderedDict from pathlib import Path from types import MethodType -from typing import Any, Dict, List, Tuple, Union +from typing import Any import torch @@ -242,8 +242,8 @@ def unroll_input(input_names, input_example): def parse_groups( - ret: List[torch.Tensor], output_lists: List[List[int]] -) -> Tuple[Union[torch.Tensor, List[torch.Tensor]], ...]: + ret: list[torch.Tensor], output_lists: list[list[int]] +) -> tuple[torch.Tensor | list[torch.Tensor], ...]: """ Implements parsing of 'output_lists' arg of trt_compile(). @@ -261,7 +261,7 @@ def parse_groups( Tuple of Union[torch.Tensor, List[torch.Tensor]], according to the grouping in output_lists """ - groups: Tuple[Union[torch.Tensor, List[torch.Tensor]], ...] = tuple() + groups: tuple[torch.Tensor | list[torch.Tensor], ...] = tuple() cur = 0 for l in range(len(output_lists)): gl = output_lists[l] @@ -273,7 +273,7 @@ def parse_groups( groups = (*groups, ret[cur : cur + gl[0]]) cur = cur + gl[0] elif gl[0] == -1: - rev_groups: Tuple[Union[torch.Tensor, List[torch.Tensor]], ...] = tuple() + rev_groups: tuple[torch.Tensor | list[torch.Tensor], ...] = tuple() rcur = len(ret) for rl in range(len(output_lists) - 1, l, -1): rgl = output_lists[rl] @@ -601,8 +601,8 @@ def trt_forward(self, *argv, **kwargs): def trt_compile( model: torch.nn.Module, base_path: str, - args: Dict[str, Any] | None = None, - submodule: Union[str, List[str]] | None = None, + args: dict[str, Any] | None = None, + submodule: str | list[str] | None = None, logger: Any | None = None, ) -> torch.nn.Module: """ @@ -625,7 +625,7 @@ def trt_compile( Always returns same model passed in as argument. This is for ease of use in configs. """ - default_args: Dict[str, Any] = { + default_args: dict[str, Any] = { "method": "onnx", "precision": "fp16", "build_args": {"builder_optimization_level": 5, "precision_constraints": "obey"}, diff --git a/monai/networks/utils.py b/monai/networks/utils.py index df91c84bdf..4f444bb100 100644 --- a/monai/networks/utils.py +++ b/monai/networks/utils.py @@ -22,7 +22,8 @@ from collections.abc import Callable, Mapping, Sequence from contextlib import contextmanager from copy import deepcopy -from typing import Any, Iterable +from typing import Any +from collections.abc import Iterable import numpy as np import torch From 623865492618d4a1c787809d9ce269ba0790a58f Mon Sep 17 00:00:00 2001 From: jirka Date: Sun, 9 Nov 2025 10:40:58 +0100 Subject: [PATCH 12/12] ./runtests.sh --autofix Signed-off-by: jirka --- monai/losses/ds_loss.py | 1 - monai/losses/perceptual.py | 4 +++- monai/metrics/utils.py | 2 +- monai/networks/blocks/attention_utils.py | 1 - monai/networks/blocks/crossattention.py | 1 - monai/networks/blocks/mlp.py | 1 - monai/networks/blocks/selfattention.py | 1 - monai/networks/blocks/spatialattention.py | 1 - monai/networks/blocks/transformerblock.py | 1 - monai/networks/layers/simplelayers.py | 2 +- monai/networks/layers/utils.py | 1 - monai/networks/nets/dynunet.py | 2 +- monai/networks/nets/vista3d.py | 2 +- monai/networks/schedulers/rectified_flow.py | 1 - monai/networks/utils.py | 3 +-- 15 files changed, 8 insertions(+), 16 deletions(-) diff --git a/monai/losses/ds_loss.py b/monai/losses/ds_loss.py index ef359bcfd0..7e6fcf7e3c 100644 --- a/monai/losses/ds_loss.py +++ b/monai/losses/ds_loss.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch import torch.nn.functional as F from torch.nn.modules.loss import _Loss diff --git a/monai/losses/perceptual.py b/monai/losses/perceptual.py index 7774c39f10..aed1f26b86 100644 --- a/monai/losses/perceptual.py +++ b/monai/losses/perceptual.py @@ -95,7 +95,9 @@ def __init__( if network_type.lower() not in list(PercetualNetworkType): raise ValueError( - "Unrecognised criterion entered for Perceptual Loss. Must be one in: {}".format(", ".join(PercetualNetworkType)) + "Unrecognised criterion entered for Perceptual Loss. Must be one in: {}".format( + ", ".join(PercetualNetworkType) + ) ) if cache_dir: diff --git a/monai/metrics/utils.py b/monai/metrics/utils.py index 606a54669b..a451b1a770 100644 --- a/monai/metrics/utils.py +++ b/monai/metrics/utils.py @@ -13,7 +13,7 @@ import warnings from collections.abc import Iterable, Sequence -from functools import partial, cache +from functools import cache, partial from types import ModuleType from typing import Any diff --git a/monai/networks/blocks/attention_utils.py b/monai/networks/blocks/attention_utils.py index c5666d7728..a8dfcd7df3 100644 --- a/monai/networks/blocks/attention_utils.py +++ b/monai/networks/blocks/attention_utils.py @@ -9,7 +9,6 @@ from __future__ import annotations - import torch import torch.nn.functional as F from torch import nn diff --git a/monai/networks/blocks/crossattention.py b/monai/networks/blocks/crossattention.py index e00ff406b6..baaa21ed1f 100644 --- a/monai/networks/blocks/crossattention.py +++ b/monai/networks/blocks/crossattention.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch import torch.nn as nn diff --git a/monai/networks/blocks/mlp.py b/monai/networks/blocks/mlp.py index aee76846e3..84c8065531 100644 --- a/monai/networks/blocks/mlp.py +++ b/monai/networks/blocks/mlp.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch.nn as nn from monai.networks.layers import get_act_layer diff --git a/monai/networks/blocks/selfattention.py b/monai/networks/blocks/selfattention.py index 0bca6a24bd..2791d2fb00 100644 --- a/monai/networks/blocks/selfattention.py +++ b/monai/networks/blocks/selfattention.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch import torch.nn as nn import torch.nn.functional as F diff --git a/monai/networks/blocks/spatialattention.py b/monai/networks/blocks/spatialattention.py index 52513c961b..40fb36160b 100644 --- a/monai/networks/blocks/spatialattention.py +++ b/monai/networks/blocks/spatialattention.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch import torch.nn as nn diff --git a/monai/networks/blocks/transformerblock.py b/monai/networks/blocks/transformerblock.py index 0fd656b2b6..b93d81bdef 100644 --- a/monai/networks/blocks/transformerblock.py +++ b/monai/networks/blocks/transformerblock.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch import torch.nn as nn diff --git a/monai/networks/layers/simplelayers.py b/monai/networks/layers/simplelayers.py index ab5cad2b92..56f7192e4d 100644 --- a/monai/networks/layers/simplelayers.py +++ b/monai/networks/layers/simplelayers.py @@ -12,8 +12,8 @@ from __future__ import annotations import math -from copy import deepcopy from collections.abc import Sequence +from copy import deepcopy import torch import torch.nn.functional as F diff --git a/monai/networks/layers/utils.py b/monai/networks/layers/utils.py index c76eab934b..4f8cfb225e 100644 --- a/monai/networks/layers/utils.py +++ b/monai/networks/layers/utils.py @@ -11,7 +11,6 @@ from __future__ import annotations - import torch.nn from monai.networks.layers.factories import Act, Dropout, Norm, Pool, RelPosEmbedding, split_args diff --git a/monai/networks/nets/dynunet.py b/monai/networks/nets/dynunet.py index c5b7efd22c..ec418469bb 100644 --- a/monai/networks/nets/dynunet.py +++ b/monai/networks/nets/dynunet.py @@ -11,8 +11,8 @@ # isort: dont-add-import: from __future__ import annotations -from typing import Optional, Union from collections.abc import Sequence +from typing import Optional, Union import torch import torch.nn as nn diff --git a/monai/networks/nets/vista3d.py b/monai/networks/nets/vista3d.py index 55d84afe28..93bdb34a76 100644 --- a/monai/networks/nets/vista3d.py +++ b/monai/networks/nets/vista3d.py @@ -12,8 +12,8 @@ from __future__ import annotations import math -from typing import Any, Callable from collections.abc import Sequence +from typing import Any, Callable import numpy as np import torch diff --git a/monai/networks/schedulers/rectified_flow.py b/monai/networks/schedulers/rectified_flow.py index bd0a715f2b..f090ebc1e8 100644 --- a/monai/networks/schedulers/rectified_flow.py +++ b/monai/networks/schedulers/rectified_flow.py @@ -28,7 +28,6 @@ from __future__ import annotations - import numpy as np import torch from torch.distributions import LogisticNormal diff --git a/monai/networks/utils.py b/monai/networks/utils.py index 4f444bb100..a4a006f97c 100644 --- a/monai/networks/utils.py +++ b/monai/networks/utils.py @@ -19,11 +19,10 @@ import tempfile import warnings from collections import OrderedDict -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from contextlib import contextmanager from copy import deepcopy from typing import Any -from collections.abc import Iterable import numpy as np import torch