diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 298be9062c..5419004a9e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -37,7 +37,7 @@ repos: rev: v3.18.0 hooks: - id: pyupgrade - args: [--py38-plus, --keep-runtime-typing] + args: [--py39-plus, --keep-runtime-typing] name: Upgrade code with exceptions exclude: | (?x)( diff --git a/monai/apps/detection/networks/retinanet_network.py b/monai/apps/detection/networks/retinanet_network.py index ec86c3b0e9..ca6a8f5c19 100644 --- a/monai/apps/detection/networks/retinanet_network.py +++ b/monai/apps/detection/networks/retinanet_network.py @@ -42,7 +42,7 @@ import math import warnings from collections.abc import Callable, Sequence -from typing import Any, Dict +from typing import Any import torch from torch import Tensor, nn @@ -330,7 +330,7 @@ def forward(self, images: Tensor) -> Any: features = self.feature_extractor(images) if isinstance(features, Tensor): feature_maps = [features] - elif torch.jit.isinstance(features, Dict[str, Tensor]): + elif torch.jit.isinstance(features, dict[str, Tensor]): feature_maps = list(features.values()) else: feature_maps = list(features) diff --git a/monai/apps/detection/transforms/array.py b/monai/apps/detection/transforms/array.py index d8ffce4584..6b92572954 100644 --- a/monai/apps/detection/transforms/array.py +++ b/monai/apps/detection/transforms/array.py @@ -15,7 +15,9 @@ from __future__ import annotations -from typing import Any, Sequence +from typing import Any + +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/apps/detection/utils/anchor_utils.py b/monai/apps/detection/utils/anchor_utils.py index cbde3ebae9..145350853a 100644 --- a/monai/apps/detection/utils/anchor_utils.py +++ b/monai/apps/detection/utils/anchor_utils.py @@ -39,7 +39,8 @@ from __future__ import annotations -from typing import List, Sequence + +from collections.abc import Sequence import torch from torch import Tensor, nn @@ -106,7 +107,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 +365,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/apps/generation/maisi/networks/autoencoderkl_maisi.py b/monai/apps/generation/maisi/networks/autoencoderkl_maisi.py index a52274b24a..6251ea8e83 100644 --- a/monai/apps/generation/maisi/networks/autoencoderkl_maisi.py +++ b/monai/apps/generation/maisi/networks/autoencoderkl_maisi.py @@ -13,7 +13,7 @@ import gc import logging -from typing import Sequence +from collections.abc import Sequence import torch import torch.nn as nn diff --git a/monai/apps/generation/maisi/networks/controlnet_maisi.py b/monai/apps/generation/maisi/networks/controlnet_maisi.py index 269086d971..7c13fd7bc6 100644 --- a/monai/apps/generation/maisi/networks/controlnet_maisi.py +++ b/monai/apps/generation/maisi/networks/controlnet_maisi.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Sequence +from collections.abc import Sequence import torch diff --git a/monai/apps/pathology/engines/utils.py b/monai/apps/pathology/engines/utils.py index 02249ed640..c704dc7469 100644 --- a/monai/apps/pathology/engines/utils.py +++ b/monai/apps/pathology/engines/utils.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import Any, Sequence +from typing import Any + +from collections.abc import Sequence import torch diff --git a/monai/apps/pathology/inferers/inferer.py b/monai/apps/pathology/inferers/inferer.py index 71259ca7df..4f034f0ad1 100644 --- a/monai/apps/pathology/inferers/inferer.py +++ b/monai/apps/pathology/inferers/inferer.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import Any, Callable, Sequence +from typing import Any, Callable + +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/apps/pathology/metrics/lesion_froc.py b/monai/apps/pathology/metrics/lesion_froc.py index f4bf51ab28..bbd7bf4905 100644 --- a/monai/apps/pathology/metrics/lesion_froc.py +++ b/monai/apps/pathology/metrics/lesion_froc.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Iterable +from typing import TYPE_CHECKING, Any + +from collections.abc import Iterable import numpy as np diff --git a/monai/apps/pathology/transforms/post/array.py b/monai/apps/pathology/transforms/post/array.py index 035bce2c69..bb50ee4fd9 100644 --- a/monai/apps/pathology/transforms/post/array.py +++ b/monai/apps/pathology/transforms/post/array.py @@ -12,7 +12,9 @@ from __future__ import annotations import warnings -from typing import Callable, Sequence +from typing import Callable + +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/apps/tcia/utils.py b/monai/apps/tcia/utils.py index 5524b488e9..f023cdbc87 100644 --- a/monai/apps/tcia/utils.py +++ b/monai/apps/tcia/utils.py @@ -12,7 +12,7 @@ from __future__ import annotations import os -from typing import Iterable +from collections.abc import Iterable import monai from monai.config.type_definitions import PathLike diff --git a/monai/apps/utils.py b/monai/apps/utils.py index 0c998146a3..c2e17d3247 100644 --- a/monai/apps/utils.py +++ b/monai/apps/utils.py @@ -136,10 +136,7 @@ def check_hash(filepath: PathLike, val: str | None = None, hash_type: str = "md5 return True actual_hash_func = look_up_option(hash_type.lower(), SUPPORTED_HASH_TYPES) - if sys.version_info >= (3, 9): - actual_hash = actual_hash_func(usedforsecurity=False) # allows checks on FIPS enabled machines - else: - actual_hash = actual_hash_func() + actual_hash = actual_hash_func(usedforsecurity=False) # allows checks on FIPS enabled machines try: with open(filepath, "rb") as f: diff --git a/monai/apps/vista3d/transforms.py b/monai/apps/vista3d/transforms.py index 3e8145cd80..bd7fb19493 100644 --- a/monai/apps/vista3d/transforms.py +++ b/monai/apps/vista3d/transforms.py @@ -12,7 +12,7 @@ from __future__ import annotations import warnings -from typing import Sequence +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/bundle/reference_resolver.py b/monai/bundle/reference_resolver.py index 050cd75fa7..6c5ca776f5 100644 --- a/monai/bundle/reference_resolver.py +++ b/monai/bundle/reference_resolver.py @@ -14,7 +14,9 @@ import re import warnings from collections.abc import Sequence -from typing import Any, Iterator +from typing import Any + +from collections.abc import Iterator from monai.bundle.config_item import ConfigComponent, ConfigExpression, ConfigItem from monai.bundle.utils import DEPRECATED_ID_MAPPING, ID_REF_KEY, ID_SEP_KEY diff --git a/monai/bundle/workflows.py b/monai/bundle/workflows.py index ccdb08e208..f425d8fd28 100644 --- a/monai/bundle/workflows.py +++ b/monai/bundle/workflows.py @@ -19,7 +19,9 @@ from copy import copy from logging.config import fileConfig from pathlib import Path -from typing import Any, Sequence +from typing import Any + +from collections.abc import Sequence from monai.apps.utils import get_logger from monai.bundle.config_parser import ConfigParser diff --git a/monai/config/type_definitions.py b/monai/config/type_definitions.py index 57454a94e1..cf6a2957ee 100644 --- a/monai/config/type_definitions.py +++ b/monai/config/type_definitions.py @@ -12,7 +12,9 @@ from __future__ import annotations import os -from typing import Collection, Hashable, Iterable, Sequence, TypeVar, Union +from typing import TypeVar, Union + +from collections.abc import Collection, Hashable, Iterable, Sequence import numpy as np import torch diff --git a/monai/data/meta_obj.py b/monai/data/meta_obj.py index 0dccaa9e1c..d951d69b04 100644 --- a/monai/data/meta_obj.py +++ b/monai/data/meta_obj.py @@ -14,7 +14,9 @@ import itertools import pprint from copy import deepcopy -from typing import Any, Iterable +from typing import Any + +from collections.abc import Iterable import numpy as np import torch diff --git a/monai/data/meta_tensor.py b/monai/data/meta_tensor.py index 2df4da4a35..88e55c74da 100644 --- a/monai/data/meta_tensor.py +++ b/monai/data/meta_tensor.py @@ -14,7 +14,9 @@ import functools import warnings from copy import deepcopy -from typing import Any, Sequence +from typing import Any + +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/engines/evaluator.py b/monai/engines/evaluator.py index 523c3dcbf6..8c0972ae7f 100644 --- a/monai/engines/evaluator.py +++ b/monai/engines/evaluator.py @@ -12,7 +12,9 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence +from typing import TYPE_CHECKING, Any, Callable + +from collections.abc import Iterable, Sequence import torch from torch.utils.data import DataLoader diff --git a/monai/engines/trainer.py b/monai/engines/trainer.py index bbcc9c880b..0ca9d40a26 100644 --- a/monai/engines/trainer.py +++ b/monai/engines/trainer.py @@ -12,7 +12,9 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence +from typing import TYPE_CHECKING, Any, Callable + +from collections.abc import Iterable, Sequence import torch from torch.optim.optimizer import Optimizer diff --git a/monai/engines/utils.py b/monai/engines/utils.py index 11a0000989..74612f7116 100644 --- a/monai/engines/utils.py +++ b/monai/engines/utils.py @@ -13,7 +13,9 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Sequence -from typing import TYPE_CHECKING, Any, Mapping, cast +from typing import TYPE_CHECKING, Any, cast + +from collections.abc import Mapping import torch import torch.nn as nn diff --git a/monai/handlers/clearml_handlers.py b/monai/handlers/clearml_handlers.py index 1cfd6a33fb..11f9dca24f 100644 --- a/monai/handlers/clearml_handlers.py +++ b/monai/handlers/clearml_handlers.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Mapping, Sequence +from typing import TYPE_CHECKING, Any + +from collections.abc import Mapping, Sequence from monai.utils import optional_import diff --git a/monai/inferers/utils.py b/monai/inferers/utils.py index bd99765348..8bb2941529 100644 --- a/monai/inferers/utils.py +++ b/monai/inferers/utils.py @@ -13,7 +13,9 @@ import itertools from collections.abc import Callable, Mapping, Sequence -from typing import Any, Iterable +from typing import Any + +from collections.abc import Iterable import numpy as np import torch diff --git a/monai/metrics/utils.py b/monai/metrics/utils.py index 340e54a1d7..43bd5a3483 100644 --- a/monai/metrics/utils.py +++ b/monai/metrics/utils.py @@ -14,7 +14,9 @@ import warnings from functools import lru_cache, partial from types import ModuleType -from typing import Any, Iterable, Sequence +from typing import Any + +from collections.abc import Iterable, Sequence import numpy as np import torch 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 bdecf63168..f2bb311288 100644 --- a/monai/networks/blocks/crossattention.py +++ b/monai/networks/blocks/crossattention.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Optional, Tuple +from typing import Optional import torch import torch.nn as nn @@ -42,7 +42,7 @@ def __init__( causal: bool = False, sequence_length: int | None = None, rel_pos_embedding: Optional[str] = None, - input_size: Optional[Tuple] = None, + input_size: Optional[tuple] = None, attention_dtype: Optional[torch.dtype] = None, use_flash_attention: bool = False, ) -> None: 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/pos_embed_utils.py b/monai/networks/blocks/pos_embed_utils.py index 21586e56da..1bda4d8aea 100644 --- a/monai/networks/blocks/pos_embed_utils.py +++ b/monai/networks/blocks/pos_embed_utils.py @@ -13,7 +13,7 @@ import collections.abc from itertools import repeat -from typing import List, Union +from typing import Union import torch import torch.nn as nn @@ -33,7 +33,7 @@ def parse(x): def build_sincos_position_embedding( - grid_size: Union[int, List[int]], embed_dim: int, spatial_dims: int = 3, temperature: float = 10000.0 + grid_size: Union[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..c7546bdb4e 100644 --- a/monai/networks/blocks/rel_pos_embedding.py +++ b/monai/networks/blocks/rel_pos_embedding.py @@ -9,7 +9,8 @@ from __future__ import annotations -from typing import Iterable, Tuple + +from collections.abc import Iterable import torch from torch import nn @@ -19,7 +20,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 ac96b077bd..f582fa68aa 100644 --- a/monai/networks/blocks/selfattention.py +++ b/monai/networks/blocks/selfattention.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Tuple, Union +from typing import Union import torch import torch.nn as nn @@ -41,7 +41,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, diff --git a/monai/networks/layers/simplelayers.py b/monai/networks/layers/simplelayers.py index 4acd4a3622..98417f17aa 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/vector_quantizer.py b/monai/networks/layers/vector_quantizer.py index 9c354e1009..a865650c44 100644 --- a/monai/networks/layers/vector_quantizer.py +++ b/monai/networks/layers/vector_quantizer.py @@ -11,7 +11,8 @@ from __future__ import annotations -from typing import Sequence, Tuple + +from collections.abc import Sequence import torch from torch import nn @@ -87,7 +88,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 +165,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 +212,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/autoencoderkl.py b/monai/networks/nets/autoencoderkl.py index af191e748b..a5914d687a 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/dynunet.py b/monai/networks/nets/dynunet.py index a2a133a24c..6c87387bd2 100644 --- a/monai/networks/nets/dynunet.py +++ b/monai/networks/nets/dynunet.py @@ -11,7 +11,9 @@ # 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 +34,7 @@ class DynUNetSkipLayer(nn.Module): forward passes of the network. """ - heads: Union[None, List[torch.Tensor]] + heads: Union[None, list[torch.Tensor]] def __init__(self, index, downsample, upsample, next_layer, heads=None, super_head=None): super().__init__() @@ -136,9 +138,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 +171,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 +325,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..ceeb4b863e 100644 --- a/monai/networks/nets/quicknat.py +++ b/monai/networks/nets/quicknat.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import Optional, Sequence, Tuple, Union +from typing import Optional, Union + +from collections.abc import Sequence import torch import torch.nn as nn @@ -360,8 +362,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: Union[tuple, str] = Act.PRELU, + norm: Union[tuple, str] = Norm.INSTANCE, adn_ordering: str = "NA", ) -> None: self.act = act diff --git a/monai/networks/nets/spade_network.py b/monai/networks/nets/spade_network.py index 9164541f27..e00ca47e45 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 diff --git a/monai/networks/nets/vista3d.py b/monai/networks/nets/vista3d.py index 6313b7812d..fa426a40c2 100644 --- a/monai/networks/nets/vista3d.py +++ b/monai/networks/nets/vista3d.py @@ -12,7 +12,9 @@ from __future__ import annotations import math -from typing import Any, Callable, Optional, Sequence, Tuple +from typing import Any, Callable, Optional + +from collections.abc import Sequence import numpy as np import torch @@ -692,7 +694,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 @@ -769,7 +771,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) @@ -891,7 +893,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 @@ -907,7 +909,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/trt_compiler.py b/monai/networks/trt_compiler.py index a360f63dbd..d29e20084c 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, Union +from typing import Any, Union import torch @@ -499,8 +499,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: Union[str, list[str]] | None = None, logger: Any | None = None, ) -> torch.nn.Module: """ @@ -521,7 +521,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/transforms/intensity/dictionary.py b/monai/transforms/intensity/dictionary.py index 5dbac485fe..c5e7add79d 100644 --- a/monai/transforms/intensity/dictionary.py +++ b/monai/transforms/intensity/dictionary.py @@ -17,7 +17,9 @@ from __future__ import annotations -from typing import Callable, Hashable, Mapping, Sequence +from typing import Callable + +from collections.abc import Hashable, Mapping, Sequence import numpy as np diff --git a/monai/transforms/lazy/functional.py b/monai/transforms/lazy/functional.py index 6b95027832..518c74e414 100644 --- a/monai/transforms/lazy/functional.py +++ b/monai/transforms/lazy/functional.py @@ -11,7 +11,9 @@ from __future__ import annotations -from typing import Any, Mapping, Sequence +from typing import Any + +from collections.abc import Mapping, Sequence import torch diff --git a/monai/transforms/spatial/array.py b/monai/transforms/spatial/array.py index 6e39fb2e19..18ea0da23b 100644 --- a/monai/transforms/spatial/array.py +++ b/monai/transforms/spatial/array.py @@ -18,7 +18,9 @@ from collections.abc import Callable from copy import deepcopy from itertools import zip_longest -from typing import Any, Optional, Sequence, Tuple, Union, cast +from typing import Any, Optional, Union, cast + +from collections.abc import Sequence import numpy as np import torch @@ -116,7 +118,7 @@ "RandSimulateLowResolution", ] -RandRange = Optional[Union[Sequence[Union[Tuple[float, float], float]], float]] +RandRange = Optional[Union[Sequence[Union[tuple[float, float], float]], float]] class SpatialResample(InvertibleTransform, LazyTransform): diff --git a/monai/transforms/utility/dictionary.py b/monai/transforms/utility/dictionary.py index 79d0be522d..da43914aba 100644 --- a/monai/transforms/utility/dictionary.py +++ b/monai/transforms/utility/dictionary.py @@ -20,7 +20,9 @@ import re from collections.abc import Callable, Hashable, Mapping from copy import deepcopy -from typing import Any, Sequence, cast +from typing import Any, cast + +from collections.abc import Sequence import numpy as np import torch diff --git a/monai/transforms/utils_morphological_ops.py b/monai/transforms/utils_morphological_ops.py index b3134c1865..61d3c5b858 100644 --- a/monai/transforms/utils_morphological_ops.py +++ b/monai/transforms/utils_morphological_ops.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import Sequence +from collections.abc import Sequence import torch import torch.nn.functional as F diff --git a/monai/utils/component_store.py b/monai/utils/component_store.py index d1e71eaebf..44be6efe94 100644 --- a/monai/utils/component_store.py +++ b/monai/utils/component_store.py @@ -14,7 +14,9 @@ from collections import namedtuple from keyword import iskeyword from textwrap import dedent, indent -from typing import Any, Callable, Iterable, TypeVar +from typing import Any, Callable, TypeVar + +from collections.abc import Iterable T = TypeVar("T") diff --git a/monai/utils/decorators.py b/monai/utils/decorators.py index 1c064468e8..0c3bf6ba6f 100644 --- a/monai/utils/decorators.py +++ b/monai/utils/decorators.py @@ -15,7 +15,9 @@ __all__ = ["RestartGenerator", "MethodReplacer"] -from typing import Callable, Generator +from typing import Callable + +from collections.abc import Generator class RestartGenerator: diff --git a/monai/utils/module.py b/monai/utils/module.py index df5fe873ae..f2acb28119 100644 --- a/monai/utils/module.py +++ b/monai/utils/module.py @@ -25,7 +25,9 @@ from pydoc import locate from re import match from types import FunctionType, ModuleType -from typing import Any, Iterable, cast +from typing import Any, cast + +from collections.abc import Iterable import torch diff --git a/monai/utils/state_cacher.py b/monai/utils/state_cacher.py index d37e7abde4..255e15a7e4 100644 --- a/monai/utils/state_cacher.py +++ b/monai/utils/state_cacher.py @@ -16,7 +16,9 @@ import pickle import tempfile from types import ModuleType -from typing import Any, Hashable +from typing import Any + +from collections.abc import Hashable import torch from torch.serialization import DEFAULT_PROTOCOL diff --git a/tests/test_compute_panoptic_quality.py b/tests/test_compute_panoptic_quality.py index a916ea32b2..a915eb64f9 100644 --- a/tests/test_compute_panoptic_quality.py +++ b/tests/test_compute_panoptic_quality.py @@ -12,7 +12,6 @@ from __future__ import annotations import unittest -from typing import List import numpy as np import torch @@ -104,7 +103,7 @@ def test_value_class(self, input_params, y_pred, y_gt, expected_value): metric = PanopticQualityMetric(**input_params) metric(y_pred, y_gt) outputs = metric.aggregate() - if isinstance(outputs, List): + if isinstance(outputs, list): for output, value in zip(outputs, expected_value): np.testing.assert_allclose(output.cpu().numpy(), np.asarray(value), atol=1e-4) else: diff --git a/tests/test_dynunet.py b/tests/test_dynunet.py index f3c982056c..e173049a95 100644 --- a/tests/test_dynunet.py +++ b/tests/test_dynunet.py @@ -13,7 +13,9 @@ import platform import unittest -from typing import Any, Sequence +from typing import Any + +from collections.abc import Sequence import torch from parameterized import parameterized diff --git a/tests/test_network_consistency.py b/tests/test_network_consistency.py index 4182501808..6949bb359f 100644 --- a/tests/test_network_consistency.py +++ b/tests/test_network_consistency.py @@ -15,7 +15,7 @@ import os import unittest from glob import glob -from typing import Sequence +from collections.abc import Sequence from unittest.case import skipIf import torch