From 45fa3e44a22cd0b74071237304bdfef97b5b9bd6 Mon Sep 17 00:00:00 2001 From: Zaida Zhou <58739961+zhouzaida@users.noreply.github.com> Date: Wed, 18 May 2022 11:47:14 +0800 Subject: [PATCH] Add pyupgrade pre-commit hook (#1937) * add pyupgrade * add options for pyupgrade * minor refinement --- .dev_scripts/visualize_lr.py | 6 +- .pre-commit-config.yaml | 6 +- docs/en/conf.py | 2 +- docs/zh_cn/conf.py | 2 +- examples/train.py | 2 +- mmcv/cnn/alexnet.py | 2 +- mmcv/cnn/bricks/activation.py | 2 +- mmcv/cnn/bricks/context_block.py | 2 +- mmcv/cnn/bricks/conv_module.py | 4 +- mmcv/cnn/bricks/conv_ws.py | 2 +- .../bricks/depthwise_separable_conv_module.py | 2 +- mmcv/cnn/bricks/drop.py | 2 +- mmcv/cnn/bricks/generalized_attention.py | 2 +- mmcv/cnn/bricks/hsigmoid.py | 2 +- mmcv/cnn/bricks/hswish.py | 2 +- mmcv/cnn/bricks/non_local.py | 11 +-- mmcv/cnn/bricks/scale.py | 2 +- mmcv/cnn/bricks/swish.py | 2 +- mmcv/cnn/bricks/transformer.py | 16 ++-- mmcv/cnn/bricks/upsample.py | 2 +- mmcv/cnn/resnet.py | 8 +- mmcv/cnn/utils/flops_counter.py | 4 +- mmcv/cnn/utils/weight_init.py | 4 +- mmcv/cnn/vgg.py | 4 +- mmcv/device/mlu/data_parallel.py | 2 +- mmcv/fileio/file_client.py | 32 ++++---- mmcv/fileio/handlers/pickle_handler.py | 6 +- mmcv/image/geometric.py | 2 +- mmcv/onnx/onnx_utils/symbolic_helper.py | 2 +- mmcv/ops/border_align.py | 2 +- mmcv/ops/box_iou_rotated.py | 2 +- mmcv/ops/carafe.py | 6 +- mmcv/ops/corner_pool.py | 2 +- mmcv/ops/deform_conv.py | 4 +- mmcv/ops/deform_roi_pool.py | 8 +- mmcv/ops/focal_loss.py | 4 +- mmcv/ops/fused_bias_leakyrelu.py | 2 +- mmcv/ops/masked_conv.py | 7 +- mmcv/ops/merge_cells.py | 7 +- mmcv/ops/modulated_deform_conv.py | 6 +- mmcv/ops/point_sample.py | 2 +- mmcv/ops/psa_mask.py | 2 +- mmcv/ops/riroi_align_rotated.py | 2 +- mmcv/ops/roi_align.py | 2 +- mmcv/ops/roi_align_rotated.py | 2 +- mmcv/ops/roi_pool.py | 2 +- mmcv/ops/sparse_conv.py | 22 ++--- mmcv/ops/sparse_modules.py | 4 +- mmcv/ops/sparse_pool.py | 8 +- mmcv/ops/sparse_structure.py | 2 +- mmcv/ops/sync_bn.py | 2 +- mmcv/parallel/data_parallel.py | 2 +- mmcv/parallel/distributed_deprecated.py | 2 +- mmcv/runner/base_module.py | 2 +- mmcv/runner/hooks/checkpoint.py | 10 +-- mmcv/runner/hooks/evaluation.py | 8 +- mmcv/runner/hooks/logger/clearml.py | 5 +- mmcv/runner/hooks/logger/mlflow.py | 5 +- mmcv/runner/hooks/logger/neptune.py | 3 +- mmcv/runner/hooks/logger/pavi.py | 5 +- mmcv/runner/hooks/logger/segmind.py | 3 +- mmcv/runner/hooks/logger/tensorboard.py | 5 +- mmcv/runner/hooks/logger/text.py | 19 +++-- mmcv/runner/hooks/logger/wandb.py | 5 +- mmcv/runner/hooks/lr_updater.py | 24 +++--- mmcv/runner/hooks/momentum_updater.py | 12 +-- mmcv/runner/hooks/optimizer.py | 8 +- mmcv/runner/iter_based_runner.py | 2 +- mmcv/tensorrt/tensorrt_utils.py | 4 +- mmcv/utils/config.py | 34 ++++---- mmcv/utils/timer.py | 2 +- mmcv/video/optflow.py | 10 +-- mmcv/visualization/optflow.py | 1 - setup.py | 7 +- tests/test_arraymisc.py | 1 - tests/test_cnn/test_conv_module.py | 2 +- tests/test_fileclient.py | 80 +++++++++---------- tests/test_fileio.py | 2 +- tests/test_ops/test_bbox.py | 2 +- tests/test_ops/test_bilinear_grid_sample.py | 2 +- tests/test_ops/test_box_iou_rotated.py | 2 +- tests/test_ops/test_carafe.py | 2 +- tests/test_ops/test_cc_attention.py | 2 +- tests/test_ops/test_deform_conv.py | 2 +- tests/test_ops/test_deform_roi_pool.py | 2 +- tests/test_ops/test_focal_loss.py | 2 +- tests/test_ops/test_fused_bias_leakyrelu.py | 2 +- tests/test_ops/test_info.py | 2 +- tests/test_ops/test_masked_conv2d.py | 2 +- tests/test_ops/test_modulated_deform_conv.py | 2 +- tests/test_ops/test_ms_deformable_attn.py | 8 +- tests/test_ops/test_nms.py | 5 +- tests/test_ops/test_onnx.py | 4 +- tests/test_ops/test_psa_mask.py | 2 +- tests/test_ops/test_roi_pool.py | 2 +- tests/test_ops/test_syncbn.py | 2 +- tests/test_ops/test_tensorrt.py | 6 +- tests/test_ops/test_upfirdn2d.py | 2 +- tests/test_ops/test_voxelization.py | 10 +-- tests/test_parallel.py | 2 +- tests/test_runner/test_basemodule.py | 8 +- tests/test_runner/test_checkpoint.py | 12 +-- tests/test_runner/test_fp16.py | 4 +- tests/test_utils/test_config.py | 34 ++++---- tests/test_utils/test_logging.py | 2 +- tests/test_utils/test_parrots_jit.py | 4 +- tests/test_utils/test_path.py | 48 ++++++----- tests/test_utils/test_progressbar.py | 14 +--- tests/test_utils/test_testing.py | 4 +- tests/test_utils/test_version_utils.py | 2 +- 110 files changed, 339 insertions(+), 360 deletions(-) diff --git a/.dev_scripts/visualize_lr.py b/.dev_scripts/visualize_lr.py index aaf01f224..5ca9aaa11 100644 --- a/.dev_scripts/visualize_lr.py +++ b/.dev_scripts/visualize_lr.py @@ -42,7 +42,7 @@ def parse_args(): class SimpleModel(nn.Module): def __init__(self): - super(SimpleModel, self).__init__() + super().__init__() self.conv = nn.Conv2d(1, 1, 1) def train_step(self, *args, **kwargs): @@ -159,13 +159,13 @@ def run(cfg, logger): def plot_lr_curve(json_file, cfg): data_dict = dict(LearningRate=[], Momentum=[]) assert os.path.isfile(json_file) - with open(json_file, 'r') as f: + with open(json_file) as f: for line in f: log = json.loads(line.strip()) data_dict['LearningRate'].append(log['lr']) data_dict['Momentum'].append(log['momentum']) - wind_w, wind_h = [int(size) for size in cfg.window_size.split('*')] + wind_w, wind_h = (int(size) for size in cfg.window_size.split('*')) # if legend is None, use {filename}_{key} as legend fig, axes = plt.subplots(2, 1, figsize=(wind_w, wind_h)) plt.subplots_adjust(hspace=0.5) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d2dc91452..d10e61a23 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -43,7 +43,11 @@ repos: hooks: - id: docformatter args: ["--in-place", "--wrap-descriptions", "79"] - + - repo: https://github.com/asottile/pyupgrade + rev: v2.32.1 + hooks: + - id: pyupgrade + args: ["--py36-plus"] - repo: https://github.com/open-mmlab/pre-commit-hooks rev: v0.2.0 # Use the ref you want to point at hooks: diff --git a/docs/en/conf.py b/docs/en/conf.py index db3e1edba..1a20c44d8 100644 --- a/docs/en/conf.py +++ b/docs/en/conf.py @@ -20,7 +20,7 @@ from sphinx.builders.html import StandaloneHTMLBuilder sys.path.insert(0, os.path.abspath('../..')) version_file = '../../mmcv/version.py' -with open(version_file, 'r') as f: +with open(version_file) as f: exec(compile(f.read(), version_file, 'exec')) __version__ = locals()['__version__'] diff --git a/docs/zh_cn/conf.py b/docs/zh_cn/conf.py index 98f077acb..3c3b34c7f 100644 --- a/docs/zh_cn/conf.py +++ b/docs/zh_cn/conf.py @@ -20,7 +20,7 @@ from sphinx.builders.html import StandaloneHTMLBuilder sys.path.insert(0, os.path.abspath('../..')) version_file = '../../mmcv/version.py' -with open(version_file, 'r') as f: +with open(version_file) as f: exec(compile(f.read(), version_file, 'exec')) __version__ = locals()['__version__'] diff --git a/examples/train.py b/examples/train.py index 2dbdfee40..b08d36bf6 100644 --- a/examples/train.py +++ b/examples/train.py @@ -14,7 +14,7 @@ from mmcv.utils import get_logger class Model(nn.Module): def __init__(self): - super(Model, self).__init__() + super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) diff --git a/mmcv/cnn/alexnet.py b/mmcv/cnn/alexnet.py index 89e36b8c7..2c809cca8 100644 --- a/mmcv/cnn/alexnet.py +++ b/mmcv/cnn/alexnet.py @@ -12,7 +12,7 @@ class AlexNet(nn.Module): """ def __init__(self, num_classes=-1): - super(AlexNet, self).__init__() + super().__init__() self.num_classes = num_classes self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), diff --git a/mmcv/cnn/bricks/activation.py b/mmcv/cnn/bricks/activation.py index 26be59581..b82374cf5 100644 --- a/mmcv/cnn/bricks/activation.py +++ b/mmcv/cnn/bricks/activation.py @@ -29,7 +29,7 @@ class Clamp(nn.Module): """ def __init__(self, min=-1., max=1.): - super(Clamp, self).__init__() + super().__init__() self.min = min self.max = max diff --git a/mmcv/cnn/bricks/context_block.py b/mmcv/cnn/bricks/context_block.py index d60fdb904..92e5255b6 100644 --- a/mmcv/cnn/bricks/context_block.py +++ b/mmcv/cnn/bricks/context_block.py @@ -38,7 +38,7 @@ class ContextBlock(nn.Module): ratio, pooling_type='att', fusion_types=('channel_add', )): - super(ContextBlock, self).__init__() + super().__init__() assert pooling_type in ['avg', 'att'] assert isinstance(fusion_types, (list, tuple)) valid_fusion_types = ['channel_add', 'channel_mul'] diff --git a/mmcv/cnn/bricks/conv_module.py b/mmcv/cnn/bricks/conv_module.py index 0078647a1..1d9756859 100644 --- a/mmcv/cnn/bricks/conv_module.py +++ b/mmcv/cnn/bricks/conv_module.py @@ -83,7 +83,7 @@ class ConvModule(nn.Module): with_spectral_norm=False, padding_mode='zeros', order=('conv', 'norm', 'act')): - super(ConvModule, self).__init__() + super().__init__() assert conv_cfg is None or isinstance(conv_cfg, dict) assert norm_cfg is None or isinstance(norm_cfg, dict) assert act_cfg is None or isinstance(act_cfg, dict) @@ -96,7 +96,7 @@ class ConvModule(nn.Module): self.with_explicit_padding = padding_mode not in official_padding_mode self.order = order assert isinstance(self.order, tuple) and len(self.order) == 3 - assert set(order) == set(['conv', 'norm', 'act']) + assert set(order) == {'conv', 'norm', 'act'} self.with_norm = norm_cfg is not None self.with_activation = act_cfg is not None diff --git a/mmcv/cnn/bricks/conv_ws.py b/mmcv/cnn/bricks/conv_ws.py index a3941e278..fcd0f228a 100644 --- a/mmcv/cnn/bricks/conv_ws.py +++ b/mmcv/cnn/bricks/conv_ws.py @@ -35,7 +35,7 @@ class ConvWS2d(nn.Conv2d): groups=1, bias=True, eps=1e-5): - super(ConvWS2d, self).__init__( + super().__init__( in_channels, out_channels, kernel_size, diff --git a/mmcv/cnn/bricks/depthwise_separable_conv_module.py b/mmcv/cnn/bricks/depthwise_separable_conv_module.py index 722d5d8d7..fa6136143 100644 --- a/mmcv/cnn/bricks/depthwise_separable_conv_module.py +++ b/mmcv/cnn/bricks/depthwise_separable_conv_module.py @@ -59,7 +59,7 @@ class DepthwiseSeparableConvModule(nn.Module): pw_norm_cfg='default', pw_act_cfg='default', **kwargs): - super(DepthwiseSeparableConvModule, self).__init__() + super().__init__() assert 'groups' not in kwargs, 'groups should not be specified' # if norm/activation config of depthwise/pointwise ConvModule is not diff --git a/mmcv/cnn/bricks/drop.py b/mmcv/cnn/bricks/drop.py index b0a026654..763b43215 100644 --- a/mmcv/cnn/bricks/drop.py +++ b/mmcv/cnn/bricks/drop.py @@ -37,7 +37,7 @@ class DropPath(nn.Module): """ def __init__(self, drop_prob=0.1): - super(DropPath, self).__init__() + super().__init__() self.drop_prob = drop_prob def forward(self, x): diff --git a/mmcv/cnn/bricks/generalized_attention.py b/mmcv/cnn/bricks/generalized_attention.py index c8a74d268..87c5c3780 100644 --- a/mmcv/cnn/bricks/generalized_attention.py +++ b/mmcv/cnn/bricks/generalized_attention.py @@ -54,7 +54,7 @@ class GeneralizedAttention(nn.Module): q_stride=1, attention_type='1111'): - super(GeneralizedAttention, self).__init__() + super().__init__() # hard range means local range for non-local operation self.position_embedding_dim = ( diff --git a/mmcv/cnn/bricks/hsigmoid.py b/mmcv/cnn/bricks/hsigmoid.py index e013d739e..1b538371f 100644 --- a/mmcv/cnn/bricks/hsigmoid.py +++ b/mmcv/cnn/bricks/hsigmoid.py @@ -27,7 +27,7 @@ class HSigmoid(nn.Module): """ def __init__(self, bias=3.0, divisor=6.0, min_value=0.0, max_value=1.0): - super(HSigmoid, self).__init__() + super().__init__() warnings.warn( 'In MMCV v1.4.4, we modified the default value of args to align ' 'with PyTorch official. Previous Implementation: ' diff --git a/mmcv/cnn/bricks/hswish.py b/mmcv/cnn/bricks/hswish.py index 27096832f..6089d0cc1 100644 --- a/mmcv/cnn/bricks/hswish.py +++ b/mmcv/cnn/bricks/hswish.py @@ -22,7 +22,7 @@ class HSwish(nn.Module): """ def __init__(self, inplace=False): - super(HSwish, self).__init__() + super().__init__() self.act = nn.ReLU6(inplace) def forward(self, x): diff --git a/mmcv/cnn/bricks/non_local.py b/mmcv/cnn/bricks/non_local.py index 92d00155e..f79797995 100644 --- a/mmcv/cnn/bricks/non_local.py +++ b/mmcv/cnn/bricks/non_local.py @@ -40,7 +40,7 @@ class _NonLocalNd(nn.Module, metaclass=ABCMeta): norm_cfg=None, mode='embedded_gaussian', **kwargs): - super(_NonLocalNd, self).__init__() + super().__init__() self.in_channels = in_channels self.reduction = reduction self.use_scale = use_scale @@ -228,8 +228,7 @@ class NonLocal1d(_NonLocalNd): sub_sample=False, conv_cfg=dict(type='Conv1d'), **kwargs): - super(NonLocal1d, self).__init__( - in_channels, conv_cfg=conv_cfg, **kwargs) + super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs) self.sub_sample = sub_sample @@ -262,8 +261,7 @@ class NonLocal2d(_NonLocalNd): sub_sample=False, conv_cfg=dict(type='Conv2d'), **kwargs): - super(NonLocal2d, self).__init__( - in_channels, conv_cfg=conv_cfg, **kwargs) + super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs) self.sub_sample = sub_sample @@ -293,8 +291,7 @@ class NonLocal3d(_NonLocalNd): sub_sample=False, conv_cfg=dict(type='Conv3d'), **kwargs): - super(NonLocal3d, self).__init__( - in_channels, conv_cfg=conv_cfg, **kwargs) + super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs) self.sub_sample = sub_sample if sub_sample: diff --git a/mmcv/cnn/bricks/scale.py b/mmcv/cnn/bricks/scale.py index c905fffcc..afd5d2d4e 100644 --- a/mmcv/cnn/bricks/scale.py +++ b/mmcv/cnn/bricks/scale.py @@ -14,7 +14,7 @@ class Scale(nn.Module): """ def __init__(self, scale=1.0): - super(Scale, self).__init__() + super().__init__() self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float)) def forward(self, x): diff --git a/mmcv/cnn/bricks/swish.py b/mmcv/cnn/bricks/swish.py index e2ca8ed7b..7df0fbba6 100644 --- a/mmcv/cnn/bricks/swish.py +++ b/mmcv/cnn/bricks/swish.py @@ -19,7 +19,7 @@ class Swish(nn.Module): """ def __init__(self): - super(Swish, self).__init__() + super().__init__() def forward(self, x): return x * torch.sigmoid(x) diff --git a/mmcv/cnn/bricks/transformer.py b/mmcv/cnn/bricks/transformer.py index 70c6623c7..f7ba4d9f8 100644 --- a/mmcv/cnn/bricks/transformer.py +++ b/mmcv/cnn/bricks/transformer.py @@ -96,7 +96,7 @@ class AdaptivePadding(nn.Module): """ def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'): - super(AdaptivePadding, self).__init__() + super().__init__() assert padding in ('same', 'corner') kernel_size = to_2tuple(kernel_size) @@ -190,7 +190,7 @@ class PatchEmbed(BaseModule): norm_cfg=None, input_size=None, init_cfg=None): - super(PatchEmbed, self).__init__(init_cfg=init_cfg) + super().__init__(init_cfg=init_cfg) self.embed_dims = embed_dims if stride is None: @@ -435,7 +435,7 @@ class MultiheadAttention(BaseModule): init_cfg=None, batch_first=False, **kwargs): - super(MultiheadAttention, self).__init__(init_cfg) + super().__init__(init_cfg) if 'dropout' in kwargs: warnings.warn( 'The arguments `dropout` in MultiheadAttention ' @@ -590,7 +590,7 @@ class FFN(BaseModule): add_identity=True, init_cfg=None, **kwargs): - super(FFN, self).__init__(init_cfg) + super().__init__(init_cfg) assert num_fcs >= 2, 'num_fcs should be no less ' \ f'than 2. got {num_fcs}.' self.embed_dims = embed_dims @@ -694,12 +694,12 @@ class BaseTransformerLayer(BaseModule): f'to a dict named `ffn_cfgs`. ', DeprecationWarning) ffn_cfgs[new_name] = kwargs[ori_name] - super(BaseTransformerLayer, self).__init__(init_cfg) + super().__init__(init_cfg) self.batch_first = batch_first - assert set(operation_order) & set( - ['self_attn', 'norm', 'ffn', 'cross_attn']) == \ + assert set(operation_order) & { + 'self_attn', 'norm', 'ffn', 'cross_attn'} == \ set(operation_order), f'The operation_order of' \ f' {self.__class__.__name__} should ' \ f'contains all four operation type ' \ @@ -880,7 +880,7 @@ class TransformerLayerSequence(BaseModule): """ def __init__(self, transformerlayers=None, num_layers=None, init_cfg=None): - super(TransformerLayerSequence, self).__init__(init_cfg) + super().__init__(init_cfg) if isinstance(transformerlayers, dict): transformerlayers = [ copy.deepcopy(transformerlayers) for _ in range(num_layers) diff --git a/mmcv/cnn/bricks/upsample.py b/mmcv/cnn/bricks/upsample.py index 0fd21fbf9..15e4febde 100644 --- a/mmcv/cnn/bricks/upsample.py +++ b/mmcv/cnn/bricks/upsample.py @@ -26,7 +26,7 @@ class PixelShufflePack(nn.Module): def __init__(self, in_channels, out_channels, scale_factor, upsample_kernel): - super(PixelShufflePack, self).__init__() + super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.scale_factor = scale_factor diff --git a/mmcv/cnn/resnet.py b/mmcv/cnn/resnet.py index 1cb3ac057..ba9d72510 100644 --- a/mmcv/cnn/resnet.py +++ b/mmcv/cnn/resnet.py @@ -30,7 +30,7 @@ class BasicBlock(nn.Module): downsample=None, style='pytorch', with_cp=False): - super(BasicBlock, self).__init__() + super().__init__() assert style in ['pytorch', 'caffe'] self.conv1 = conv3x3(inplanes, planes, stride, dilation) self.bn1 = nn.BatchNorm2d(planes) @@ -77,7 +77,7 @@ class Bottleneck(nn.Module): If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is "caffe", the stride-two layer is the first 1x1 conv layer. """ - super(Bottleneck, self).__init__() + super().__init__() assert style in ['pytorch', 'caffe'] if style == 'pytorch': conv1_stride = 1 @@ -218,7 +218,7 @@ class ResNet(nn.Module): bn_eval=True, bn_frozen=False, with_cp=False): - super(ResNet, self).__init__() + super().__init__() if depth not in self.arch_settings: raise KeyError(f'invalid depth {depth} for resnet') assert num_stages >= 1 and num_stages <= 4 @@ -293,7 +293,7 @@ class ResNet(nn.Module): return tuple(outs) def train(self, mode=True): - super(ResNet, self).train(mode) + super().train(mode) if self.bn_eval: for m in self.modules(): if isinstance(m, nn.BatchNorm2d): diff --git a/mmcv/cnn/utils/flops_counter.py b/mmcv/cnn/utils/flops_counter.py index a6045db84..edf332f6b 100644 --- a/mmcv/cnn/utils/flops_counter.py +++ b/mmcv/cnn/utils/flops_counter.py @@ -277,10 +277,10 @@ def print_model_with_flops(model, return ', '.join([ params_to_string( accumulated_num_params, units='M', precision=precision), - '{:.3%} Params'.format(accumulated_num_params / total_params), + f'{accumulated_num_params / total_params:.3%} Params', flops_to_string( accumulated_flops_cost, units=units, precision=precision), - '{:.3%} FLOPs'.format(accumulated_flops_cost / total_flops), + f'{accumulated_flops_cost / total_flops:.3%} FLOPs', self.original_extra_repr() ]) diff --git a/mmcv/cnn/utils/weight_init.py b/mmcv/cnn/utils/weight_init.py index 0ac08c87f..9f1da7a9f 100644 --- a/mmcv/cnn/utils/weight_init.py +++ b/mmcv/cnn/utils/weight_init.py @@ -129,7 +129,7 @@ def _get_bases_name(m): return [b.__name__ for b in m.__class__.__bases__] -class BaseInit(object): +class BaseInit: def __init__(self, *, bias=0, bias_prob=None, layer=None): self.wholemodule = False @@ -461,7 +461,7 @@ class Caffe2XavierInit(KaimingInit): @INITIALIZERS.register_module(name='Pretrained') -class PretrainedInit(object): +class PretrainedInit: """Initialize module by loading a pretrained model. Args: diff --git a/mmcv/cnn/vgg.py b/mmcv/cnn/vgg.py index 8778b6495..6201a9a6e 100644 --- a/mmcv/cnn/vgg.py +++ b/mmcv/cnn/vgg.py @@ -70,7 +70,7 @@ class VGG(nn.Module): bn_frozen=False, ceil_mode=False, with_last_pool=True): - super(VGG, self).__init__() + super().__init__() if depth not in self.arch_settings: raise KeyError(f'invalid depth {depth} for vgg') assert num_stages >= 1 and num_stages <= 5 @@ -157,7 +157,7 @@ class VGG(nn.Module): return tuple(outs) def train(self, mode=True): - super(VGG, self).train(mode) + super().train(mode) if self.bn_eval: for m in self.modules(): if isinstance(m, nn.BatchNorm2d): diff --git a/mmcv/device/mlu/data_parallel.py b/mmcv/device/mlu/data_parallel.py index b2d09d0b0..ebe14c0a5 100644 --- a/mmcv/device/mlu/data_parallel.py +++ b/mmcv/device/mlu/data_parallel.py @@ -33,7 +33,7 @@ class MLUDataParallel(MMDataParallel): """ def __init__(self, *args, dim=0, **kwargs): - super(MLUDataParallel, self).__init__(*args, dim=dim, **kwargs) + super().__init__(*args, dim=dim, **kwargs) self.device_ids = [0] self.src_device_obj = torch.device('mlu:0') diff --git a/mmcv/fileio/file_client.py b/mmcv/fileio/file_client.py index aed74f054..49775db89 100644 --- a/mmcv/fileio/file_client.py +++ b/mmcv/fileio/file_client.py @@ -210,9 +210,9 @@ class PetrelBackend(BaseStorageBackend): """ if not has_method(self._client, 'delete'): raise NotImplementedError( - ('Current version of Petrel Python SDK has not supported ' - 'the `delete` method, please use a higher version or dev' - ' branch instead.')) + 'Current version of Petrel Python SDK has not supported ' + 'the `delete` method, please use a higher version or dev' + ' branch instead.') filepath = self._map_path(filepath) filepath = self._format_path(filepath) @@ -230,9 +230,9 @@ class PetrelBackend(BaseStorageBackend): if not (has_method(self._client, 'contains') and has_method(self._client, 'isdir')): raise NotImplementedError( - ('Current version of Petrel Python SDK has not supported ' - 'the `contains` and `isdir` methods, please use a higher' - 'version or dev branch instead.')) + 'Current version of Petrel Python SDK has not supported ' + 'the `contains` and `isdir` methods, please use a higher' + 'version or dev branch instead.') filepath = self._map_path(filepath) filepath = self._format_path(filepath) @@ -251,9 +251,9 @@ class PetrelBackend(BaseStorageBackend): """ if not has_method(self._client, 'isdir'): raise NotImplementedError( - ('Current version of Petrel Python SDK has not supported ' - 'the `isdir` method, please use a higher version or dev' - ' branch instead.')) + 'Current version of Petrel Python SDK has not supported ' + 'the `isdir` method, please use a higher version or dev' + ' branch instead.') filepath = self._map_path(filepath) filepath = self._format_path(filepath) @@ -271,9 +271,9 @@ class PetrelBackend(BaseStorageBackend): """ if not has_method(self._client, 'contains'): raise NotImplementedError( - ('Current version of Petrel Python SDK has not supported ' - 'the `contains` method, please use a higher version or ' - 'dev branch instead.')) + 'Current version of Petrel Python SDK has not supported ' + 'the `contains` method, please use a higher version or ' + 'dev branch instead.') filepath = self._map_path(filepath) filepath = self._format_path(filepath) @@ -366,9 +366,9 @@ class PetrelBackend(BaseStorageBackend): """ if not has_method(self._client, 'list'): raise NotImplementedError( - ('Current version of Petrel Python SDK has not supported ' - 'the `list` method, please use a higher version or dev' - ' branch instead.')) + 'Current version of Petrel Python SDK has not supported ' + 'the `list` method, please use a higher version or dev' + ' branch instead.') dir_path = self._map_path(dir_path) dir_path = self._format_path(dir_path) @@ -549,7 +549,7 @@ class HardDiskBackend(BaseStorageBackend): Returns: str: Expected text reading from ``filepath``. """ - with open(filepath, 'r', encoding=encoding) as f: + with open(filepath, encoding=encoding) as f: value_buf = f.read() return value_buf diff --git a/mmcv/fileio/handlers/pickle_handler.py b/mmcv/fileio/handlers/pickle_handler.py index b37c79bed..073856fd2 100644 --- a/mmcv/fileio/handlers/pickle_handler.py +++ b/mmcv/fileio/handlers/pickle_handler.py @@ -12,8 +12,7 @@ class PickleHandler(BaseFileHandler): return pickle.load(file, **kwargs) def load_from_path(self, filepath, **kwargs): - return super(PickleHandler, self).load_from_path( - filepath, mode='rb', **kwargs) + return super().load_from_path(filepath, mode='rb', **kwargs) def dump_to_str(self, obj, **kwargs): kwargs.setdefault('protocol', 2) @@ -24,5 +23,4 @@ class PickleHandler(BaseFileHandler): pickle.dump(obj, file, **kwargs) def dump_to_path(self, obj, filepath, **kwargs): - super(PickleHandler, self).dump_to_path( - obj, filepath, mode='wb', **kwargs) + super().dump_to_path(obj, filepath, mode='wb', **kwargs) diff --git a/mmcv/image/geometric.py b/mmcv/image/geometric.py index 4c423bf2a..eecd795ea 100644 --- a/mmcv/image/geometric.py +++ b/mmcv/image/geometric.py @@ -157,7 +157,7 @@ def imresize_to_multiple(img, size = _scale_size((w, h), scale_factor) divisor = to_2tuple(divisor) - size = tuple([int(np.ceil(s / d)) * d for s, d in zip(size, divisor)]) + size = tuple(int(np.ceil(s / d)) * d for s, d in zip(size, divisor)) resized_img, w_scale, h_scale = imresize( img, size, diff --git a/mmcv/onnx/onnx_utils/symbolic_helper.py b/mmcv/onnx/onnx_utils/symbolic_helper.py index ded275672..cc9e96f8f 100644 --- a/mmcv/onnx/onnx_utils/symbolic_helper.py +++ b/mmcv/onnx/onnx_utils/symbolic_helper.py @@ -59,7 +59,7 @@ def _parse_arg(value, desc): raise RuntimeError( "ONNX symbolic doesn't know to interpret ListConstruct node") - raise RuntimeError('Unexpected node type: {}'.format(value.node().kind())) + raise RuntimeError(f'Unexpected node type: {value.node().kind()}') def _maybe_get_const(value, desc): diff --git a/mmcv/ops/border_align.py b/mmcv/ops/border_align.py index 2cbe25f45..e5a5bb743 100644 --- a/mmcv/ops/border_align.py +++ b/mmcv/ops/border_align.py @@ -86,7 +86,7 @@ class BorderAlign(nn.Module): """ def __init__(self, pool_size): - super(BorderAlign, self).__init__() + super().__init__() self.pool_size = pool_size def forward(self, input, boxes): diff --git a/mmcv/ops/box_iou_rotated.py b/mmcv/ops/box_iou_rotated.py index 7ebef505b..20f663959 100644 --- a/mmcv/ops/box_iou_rotated.py +++ b/mmcv/ops/box_iou_rotated.py @@ -131,7 +131,7 @@ def box_iou_rotated(bboxes1, if aligned: ious = bboxes1.new_zeros(rows) else: - ious = bboxes1.new_zeros((rows * cols)) + ious = bboxes1.new_zeros(rows * cols) if not clockwise: flip_mat = bboxes1.new_ones(bboxes1.shape[-1]) flip_mat[-1] = -1 diff --git a/mmcv/ops/carafe.py b/mmcv/ops/carafe.py index d93ff43bb..a13389b26 100644 --- a/mmcv/ops/carafe.py +++ b/mmcv/ops/carafe.py @@ -85,7 +85,7 @@ carafe_naive = CARAFENaiveFunction.apply class CARAFENaive(Module): def __init__(self, kernel_size, group_size, scale_factor): - super(CARAFENaive, self).__init__() + super().__init__() assert isinstance(kernel_size, int) and isinstance( group_size, int) and isinstance(scale_factor, int) @@ -195,7 +195,7 @@ class CARAFE(Module): """ def __init__(self, kernel_size, group_size, scale_factor): - super(CARAFE, self).__init__() + super().__init__() assert isinstance(kernel_size, int) and isinstance( group_size, int) and isinstance(scale_factor, int) @@ -238,7 +238,7 @@ class CARAFEPack(nn.Module): encoder_kernel=3, encoder_dilation=1, compressed_channels=64): - super(CARAFEPack, self).__init__() + super().__init__() self.channels = channels self.scale_factor = scale_factor self.up_kernel = up_kernel diff --git a/mmcv/ops/corner_pool.py b/mmcv/ops/corner_pool.py index 067e8f029..651a455ab 100644 --- a/mmcv/ops/corner_pool.py +++ b/mmcv/ops/corner_pool.py @@ -125,7 +125,7 @@ class CornerPool(nn.Module): } def __init__(self, mode): - super(CornerPool, self).__init__() + super().__init__() assert mode in self.pool_functions self.mode = mode self.corner_pool = self.pool_functions[mode] diff --git a/mmcv/ops/deform_conv.py b/mmcv/ops/deform_conv.py index dc2391d42..105668159 100644 --- a/mmcv/ops/deform_conv.py +++ b/mmcv/ops/deform_conv.py @@ -236,7 +236,7 @@ class DeformConv2d(nn.Module): deform_groups: int = 1, bias: bool = False, im2col_step: int = 32) -> None: - super(DeformConv2d, self).__init__() + super().__init__() assert not bias, \ f'bias={bias} is not supported in DeformConv2d.' @@ -356,7 +356,7 @@ class DeformConv2dPack(DeformConv2d): _version = 2 def __init__(self, *args, **kwargs): - super(DeformConv2dPack, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.conv_offset = nn.Conv2d( self.in_channels, self.deform_groups * 2 * self.kernel_size[0] * self.kernel_size[1], diff --git a/mmcv/ops/deform_roi_pool.py b/mmcv/ops/deform_roi_pool.py index cc245ba91..7d7b84f39 100644 --- a/mmcv/ops/deform_roi_pool.py +++ b/mmcv/ops/deform_roi_pool.py @@ -96,7 +96,7 @@ class DeformRoIPool(nn.Module): spatial_scale=1.0, sampling_ratio=0, gamma=0.1): - super(DeformRoIPool, self).__init__() + super().__init__() self.output_size = _pair(output_size) self.spatial_scale = float(spatial_scale) self.sampling_ratio = int(sampling_ratio) @@ -117,8 +117,7 @@ class DeformRoIPoolPack(DeformRoIPool): spatial_scale=1.0, sampling_ratio=0, gamma=0.1): - super(DeformRoIPoolPack, self).__init__(output_size, spatial_scale, - sampling_ratio, gamma) + super().__init__(output_size, spatial_scale, sampling_ratio, gamma) self.output_channels = output_channels self.deform_fc_channels = deform_fc_channels @@ -158,8 +157,7 @@ class ModulatedDeformRoIPoolPack(DeformRoIPool): spatial_scale=1.0, sampling_ratio=0, gamma=0.1): - super(ModulatedDeformRoIPoolPack, - self).__init__(output_size, spatial_scale, sampling_ratio, gamma) + super().__init__(output_size, spatial_scale, sampling_ratio, gamma) self.output_channels = output_channels self.deform_fc_channels = deform_fc_channels diff --git a/mmcv/ops/focal_loss.py b/mmcv/ops/focal_loss.py index 805860516..f04a4cd07 100644 --- a/mmcv/ops/focal_loss.py +++ b/mmcv/ops/focal_loss.py @@ -89,7 +89,7 @@ sigmoid_focal_loss = SigmoidFocalLossFunction.apply class SigmoidFocalLoss(nn.Module): def __init__(self, gamma, alpha, weight=None, reduction='mean'): - super(SigmoidFocalLoss, self).__init__() + super().__init__() self.gamma = gamma self.alpha = alpha self.register_buffer('weight', weight) @@ -195,7 +195,7 @@ softmax_focal_loss = SoftmaxFocalLossFunction.apply class SoftmaxFocalLoss(nn.Module): def __init__(self, gamma, alpha, weight=None, reduction='mean'): - super(SoftmaxFocalLoss, self).__init__() + super().__init__() self.gamma = gamma self.alpha = alpha self.register_buffer('weight', weight) diff --git a/mmcv/ops/fused_bias_leakyrelu.py b/mmcv/ops/fused_bias_leakyrelu.py index 6f3c3ddb8..ee0b9ea61 100644 --- a/mmcv/ops/fused_bias_leakyrelu.py +++ b/mmcv/ops/fused_bias_leakyrelu.py @@ -212,7 +212,7 @@ class FusedBiasLeakyReLU(nn.Module): """ def __init__(self, num_channels, negative_slope=0.2, scale=2**0.5): - super(FusedBiasLeakyReLU, self).__init__() + super().__init__() self.bias = nn.Parameter(torch.zeros(num_channels)) self.negative_slope = negative_slope diff --git a/mmcv/ops/masked_conv.py b/mmcv/ops/masked_conv.py index 0d61555ee..9f0d3ca95 100644 --- a/mmcv/ops/masked_conv.py +++ b/mmcv/ops/masked_conv.py @@ -98,13 +98,12 @@ class MaskedConv2d(nn.Conv2d): dilation=1, groups=1, bias=True): - super(MaskedConv2d, - self).__init__(in_channels, out_channels, kernel_size, stride, - padding, dilation, groups, bias) + super().__init__(in_channels, out_channels, kernel_size, stride, + padding, dilation, groups, bias) def forward(self, input, mask=None): if mask is None: # fallback to the normal Conv2d - return super(MaskedConv2d, self).forward(input) + return super().forward(input) else: return masked_conv2d(input, mask, self.weight, self.bias, self.padding) diff --git a/mmcv/ops/merge_cells.py b/mmcv/ops/merge_cells.py index 48ca8cc0a..4f4944cee 100644 --- a/mmcv/ops/merge_cells.py +++ b/mmcv/ops/merge_cells.py @@ -53,7 +53,7 @@ class BaseMergeCell(nn.Module): input_conv_cfg=None, input_norm_cfg=None, upsample_mode='nearest'): - super(BaseMergeCell, self).__init__() + super().__init__() assert upsample_mode in ['nearest', 'bilinear'] self.with_out_conv = with_out_conv self.with_input1_conv = with_input1_conv @@ -121,7 +121,7 @@ class BaseMergeCell(nn.Module): class SumCell(BaseMergeCell): def __init__(self, in_channels, out_channels, **kwargs): - super(SumCell, self).__init__(in_channels, out_channels, **kwargs) + super().__init__(in_channels, out_channels, **kwargs) def _binary_op(self, x1, x2): return x1 + x2 @@ -130,8 +130,7 @@ class SumCell(BaseMergeCell): class ConcatCell(BaseMergeCell): def __init__(self, in_channels, out_channels, **kwargs): - super(ConcatCell, self).__init__(in_channels * 2, out_channels, - **kwargs) + super().__init__(in_channels * 2, out_channels, **kwargs) def _binary_op(self, x1, x2): ret = torch.cat([x1, x2], dim=1) diff --git a/mmcv/ops/modulated_deform_conv.py b/mmcv/ops/modulated_deform_conv.py index 56f2501a7..7c645cae6 100644 --- a/mmcv/ops/modulated_deform_conv.py +++ b/mmcv/ops/modulated_deform_conv.py @@ -168,7 +168,7 @@ class ModulatedDeformConv2d(nn.Module): groups=1, deform_groups=1, bias=True): - super(ModulatedDeformConv2d, self).__init__() + super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _pair(kernel_size) @@ -227,7 +227,7 @@ class ModulatedDeformConv2dPack(ModulatedDeformConv2d): _version = 2 def __init__(self, *args, **kwargs): - super(ModulatedDeformConv2dPack, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.conv_offset = nn.Conv2d( self.in_channels, self.deform_groups * 3 * self.kernel_size[0] * self.kernel_size[1], @@ -239,7 +239,7 @@ class ModulatedDeformConv2dPack(ModulatedDeformConv2d): self.init_weights() def init_weights(self): - super(ModulatedDeformConv2dPack, self).init_weights() + super().init_weights() if hasattr(self, 'conv_offset'): self.conv_offset.weight.data.zero_() self.conv_offset.bias.data.zero_() diff --git a/mmcv/ops/point_sample.py b/mmcv/ops/point_sample.py index 9a70b28e2..0d3147c15 100644 --- a/mmcv/ops/point_sample.py +++ b/mmcv/ops/point_sample.py @@ -296,7 +296,7 @@ class SimpleRoIAlign(nn.Module): If True, align the results more perfectly. """ - super(SimpleRoIAlign, self).__init__() + super().__init__() self.output_size = _pair(output_size) self.spatial_scale = float(spatial_scale) # to be consistent with other RoI ops diff --git a/mmcv/ops/psa_mask.py b/mmcv/ops/psa_mask.py index cdf14e62b..0786e2d25 100644 --- a/mmcv/ops/psa_mask.py +++ b/mmcv/ops/psa_mask.py @@ -72,7 +72,7 @@ psa_mask = PSAMaskFunction.apply class PSAMask(nn.Module): def __init__(self, psa_type, mask_size=None): - super(PSAMask, self).__init__() + super().__init__() assert psa_type in ['collect', 'distribute'] if psa_type == 'collect': psa_type_enum = 0 diff --git a/mmcv/ops/riroi_align_rotated.py b/mmcv/ops/riroi_align_rotated.py index c87ae2995..af1e6098e 100644 --- a/mmcv/ops/riroi_align_rotated.py +++ b/mmcv/ops/riroi_align_rotated.py @@ -116,7 +116,7 @@ class RiRoIAlignRotated(nn.Module): num_samples=0, num_orientations=8, clockwise=False): - super(RiRoIAlignRotated, self).__init__() + super().__init__() self.out_size = out_size self.spatial_scale = float(spatial_scale) diff --git a/mmcv/ops/roi_align.py b/mmcv/ops/roi_align.py index 12beb8e52..7e387f944 100644 --- a/mmcv/ops/roi_align.py +++ b/mmcv/ops/roi_align.py @@ -181,7 +181,7 @@ class RoIAlign(nn.Module): pool_mode='avg', aligned=True, use_torchvision=False): - super(RoIAlign, self).__init__() + super().__init__() self.output_size = _pair(output_size) self.spatial_scale = float(spatial_scale) diff --git a/mmcv/ops/roi_align_rotated.py b/mmcv/ops/roi_align_rotated.py index 965f9c987..8551b172b 100644 --- a/mmcv/ops/roi_align_rotated.py +++ b/mmcv/ops/roi_align_rotated.py @@ -156,7 +156,7 @@ class RoIAlignRotated(nn.Module): sampling_ratio=0, aligned=True, clockwise=False): - super(RoIAlignRotated, self).__init__() + super().__init__() self.output_size = _pair(output_size) self.spatial_scale = float(spatial_scale) diff --git a/mmcv/ops/roi_pool.py b/mmcv/ops/roi_pool.py index d339d8f29..f63faabb4 100644 --- a/mmcv/ops/roi_pool.py +++ b/mmcv/ops/roi_pool.py @@ -71,7 +71,7 @@ roi_pool = RoIPoolFunction.apply class RoIPool(nn.Module): def __init__(self, output_size, spatial_scale=1.0): - super(RoIPool, self).__init__() + super().__init__() self.output_size = _pair(output_size) self.spatial_scale = float(spatial_scale) diff --git a/mmcv/ops/sparse_conv.py b/mmcv/ops/sparse_conv.py index 82aea4d65..3df88d003 100644 --- a/mmcv/ops/sparse_conv.py +++ b/mmcv/ops/sparse_conv.py @@ -64,7 +64,7 @@ class SparseConvolution(SparseModule): inverse=False, indice_key=None, fused_bn=False): - super(SparseConvolution, self).__init__() + super().__init__() assert groups == 1 if not isinstance(kernel_size, (list, tuple)): kernel_size = [kernel_size] * ndim @@ -217,7 +217,7 @@ class SparseConv2d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SparseConv2d, self).__init__( + super().__init__( 2, in_channels, out_channels, @@ -243,7 +243,7 @@ class SparseConv3d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SparseConv3d, self).__init__( + super().__init__( 3, in_channels, out_channels, @@ -269,7 +269,7 @@ class SparseConv4d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SparseConv4d, self).__init__( + super().__init__( 4, in_channels, out_channels, @@ -295,7 +295,7 @@ class SparseConvTranspose2d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SparseConvTranspose2d, self).__init__( + super().__init__( 2, in_channels, out_channels, @@ -322,7 +322,7 @@ class SparseConvTranspose3d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SparseConvTranspose3d, self).__init__( + super().__init__( 3, in_channels, out_channels, @@ -345,7 +345,7 @@ class SparseInverseConv2d(SparseConvolution): kernel_size, indice_key=None, bias=True): - super(SparseInverseConv2d, self).__init__( + super().__init__( 2, in_channels, out_channels, @@ -364,7 +364,7 @@ class SparseInverseConv3d(SparseConvolution): kernel_size, indice_key=None, bias=True): - super(SparseInverseConv3d, self).__init__( + super().__init__( 3, in_channels, out_channels, @@ -387,7 +387,7 @@ class SubMConv2d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SubMConv2d, self).__init__( + super().__init__( 2, in_channels, out_channels, @@ -414,7 +414,7 @@ class SubMConv3d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SubMConv3d, self).__init__( + super().__init__( 3, in_channels, out_channels, @@ -441,7 +441,7 @@ class SubMConv4d(SparseConvolution): groups=1, bias=True, indice_key=None): - super(SubMConv4d, self).__init__( + super().__init__( 4, in_channels, out_channels, diff --git a/mmcv/ops/sparse_modules.py b/mmcv/ops/sparse_modules.py index 9158d1fc1..a721b30e5 100644 --- a/mmcv/ops/sparse_modules.py +++ b/mmcv/ops/sparse_modules.py @@ -86,7 +86,7 @@ class SparseSequential(SparseModule): """ def __init__(self, *args, **kwargs): - super(SparseSequential, self).__init__() + super().__init__() if len(args) == 1 and isinstance(args[0], OrderedDict): for key, module in args[0].items(): self.add_module(key, module) @@ -103,7 +103,7 @@ class SparseSequential(SparseModule): def __getitem__(self, idx): if not (-len(self) <= idx < len(self)): - raise IndexError('index {} is out of range'.format(idx)) + raise IndexError(f'index {idx} is out of range') if idx < 0: idx += len(self) it = iter(self._modules.values()) diff --git a/mmcv/ops/sparse_pool.py b/mmcv/ops/sparse_pool.py index 0d9c1f68e..c4edb1d4e 100644 --- a/mmcv/ops/sparse_pool.py +++ b/mmcv/ops/sparse_pool.py @@ -29,7 +29,7 @@ class SparseMaxPool(SparseModule): padding=0, dilation=1, subm=False): - super(SparseMaxPool, self).__init__() + super().__init__() if not isinstance(kernel_size, (list, tuple)): kernel_size = [kernel_size] * ndim if not isinstance(stride, (list, tuple)): @@ -77,12 +77,10 @@ class SparseMaxPool(SparseModule): class SparseMaxPool2d(SparseMaxPool): def __init__(self, kernel_size, stride=1, padding=0, dilation=1): - super(SparseMaxPool2d, self).__init__(2, kernel_size, stride, padding, - dilation) + super().__init__(2, kernel_size, stride, padding, dilation) class SparseMaxPool3d(SparseMaxPool): def __init__(self, kernel_size, stride=1, padding=0, dilation=1): - super(SparseMaxPool3d, self).__init__(3, kernel_size, stride, padding, - dilation) + super().__init__(3, kernel_size, stride, padding, dilation) diff --git a/mmcv/ops/sparse_structure.py b/mmcv/ops/sparse_structure.py index 852b62d5c..82d04167c 100644 --- a/mmcv/ops/sparse_structure.py +++ b/mmcv/ops/sparse_structure.py @@ -18,7 +18,7 @@ def scatter_nd(indices, updates, shape): return ret -class SparseConvTensor(object): +class SparseConvTensor: def __init__(self, features, diff --git a/mmcv/ops/sync_bn.py b/mmcv/ops/sync_bn.py index 04302f031..e24ecb1a0 100644 --- a/mmcv/ops/sync_bn.py +++ b/mmcv/ops/sync_bn.py @@ -198,7 +198,7 @@ class SyncBatchNorm(Module): track_running_stats=True, group=None, stats_mode='default'): - super(SyncBatchNorm, self).__init__() + super().__init__() self.num_features = num_features self.eps = eps self.momentum = momentum diff --git a/mmcv/parallel/data_parallel.py b/mmcv/parallel/data_parallel.py index 7a5abeb6e..e86b47a5c 100644 --- a/mmcv/parallel/data_parallel.py +++ b/mmcv/parallel/data_parallel.py @@ -32,7 +32,7 @@ class MMDataParallel(DataParallel): """ def __init__(self, *args, dim=0, **kwargs): - super(MMDataParallel, self).__init__(*args, dim=dim, **kwargs) + super().__init__(*args, dim=dim, **kwargs) self.dim = dim def forward(self, *inputs, **kwargs): diff --git a/mmcv/parallel/distributed_deprecated.py b/mmcv/parallel/distributed_deprecated.py index b593d4a9e..d438b58bd 100644 --- a/mmcv/parallel/distributed_deprecated.py +++ b/mmcv/parallel/distributed_deprecated.py @@ -18,7 +18,7 @@ class MMDistributedDataParallel(nn.Module): dim=0, broadcast_buffers=True, bucket_cap_mb=25): - super(MMDistributedDataParallel, self).__init__() + super().__init__() self.module = module self.dim = dim self.broadcast_buffers = broadcast_buffers diff --git a/mmcv/runner/base_module.py b/mmcv/runner/base_module.py index 7937eca37..e3751dfa3 100644 --- a/mmcv/runner/base_module.py +++ b/mmcv/runner/base_module.py @@ -35,7 +35,7 @@ class BaseModule(nn.Module, metaclass=ABCMeta): # NOTE init_cfg can be defined in different levels, but init_cfg # in low levels has a higher priority. - super(BaseModule, self).__init__() + super().__init__() # define default value of init_cfg instead of hard code # in init_weights() function self._is_init = False diff --git a/mmcv/runner/hooks/checkpoint.py b/mmcv/runner/hooks/checkpoint.py index 7bb75f402..3449e98a9 100644 --- a/mmcv/runner/hooks/checkpoint.py +++ b/mmcv/runner/hooks/checkpoint.py @@ -83,8 +83,8 @@ class CheckpointHook(Hook): basename = osp.basename(runner.work_dir.rstrip(osp.sep)) self.out_dir = self.file_client.join_path(self.out_dir, basename) - runner.logger.info((f'Checkpoints will be saved to {self.out_dir} by ' - f'{self.file_client.name}.')) + runner.logger.info(f'Checkpoints will be saved to {self.out_dir} by ' + f'{self.file_client.name}.') # disable the create_symlink option because some file backends do not # allow to create a symlink @@ -93,9 +93,9 @@ class CheckpointHook(Hook): 'create_symlink'] and not self.file_client.allow_symlink: self.args['create_symlink'] = False warnings.warn( - ('create_symlink is set as True by the user but is changed' - 'to be False because creating symbolic link is not ' - f'allowed in {self.file_client.name}')) + 'create_symlink is set as True by the user but is changed' + 'to be False because creating symbolic link is not ' + f'allowed in {self.file_client.name}') else: self.args['create_symlink'] = self.file_client.allow_symlink diff --git a/mmcv/runner/hooks/evaluation.py b/mmcv/runner/hooks/evaluation.py index 2a57d535e..987bacd4a 100644 --- a/mmcv/runner/hooks/evaluation.py +++ b/mmcv/runner/hooks/evaluation.py @@ -214,8 +214,8 @@ class EvalHook(Hook): basename = osp.basename(runner.work_dir.rstrip(osp.sep)) self.out_dir = self.file_client.join_path(self.out_dir, basename) runner.logger.info( - (f'The best checkpoint will be saved to {self.out_dir} by ' - f'{self.file_client.name}')) + f'The best checkpoint will be saved to {self.out_dir} by ' + f'{self.file_client.name}') if self.save_best is not None: if runner.meta is None: @@ -335,8 +335,8 @@ class EvalHook(Hook): self.best_ckpt_path): self.file_client.remove(self.best_ckpt_path) runner.logger.info( - (f'The previous best checkpoint {self.best_ckpt_path} was ' - 'removed')) + f'The previous best checkpoint {self.best_ckpt_path} was ' + 'removed') best_ckpt_name = f'best_{self.key_indicator}_{current}.pth' self.best_ckpt_path = self.file_client.join_path( diff --git a/mmcv/runner/hooks/logger/clearml.py b/mmcv/runner/hooks/logger/clearml.py index 1de71e152..5e04a78a3 100644 --- a/mmcv/runner/hooks/logger/clearml.py +++ b/mmcv/runner/hooks/logger/clearml.py @@ -34,8 +34,7 @@ class ClearMLLoggerHook(LoggerHook): ignore_last=True, reset_flag=False, by_epoch=True): - super(ClearMLLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.import_clearml() self.init_kwargs = init_kwargs @@ -49,7 +48,7 @@ class ClearMLLoggerHook(LoggerHook): @master_only def before_run(self, runner): - super(ClearMLLoggerHook, self).before_run(runner) + super().before_run(runner) task_kwargs = self.init_kwargs if self.init_kwargs else {} self.task = self.clearml.Task.init(**task_kwargs) self.task_logger = self.task.get_logger() diff --git a/mmcv/runner/hooks/logger/mlflow.py b/mmcv/runner/hooks/logger/mlflow.py index dcd87bcb5..58f7c0d7b 100644 --- a/mmcv/runner/hooks/logger/mlflow.py +++ b/mmcv/runner/hooks/logger/mlflow.py @@ -40,8 +40,7 @@ class MlflowLoggerHook(LoggerHook): ignore_last=True, reset_flag=False, by_epoch=True): - super(MlflowLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.import_mlflow() self.exp_name = exp_name self.tags = tags @@ -59,7 +58,7 @@ class MlflowLoggerHook(LoggerHook): @master_only def before_run(self, runner): - super(MlflowLoggerHook, self).before_run(runner) + super().before_run(runner) if self.exp_name is not None: self.mlflow.set_experiment(self.exp_name) if self.tags is not None: diff --git a/mmcv/runner/hooks/logger/neptune.py b/mmcv/runner/hooks/logger/neptune.py index e0aafe91d..58640cae2 100644 --- a/mmcv/runner/hooks/logger/neptune.py +++ b/mmcv/runner/hooks/logger/neptune.py @@ -49,8 +49,7 @@ class NeptuneLoggerHook(LoggerHook): with_step=True, by_epoch=True): - super(NeptuneLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.import_neptune() self.init_kwargs = init_kwargs self.with_step = with_step diff --git a/mmcv/runner/hooks/logger/pavi.py b/mmcv/runner/hooks/logger/pavi.py index d5d61f9e5..c83021515 100644 --- a/mmcv/runner/hooks/logger/pavi.py +++ b/mmcv/runner/hooks/logger/pavi.py @@ -40,8 +40,7 @@ class PaviLoggerHook(LoggerHook): reset_flag=False, by_epoch=True, img_key='img_info'): - super(PaviLoggerHook, self).__init__(interval, ignore_last, reset_flag, - by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.init_kwargs = init_kwargs self.add_graph = add_graph self.add_last_ckpt = add_last_ckpt @@ -49,7 +48,7 @@ class PaviLoggerHook(LoggerHook): @master_only def before_run(self, runner): - super(PaviLoggerHook, self).before_run(runner) + super().before_run(runner) try: from pavi import SummaryWriter except ImportError: diff --git a/mmcv/runner/hooks/logger/segmind.py b/mmcv/runner/hooks/logger/segmind.py index e262c7c1a..e9cf1a412 100644 --- a/mmcv/runner/hooks/logger/segmind.py +++ b/mmcv/runner/hooks/logger/segmind.py @@ -27,8 +27,7 @@ class SegmindLoggerHook(LoggerHook): ignore_last=True, reset_flag=False, by_epoch=True): - super(SegmindLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.import_segmind() def import_segmind(self): diff --git a/mmcv/runner/hooks/logger/tensorboard.py b/mmcv/runner/hooks/logger/tensorboard.py index bf00d5742..86ed92c14 100644 --- a/mmcv/runner/hooks/logger/tensorboard.py +++ b/mmcv/runner/hooks/logger/tensorboard.py @@ -28,13 +28,12 @@ class TensorboardLoggerHook(LoggerHook): ignore_last=True, reset_flag=False, by_epoch=True): - super(TensorboardLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.log_dir = log_dir @master_only def before_run(self, runner): - super(TensorboardLoggerHook, self).before_run(runner) + super().before_run(runner) if (TORCH_VERSION == 'parrots' or digit_version(TORCH_VERSION) < digit_version('1.1')): try: diff --git a/mmcv/runner/hooks/logger/text.py b/mmcv/runner/hooks/logger/text.py index 644ced2c9..adf073203 100644 --- a/mmcv/runner/hooks/logger/text.py +++ b/mmcv/runner/hooks/logger/text.py @@ -62,8 +62,7 @@ class TextLoggerHook(LoggerHook): out_suffix=('.log.json', '.log', '.py'), keep_local=True, file_client_args=None): - super(TextLoggerHook, self).__init__(interval, ignore_last, reset_flag, - by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.by_epoch = by_epoch self.time_sec_tot = 0 self.interval_exp_name = interval_exp_name @@ -87,7 +86,7 @@ class TextLoggerHook(LoggerHook): self.out_dir) def before_run(self, runner): - super(TextLoggerHook, self).before_run(runner) + super().before_run(runner) if self.out_dir is not None: self.file_client = FileClient.infer_client(self.file_client_args, @@ -97,8 +96,8 @@ class TextLoggerHook(LoggerHook): basename = osp.basename(runner.work_dir.rstrip(osp.sep)) self.out_dir = self.file_client.join_path(self.out_dir, basename) runner.logger.info( - (f'Text logs will be saved to {self.out_dir} by ' - f'{self.file_client.name} after the training process.')) + f'Text logs will be saved to {self.out_dir} by ' + f'{self.file_client.name} after the training process.') self.start_iter = runner.iter self.json_log_path = osp.join(runner.work_dir, @@ -242,15 +241,15 @@ class TextLoggerHook(LoggerHook): local_filepath = osp.join(runner.work_dir, filename) out_filepath = self.file_client.join_path( self.out_dir, filename) - with open(local_filepath, 'r') as f: + with open(local_filepath) as f: self.file_client.put_text(f.read(), out_filepath) runner.logger.info( - (f'The file {local_filepath} has been uploaded to ' - f'{out_filepath}.')) + f'The file {local_filepath} has been uploaded to ' + f'{out_filepath}.') if not self.keep_local: os.remove(local_filepath) runner.logger.info( - (f'{local_filepath} was removed due to the ' - '`self.keep_local=False`')) + f'{local_filepath} was removed due to the ' + '`self.keep_local=False`') diff --git a/mmcv/runner/hooks/logger/wandb.py b/mmcv/runner/hooks/logger/wandb.py index 78b890ee1..87decca3f 100644 --- a/mmcv/runner/hooks/logger/wandb.py +++ b/mmcv/runner/hooks/logger/wandb.py @@ -57,8 +57,7 @@ class WandbLoggerHook(LoggerHook): with_step=True, log_artifact=True, out_suffix=('.log.json', '.log', '.py')): - super(WandbLoggerHook, self).__init__(interval, ignore_last, - reset_flag, by_epoch) + super().__init__(interval, ignore_last, reset_flag, by_epoch) self.import_wandb() self.init_kwargs = init_kwargs self.commit = commit @@ -76,7 +75,7 @@ class WandbLoggerHook(LoggerHook): @master_only def before_run(self, runner): - super(WandbLoggerHook, self).before_run(runner) + super().before_run(runner) if self.wandb is None: self.import_wandb() if self.init_kwargs: diff --git a/mmcv/runner/hooks/lr_updater.py b/mmcv/runner/hooks/lr_updater.py index ee2a53a65..46c5feec9 100644 --- a/mmcv/runner/hooks/lr_updater.py +++ b/mmcv/runner/hooks/lr_updater.py @@ -157,7 +157,7 @@ class LrUpdaterHook(Hook): class FixedLrUpdaterHook(LrUpdaterHook): def __init__(self, **kwargs): - super(FixedLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): return base_lr @@ -188,7 +188,7 @@ class StepLrUpdaterHook(LrUpdaterHook): self.step = step self.gamma = gamma self.min_lr = min_lr - super(StepLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): progress = runner.epoch if self.by_epoch else runner.iter @@ -215,7 +215,7 @@ class ExpLrUpdaterHook(LrUpdaterHook): def __init__(self, gamma, **kwargs): self.gamma = gamma - super(ExpLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): progress = runner.epoch if self.by_epoch else runner.iter @@ -228,7 +228,7 @@ class PolyLrUpdaterHook(LrUpdaterHook): def __init__(self, power=1., min_lr=0., **kwargs): self.power = power self.min_lr = min_lr - super(PolyLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: @@ -247,7 +247,7 @@ class InvLrUpdaterHook(LrUpdaterHook): def __init__(self, gamma, power=1., **kwargs): self.gamma = gamma self.power = power - super(InvLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): progress = runner.epoch if self.by_epoch else runner.iter @@ -269,7 +269,7 @@ class CosineAnnealingLrUpdaterHook(LrUpdaterHook): assert (min_lr is None) ^ (min_lr_ratio is None) self.min_lr = min_lr self.min_lr_ratio = min_lr_ratio - super(CosineAnnealingLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: @@ -317,7 +317,7 @@ class FlatCosineAnnealingLrUpdaterHook(LrUpdaterHook): self.start_percent = start_percent self.min_lr = min_lr self.min_lr_ratio = min_lr_ratio - super(FlatCosineAnnealingLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: @@ -367,7 +367,7 @@ class CosineRestartLrUpdaterHook(LrUpdaterHook): self.restart_weights = restart_weights assert (len(self.periods) == len(self.restart_weights) ), 'periods and restart_weights should have the same length.' - super(CosineRestartLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) self.cumulative_periods = [ sum(self.periods[0:i + 1]) for i in range(0, len(self.periods)) @@ -484,10 +484,10 @@ class CyclicLrUpdaterHook(LrUpdaterHook): assert not by_epoch, \ 'currently only support "by_epoch" = False' - super(CyclicLrUpdaterHook, self).__init__(by_epoch, **kwargs) + super().__init__(by_epoch, **kwargs) def before_run(self, runner): - super(CyclicLrUpdaterHook, self).before_run(runner) + super().before_run(runner) # initiate lr_phases # total lr_phases are separated as up and down self.max_iter_per_phase = runner.max_iters // self.cyclic_times @@ -598,7 +598,7 @@ class OneCycleLrUpdaterHook(LrUpdaterHook): self.final_div_factor = final_div_factor self.three_phase = three_phase self.lr_phases = [] # init lr_phases - super(OneCycleLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def before_run(self, runner): if hasattr(self, 'total_steps'): @@ -668,7 +668,7 @@ class LinearAnnealingLrUpdaterHook(LrUpdaterHook): assert (min_lr is None) ^ (min_lr_ratio is None) self.min_lr = min_lr self.min_lr_ratio = min_lr_ratio - super(LinearAnnealingLrUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_lr(self, runner, base_lr): if self.by_epoch: diff --git a/mmcv/runner/hooks/momentum_updater.py b/mmcv/runner/hooks/momentum_updater.py index aa15fe23c..c86d6e905 100644 --- a/mmcv/runner/hooks/momentum_updater.py +++ b/mmcv/runner/hooks/momentum_updater.py @@ -176,7 +176,7 @@ class StepMomentumUpdaterHook(MomentumUpdaterHook): self.step = step self.gamma = gamma self.min_momentum = min_momentum - super(StepMomentumUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_momentum(self, runner, base_momentum): progress = runner.epoch if self.by_epoch else runner.iter @@ -214,7 +214,7 @@ class CosineAnnealingMomentumUpdaterHook(MomentumUpdaterHook): assert (min_momentum is None) ^ (min_momentum_ratio is None) self.min_momentum = min_momentum self.min_momentum_ratio = min_momentum_ratio - super(CosineAnnealingMomentumUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_momentum(self, runner, base_momentum): if self.by_epoch: @@ -247,7 +247,7 @@ class LinearAnnealingMomentumUpdaterHook(MomentumUpdaterHook): assert (min_momentum is None) ^ (min_momentum_ratio is None) self.min_momentum = min_momentum self.min_momentum_ratio = min_momentum_ratio - super(LinearAnnealingMomentumUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def get_momentum(self, runner, base_momentum): if self.by_epoch: @@ -328,10 +328,10 @@ class CyclicMomentumUpdaterHook(MomentumUpdaterHook): # currently only support by_epoch=False assert not by_epoch, \ 'currently only support "by_epoch" = False' - super(CyclicMomentumUpdaterHook, self).__init__(by_epoch, **kwargs) + super().__init__(by_epoch, **kwargs) def before_run(self, runner): - super(CyclicMomentumUpdaterHook, self).before_run(runner) + super().before_run(runner) # initiate momentum_phases # total momentum_phases are separated as up and down max_iter_per_phase = runner.max_iters // self.cyclic_times @@ -439,7 +439,7 @@ class OneCycleMomentumUpdaterHook(MomentumUpdaterHook): self.anneal_func = annealing_linear self.three_phase = three_phase self.momentum_phases = [] # init momentum_phases - super(OneCycleMomentumUpdaterHook, self).__init__(**kwargs) + super().__init__(**kwargs) def before_run(self, runner): if isinstance(runner.optimizer, dict): diff --git a/mmcv/runner/hooks/optimizer.py b/mmcv/runner/hooks/optimizer.py index b34cc9ddc..a5c10988d 100644 --- a/mmcv/runner/hooks/optimizer.py +++ b/mmcv/runner/hooks/optimizer.py @@ -110,7 +110,7 @@ class GradientCumulativeOptimizerHook(OptimizerHook): """ def __init__(self, cumulative_iters=1, **kwargs): - super(GradientCumulativeOptimizerHook, self).__init__(**kwargs) + super().__init__(**kwargs) assert isinstance(cumulative_iters, int) and cumulative_iters > 0, \ f'cumulative_iters only accepts positive int, but got ' \ @@ -297,8 +297,7 @@ if (TORCH_VERSION != 'parrots' """ def __init__(self, *args, **kwargs): - super(GradientCumulativeFp16OptimizerHook, - self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def after_train_iter(self, runner): if not self.initialized: @@ -490,8 +489,7 @@ else: iters gradient cumulating.""" def __init__(self, *args, **kwargs): - super(GradientCumulativeFp16OptimizerHook, - self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def after_train_iter(self, runner): if not self.initialized: diff --git a/mmcv/runner/iter_based_runner.py b/mmcv/runner/iter_based_runner.py index 9892b07a4..8ab5a041b 100644 --- a/mmcv/runner/iter_based_runner.py +++ b/mmcv/runner/iter_based_runner.py @@ -263,7 +263,7 @@ class IterBasedRunner(BaseRunner): if log_config is not None: for info in log_config['hooks']: info.setdefault('by_epoch', False) - super(IterBasedRunner, self).register_training_hooks( + super().register_training_hooks( lr_config=lr_config, momentum_config=momentum_config, optimizer_config=optimizer_config, diff --git a/mmcv/tensorrt/tensorrt_utils.py b/mmcv/tensorrt/tensorrt_utils.py index ed99893d7..b415abcd7 100644 --- a/mmcv/tensorrt/tensorrt_utils.py +++ b/mmcv/tensorrt/tensorrt_utils.py @@ -54,7 +54,7 @@ def onnx2trt(onnx_model: Union[str, onnx.ModelProto], msg += reset_style warnings.warn(msg) - device = torch.device('cuda:{}'.format(device_id)) + device = torch.device(f'cuda:{device_id}') # create builder and network logger = trt.Logger(log_level) builder = trt.Builder(logger) @@ -209,7 +209,7 @@ class TRTWrapper(torch.nn.Module): msg += reset_style warnings.warn(msg) - super(TRTWrapper, self).__init__() + super().__init__() self.engine = engine if isinstance(self.engine, str): self.engine = load_trt_engine(engine) diff --git a/mmcv/utils/config.py b/mmcv/utils/config.py index 90b64727a..a76bc4872 100644 --- a/mmcv/utils/config.py +++ b/mmcv/utils/config.py @@ -39,7 +39,7 @@ class ConfigDict(Dict): def __getattr__(self, name): try: - value = super(ConfigDict, self).__getattr__(name) + value = super().__getattr__(name) except KeyError: ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") @@ -96,7 +96,7 @@ class Config: @staticmethod def _validate_py_syntax(filename): - with open(filename, 'r', encoding='utf-8') as f: + with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows content = f.read() try: @@ -116,7 +116,7 @@ class Config: fileBasename=file_basename, fileBasenameNoExtension=file_basename_no_extension, fileExtname=file_extname) - with open(filename, 'r', encoding='utf-8') as f: + with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() for key, value in support_templates.items(): @@ -130,7 +130,7 @@ class Config: def _pre_substitute_base_vars(filename, temp_config_name): """Substitute base variable placehoders to string, so that parsing would work.""" - with open(filename, 'r', encoding='utf-8') as f: + with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() base_var_dict = {} @@ -183,7 +183,7 @@ class Config: check_file_exist(filename) fileExtname = osp.splitext(filename)[1] if fileExtname not in ['.py', '.json', '.yaml', '.yml']: - raise IOError('Only py/yml/yaml/json type are supported now!') + raise OSError('Only py/yml/yaml/json type are supported now!') with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile( @@ -236,7 +236,7 @@ class Config: warnings.warn(warning_msg, DeprecationWarning) cfg_text = filename + '\n' - with open(filename, 'r', encoding='utf-8') as f: + with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows cfg_text += f.read() @@ -356,7 +356,7 @@ class Config: :obj:`Config`: Config obj. """ if file_format not in ['.py', '.json', '.yaml', '.yml']: - raise IOError('Only py/yml/yaml/json type are supported now!') + raise OSError('Only py/yml/yaml/json type are supported now!') if file_format != '.py' and 'dict(' in cfg_str: # check if users specify a wrong suffix for python warnings.warn( @@ -396,16 +396,16 @@ class Config: if isinstance(filename, Path): filename = str(filename) - super(Config, self).__setattr__('_cfg_dict', ConfigDict(cfg_dict)) - super(Config, self).__setattr__('_filename', filename) + super().__setattr__('_cfg_dict', ConfigDict(cfg_dict)) + super().__setattr__('_filename', filename) if cfg_text: text = cfg_text elif filename: - with open(filename, 'r') as f: + with open(filename) as f: text = f.read() else: text = '' - super(Config, self).__setattr__('_text', text) + super().__setattr__('_text', text) @property def filename(self): @@ -556,9 +556,9 @@ class Config: def __setstate__(self, state): _cfg_dict, _filename, _text = state - super(Config, self).__setattr__('_cfg_dict', _cfg_dict) - super(Config, self).__setattr__('_filename', _filename) - super(Config, self).__setattr__('_text', _text) + super().__setattr__('_cfg_dict', _cfg_dict) + super().__setattr__('_filename', _filename) + super().__setattr__('_text', _text) def dump(self, file=None): """Dumps config into a file or returns a string representation of the @@ -584,7 +584,7 @@ class Config: will be dumped. Defaults to None. """ import mmcv - cfg_dict = super(Config, self).__getattribute__('_cfg_dict').to_dict() + cfg_dict = super().__getattribute__('_cfg_dict').to_dict() if file is None: if self.filename is None or self.filename.endswith('.py'): return self.pretty_text @@ -638,8 +638,8 @@ class Config: subkey = key_list[-1] d[subkey] = v - cfg_dict = super(Config, self).__getattribute__('_cfg_dict') - super(Config, self).__setattr__( + cfg_dict = super().__getattribute__('_cfg_dict') + super().__setattr__( '_cfg_dict', Config._merge_a_into_b( option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys)) diff --git a/mmcv/utils/timer.py b/mmcv/utils/timer.py index 02e96e537..087a969cf 100644 --- a/mmcv/utils/timer.py +++ b/mmcv/utils/timer.py @@ -6,7 +6,7 @@ class TimerError(Exception): def __init__(self, message): self.message = message - super(TimerError, self).__init__(message) + super().__init__(message) class Timer: diff --git a/mmcv/video/optflow.py b/mmcv/video/optflow.py index 7cea95349..91ce00457 100644 --- a/mmcv/video/optflow.py +++ b/mmcv/video/optflow.py @@ -40,10 +40,10 @@ def flowread(flow_or_path: Union[np.ndarray, str], try: header = f.read(4).decode('utf-8') except Exception: - raise IOError(f'Invalid flow file: {flow_or_path}') + raise OSError(f'Invalid flow file: {flow_or_path}') else: if header != 'PIEH': - raise IOError(f'Invalid flow file: {flow_or_path}, ' + raise OSError(f'Invalid flow file: {flow_or_path}, ' 'header does not contain PIEH') w = np.fromfile(f, np.int32, 1).squeeze() @@ -53,7 +53,7 @@ def flowread(flow_or_path: Union[np.ndarray, str], assert concat_axis in [0, 1] cat_flow = imread(flow_or_path, flag='unchanged') if cat_flow.ndim != 2: - raise IOError( + raise OSError( f'{flow_or_path} is not a valid quantized flow file, ' f'its dimension is {cat_flow.ndim}.') assert cat_flow.shape[concat_axis] % 2 == 0 @@ -86,7 +86,7 @@ def flowwrite(flow: np.ndarray, """ if not quantize: with open(filename, 'wb') as f: - f.write('PIEH'.encode('utf-8')) + f.write(b'PIEH') np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f) flow = flow.astype(np.float32) flow.tofile(f) @@ -146,7 +146,7 @@ def dequantize_flow(dx: np.ndarray, assert dx.shape == dy.shape assert dx.ndim == 2 or (dx.ndim == 3 and dx.shape[-1] == 1) - dx, dy = [dequantize(d, -max_val, max_val, 255) for d in [dx, dy]] + dx, dy = (dequantize(d, -max_val, max_val, 255) for d in [dx, dy]) if denorm: dx *= dx.shape[1] diff --git a/mmcv/visualization/optflow.py b/mmcv/visualization/optflow.py index 948149bea..080b0e61f 100644 --- a/mmcv/visualization/optflow.py +++ b/mmcv/visualization/optflow.py @@ -1,5 +1,4 @@ # Copyright (c) OpenMMLab. All rights reserved. -from __future__ import division from typing import Optional, Union import numpy as np diff --git a/setup.py b/setup.py index c30ed71e7..8d836534f 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,7 @@ def choose_requirement(primary, secondary): def get_version(): version_file = 'mmcv/version.py' - with open(version_file, 'r', encoding='utf-8') as f: + with open(version_file, encoding='utf-8') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__'] @@ -94,12 +94,11 @@ def parse_requirements(fname='requirements/runtime.txt', with_version=True): yield info def parse_require_file(fpath): - with open(fpath, 'r') as f: + with open(fpath) as f: for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): - for info in parse_line(line): - yield info + yield from parse_line(line) def gen_packages_items(): if exists(require_fpath): diff --git a/tests/test_arraymisc.py b/tests/test_arraymisc.py index 8e24b8a52..b29e5f670 100644 --- a/tests/test_arraymisc.py +++ b/tests/test_arraymisc.py @@ -1,5 +1,4 @@ # Copyright (c) OpenMMLab. All rights reserved. -from __future__ import division import numpy as np import pytest diff --git a/tests/test_cnn/test_conv_module.py b/tests/test_cnn/test_conv_module.py index ee89c3f27..3fa8600f6 100644 --- a/tests/test_cnn/test_conv_module.py +++ b/tests/test_cnn/test_conv_module.py @@ -23,7 +23,7 @@ class ExampleConv(nn.Module): groups=1, bias=True, norm_cfg=None): - super(ExampleConv, self).__init__() + super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size diff --git a/tests/test_fileclient.py b/tests/test_fileclient.py index 9a10d930f..92d370245 100644 --- a/tests/test_fileclient.py +++ b/tests/test_fileclient.py @@ -202,21 +202,22 @@ class TestFileClient: # test `list_dir_or_file` with build_temporary_directory() as tmp_dir: # 1. list directories and files - assert set(disk_backend.list_dir_or_file(tmp_dir)) == set( - ['dir1', 'dir2', 'text1.txt', 'text2.txt']) + assert set(disk_backend.list_dir_or_file(tmp_dir)) == { + 'dir1', 'dir2', 'text1.txt', 'text2.txt' + } # 2. list directories and files recursively assert set(disk_backend.list_dir_or_file( - tmp_dir, recursive=True)) == set([ + tmp_dir, recursive=True)) == { 'dir1', osp.join('dir1', 'text3.txt'), 'dir2', osp.join('dir2', 'dir3'), osp.join('dir2', 'dir3', 'text4.txt'), osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt' - ]) + } # 3. only list directories assert set( disk_backend.list_dir_or_file( - tmp_dir, list_file=False)) == set(['dir1', 'dir2']) + tmp_dir, list_file=False)) == {'dir1', 'dir2'} with pytest.raises( TypeError, match='`suffix` should be None when `list_dir` is True'): @@ -227,30 +228,30 @@ class TestFileClient: # 4. only list directories recursively assert set( disk_backend.list_dir_or_file( - tmp_dir, list_file=False, recursive=True)) == set( - ['dir1', 'dir2', - osp.join('dir2', 'dir3')]) + tmp_dir, list_file=False, recursive=True)) == { + 'dir1', 'dir2', + osp.join('dir2', 'dir3') + } # 5. only list files assert set(disk_backend.list_dir_or_file( - tmp_dir, list_dir=False)) == set(['text1.txt', 'text2.txt']) + tmp_dir, list_dir=False)) == {'text1.txt', 'text2.txt'} # 6. only list files recursively assert set( disk_backend.list_dir_or_file( - tmp_dir, list_dir=False, recursive=True)) == set([ + tmp_dir, list_dir=False, recursive=True)) == { osp.join('dir1', 'text3.txt'), osp.join('dir2', 'dir3', 'text4.txt'), osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt' - ]) + } # 7. only list files ending with suffix assert set( disk_backend.list_dir_or_file( tmp_dir, list_dir=False, - suffix='.txt')) == set(['text1.txt', 'text2.txt']) + suffix='.txt')) == {'text1.txt', 'text2.txt'} assert set( disk_backend.list_dir_or_file( tmp_dir, list_dir=False, - suffix=('.txt', - '.jpg'))) == set(['text1.txt', 'text2.txt']) + suffix=('.txt', '.jpg'))) == {'text1.txt', 'text2.txt'} with pytest.raises( TypeError, match='`suffix` must be a string or tuple of strings'): @@ -260,22 +261,22 @@ class TestFileClient: assert set( disk_backend.list_dir_or_file( tmp_dir, list_dir=False, suffix='.txt', - recursive=True)) == set([ + recursive=True)) == { osp.join('dir1', 'text3.txt'), osp.join('dir2', 'dir3', 'text4.txt'), 'text1.txt', 'text2.txt' - ]) + } # 7. only list files ending with suffix assert set( disk_backend.list_dir_or_file( tmp_dir, list_dir=False, suffix=('.txt', '.jpg'), - recursive=True)) == set([ + recursive=True)) == { osp.join('dir1', 'text3.txt'), osp.join('dir2', 'dir3', 'text4.txt'), osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt' - ]) + } @patch('ceph.S3Client', MockS3Client) def test_ceph_backend(self): @@ -463,21 +464,21 @@ class TestFileClient: with build_temporary_directory() as tmp_dir: # 1. list directories and files - assert set(petrel_backend.list_dir_or_file(tmp_dir)) == set( - ['dir1', 'dir2', 'text1.txt', 'text2.txt']) + assert set(petrel_backend.list_dir_or_file(tmp_dir)) == { + 'dir1', 'dir2', 'text1.txt', 'text2.txt' + } # 2. list directories and files recursively assert set( - petrel_backend.list_dir_or_file( - tmp_dir, recursive=True)) == set([ - 'dir1', '/'.join(('dir1', 'text3.txt')), 'dir2', - '/'.join(('dir2', 'dir3')), '/'.join( + petrel_backend.list_dir_or_file(tmp_dir, recursive=True)) == { + 'dir1', '/'.join(('dir1', 'text3.txt')), 'dir2', '/'.join( + ('dir2', 'dir3')), '/'.join( ('dir2', 'dir3', 'text4.txt')), '/'.join( ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt' - ]) + } # 3. only list directories assert set( petrel_backend.list_dir_or_file( - tmp_dir, list_file=False)) == set(['dir1', 'dir2']) + tmp_dir, list_file=False)) == {'dir1', 'dir2'} with pytest.raises( TypeError, match=('`list_dir` should be False when `suffix` is not ' @@ -489,31 +490,30 @@ class TestFileClient: # 4. only list directories recursively assert set( petrel_backend.list_dir_or_file( - tmp_dir, list_file=False, recursive=True)) == set( - ['dir1', 'dir2', '/'.join(('dir2', 'dir3'))]) + tmp_dir, list_file=False, recursive=True)) == { + 'dir1', 'dir2', '/'.join(('dir2', 'dir3')) + } # 5. only list files assert set( - petrel_backend.list_dir_or_file(tmp_dir, - list_dir=False)) == set( - ['text1.txt', 'text2.txt']) + petrel_backend.list_dir_or_file( + tmp_dir, list_dir=False)) == {'text1.txt', 'text2.txt'} # 6. only list files recursively assert set( petrel_backend.list_dir_or_file( - tmp_dir, list_dir=False, recursive=True)) == set([ + tmp_dir, list_dir=False, recursive=True)) == { '/'.join(('dir1', 'text3.txt')), '/'.join( ('dir2', 'dir3', 'text4.txt')), '/'.join( ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt' - ]) + } # 7. only list files ending with suffix assert set( petrel_backend.list_dir_or_file( tmp_dir, list_dir=False, - suffix='.txt')) == set(['text1.txt', 'text2.txt']) + suffix='.txt')) == {'text1.txt', 'text2.txt'} assert set( petrel_backend.list_dir_or_file( tmp_dir, list_dir=False, - suffix=('.txt', - '.jpg'))) == set(['text1.txt', 'text2.txt']) + suffix=('.txt', '.jpg'))) == {'text1.txt', 'text2.txt'} with pytest.raises( TypeError, match='`suffix` must be a string or tuple of strings'): @@ -523,22 +523,22 @@ class TestFileClient: assert set( petrel_backend.list_dir_or_file( tmp_dir, list_dir=False, suffix='.txt', - recursive=True)) == set([ + recursive=True)) == { '/'.join(('dir1', 'text3.txt')), '/'.join( ('dir2', 'dir3', 'text4.txt')), 'text1.txt', 'text2.txt' - ]) + } # 7. only list files ending with suffix assert set( petrel_backend.list_dir_or_file( tmp_dir, list_dir=False, suffix=('.txt', '.jpg'), - recursive=True)) == set([ + recursive=True)) == { '/'.join(('dir1', 'text3.txt')), '/'.join( ('dir2', 'dir3', 'text4.txt')), '/'.join( ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt' - ]) + } @patch('mc.MemcachedClient.GetInstance', MockMemcachedClient) @patch('mc.pyvector', MagicMock) diff --git a/tests/test_fileio.py b/tests/test_fileio.py index 556a44a13..f5e23bf7f 100644 --- a/tests/test_fileio.py +++ b/tests/test_fileio.py @@ -128,7 +128,7 @@ def test_register_handler(): assert content == '1.jpg\n2.jpg\n3.jpg\n4.jpg\n5.jpg' tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test.txt2') mmcv.dump(content, tmp_filename) - with open(tmp_filename, 'r') as f: + with open(tmp_filename) as f: written = f.read() os.remove(tmp_filename) assert written == '\n' + content diff --git a/tests/test_ops/test_bbox.py b/tests/test_ops/test_bbox.py index 887804482..f276d0d58 100644 --- a/tests/test_ops/test_bbox.py +++ b/tests/test_ops/test_bbox.py @@ -6,7 +6,7 @@ import torch from mmcv.utils import IS_CUDA_AVAILABLE, IS_MLU_AVAILABLE -class TestBBox(object): +class TestBBox: def _test_bbox_overlaps(self, device='cpu', dtype=torch.float): from mmcv.ops import bbox_overlaps diff --git a/tests/test_ops/test_bilinear_grid_sample.py b/tests/test_ops/test_bilinear_grid_sample.py index d8ac22f6b..8f43d4ff2 100644 --- a/tests/test_ops/test_bilinear_grid_sample.py +++ b/tests/test_ops/test_bilinear_grid_sample.py @@ -4,7 +4,7 @@ import torch import torch.nn.functional as F -class TestBilinearGridSample(object): +class TestBilinearGridSample: def _test_bilinear_grid_sample(self, dtype=torch.float, diff --git a/tests/test_ops/test_box_iou_rotated.py b/tests/test_ops/test_box_iou_rotated.py index 847644339..9f5e0dfa3 100644 --- a/tests/test_ops/test_box_iou_rotated.py +++ b/tests/test_ops/test_box_iou_rotated.py @@ -4,7 +4,7 @@ import pytest import torch -class TestBoxIoURotated(object): +class TestBoxIoURotated: def test_box_iou_rotated_cpu(self): from mmcv.ops import box_iou_rotated diff --git a/tests/test_ops/test_carafe.py b/tests/test_ops/test_carafe.py index 3a4c6bef7..6b545a027 100644 --- a/tests/test_ops/test_carafe.py +++ b/tests/test_ops/test_carafe.py @@ -3,7 +3,7 @@ import torch from torch.autograd import gradcheck -class TestCarafe(object): +class TestCarafe: def test_carafe_naive_gradcheck(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_cc_attention.py b/tests/test_ops/test_cc_attention.py index 3da739b75..b2a8d22a3 100644 --- a/tests/test_ops/test_cc_attention.py +++ b/tests/test_ops/test_cc_attention.py @@ -15,7 +15,7 @@ class Loss(nn.Module): return torch.mean(input - target) -class TestCrissCrossAttention(object): +class TestCrissCrossAttention: def test_cc_attention(self): device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') diff --git a/tests/test_ops/test_deform_conv.py b/tests/test_ops/test_deform_conv.py index cbea9156c..e77b5f975 100644 --- a/tests/test_ops/test_deform_conv.py +++ b/tests/test_ops/test_deform_conv.py @@ -35,7 +35,7 @@ gt_offset_bias_grad = [1.44, -0.72, 0., 0., -0.10, -0.08, -0.54, -0.54], gt_deform_weight_grad = [[[[3.62, 0.], [0.40, 0.18]]]] -class TestDeformconv(object): +class TestDeformconv: def _test_deformconv(self, dtype=torch.float, diff --git a/tests/test_ops/test_deform_roi_pool.py b/tests/test_ops/test_deform_roi_pool.py index 7dbca1a29..37a279ec9 100644 --- a/tests/test_ops/test_deform_roi_pool.py +++ b/tests/test_ops/test_deform_roi_pool.py @@ -35,7 +35,7 @@ outputs = [([[[[1, 1.25], [1.5, 1.75]]]], [[[[3.0625, 0.4375], 0.00390625]]]])] -class TestDeformRoIPool(object): +class TestDeformRoIPool: def test_deform_roi_pool_gradcheck(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_focal_loss.py b/tests/test_ops/test_focal_loss.py index 9bdd4600b..316f58469 100644 --- a/tests/test_ops/test_focal_loss.py +++ b/tests/test_ops/test_focal_loss.py @@ -37,7 +37,7 @@ sigmoid_outputs = [(0.13562961, [[-0.00657264, 0.11185755], [-0.02462499, 0.08277918, 0.18050370]])] -class Testfocalloss(object): +class Testfocalloss: def _test_softmax(self, dtype=torch.float): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_fused_bias_leakyrelu.py b/tests/test_ops/test_fused_bias_leakyrelu.py index c0169ea6c..47357860d 100644 --- a/tests/test_ops/test_fused_bias_leakyrelu.py +++ b/tests/test_ops/test_fused_bias_leakyrelu.py @@ -10,7 +10,7 @@ except ImportError: _USING_PARROTS = False -class TestFusedBiasLeakyReLU(object): +class TestFusedBiasLeakyReLU: @classmethod def setup_class(cls): diff --git a/tests/test_ops/test_info.py b/tests/test_ops/test_info.py index ba467cbde..e3c1722eb 100644 --- a/tests/test_ops/test_info.py +++ b/tests/test_ops/test_info.py @@ -2,7 +2,7 @@ import torch -class TestInfo(object): +class TestInfo: def test_info(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_masked_conv2d.py b/tests/test_ops/test_masked_conv2d.py index 9150fb5b1..4516b22e9 100644 --- a/tests/test_ops/test_masked_conv2d.py +++ b/tests/test_ops/test_masked_conv2d.py @@ -2,7 +2,7 @@ import torch -class TestMaskedConv2d(object): +class TestMaskedConv2d: def test_masked_conv2d(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_modulated_deform_conv.py b/tests/test_ops/test_modulated_deform_conv.py index 5386cc78c..3b9070491 100644 --- a/tests/test_ops/test_modulated_deform_conv.py +++ b/tests/test_ops/test_modulated_deform_conv.py @@ -37,7 +37,7 @@ dcn_offset_b_grad = [ ] -class TestMdconv(object): +class TestMdconv: def _test_mdconv(self, dtype=torch.float, device='cuda'): if not torch.cuda.is_available() and device == 'cuda': diff --git a/tests/test_ops/test_ms_deformable_attn.py b/tests/test_ops/test_ms_deformable_attn.py index fee94c575..3ebbf6bdf 100644 --- a/tests/test_ops/test_ms_deformable_attn.py +++ b/tests/test_ops/test_ms_deformable_attn.py @@ -55,7 +55,7 @@ def test_forward_multi_scale_deformable_attn_pytorch(): N, M, D = 1, 2, 2 Lq, L, P = 2, 2, 2 shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long) - S = sum([(H * W).item() for H, W in shapes]) + S = sum((H * W).item() for H, W in shapes) torch.manual_seed(3) value = torch.rand(N, S, M, D) * 0.01 @@ -78,7 +78,7 @@ def test_forward_equal_with_pytorch_double(): shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros( (1, )), shapes.prod(1).cumsum(0)[:-1])) - S = sum([(H * W).item() for H, W in shapes]) + S = sum((H * W).item() for H, W in shapes) torch.manual_seed(3) value = torch.rand(N, S, M, D).cuda() * 0.01 @@ -111,7 +111,7 @@ def test_forward_equal_with_pytorch_float(): shapes = torch.as_tensor([(6, 4), (3, 2)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros( (1, )), shapes.prod(1).cumsum(0)[:-1])) - S = sum([(H * W).item() for H, W in shapes]) + S = sum((H * W).item() for H, W in shapes) torch.manual_seed(3) value = torch.rand(N, S, M, D).cuda() * 0.01 @@ -155,7 +155,7 @@ def test_gradient_numerical(channels, shapes = torch.as_tensor([(3, 2), (2, 1)], dtype=torch.long).cuda() level_start_index = torch.cat((shapes.new_zeros( (1, )), shapes.prod(1).cumsum(0)[:-1])) - S = sum([(H * W).item() for H, W in shapes]) + S = sum((H * W).item() for H, W in shapes) value = torch.rand(N, S, M, channels).cuda() * 0.01 sampling_locations = torch.rand(N, Lq, M, L, P, 2).cuda() diff --git a/tests/test_ops/test_nms.py b/tests/test_ops/test_nms.py index 2e2d996b3..aece8ad5e 100644 --- a/tests/test_ops/test_nms.py +++ b/tests/test_ops/test_nms.py @@ -6,7 +6,7 @@ import torch from mmcv.utils import IS_CUDA_AVAILABLE, IS_MLU_AVAILABLE -class Testnms(object): +class Testnms: @pytest.mark.parametrize('device', [ pytest.param( @@ -129,8 +129,7 @@ class Testnms(object): scores = tensor_dets[:, 4] nms_keep_inds = nms(boxes.contiguous(), scores.contiguous(), iou_thr)[1] - assert set([g[0].item() - for g in np_groups]) == set(nms_keep_inds.tolist()) + assert {g[0].item() for g in np_groups} == set(nms_keep_inds.tolist()) # non empty tensor input tensor_dets = torch.from_numpy(np_dets) diff --git a/tests/test_ops/test_onnx.py b/tests/test_ops/test_onnx.py index 2ecc83e80..b80140a37 100644 --- a/tests/test_ops/test_onnx.py +++ b/tests/test_ops/test_onnx.py @@ -33,7 +33,7 @@ def run_before_and_after_test(): class WrapFunction(nn.Module): def __init__(self, wrapped_function): - super(WrapFunction, self).__init__() + super().__init__() self.wrapped_function = wrapped_function def forward(self, *args, **kwargs): @@ -662,7 +662,7 @@ def test_cummax_cummin(key, opset=11): input_list = [ # arbitrary shape, e.g. 1-D, 2-D, 3-D, ... torch.rand((2, 3, 4, 1, 5)), - torch.rand((1)), + torch.rand(1), torch.rand((2, 0, 1)), # tensor.numel() is 0 torch.FloatTensor(), # empty tensor ] diff --git a/tests/test_ops/test_psa_mask.py b/tests/test_ops/test_psa_mask.py index 266f466af..c79323c99 100644 --- a/tests/test_ops/test_psa_mask.py +++ b/tests/test_ops/test_psa_mask.py @@ -15,7 +15,7 @@ class Loss(nn.Module): return torch.mean(input - target) -class TestPSAMask(object): +class TestPSAMask: def test_psa_mask_collect(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_roi_pool.py b/tests/test_ops/test_roi_pool.py index db7180eab..aff0386c3 100644 --- a/tests/test_ops/test_roi_pool.py +++ b/tests/test_ops/test_roi_pool.py @@ -29,7 +29,7 @@ outputs = [([[[[1., 2.], [3., 4.]]]], [[[[1., 1.], [1., 1.]]]]), 1.]]]])] -class TestRoiPool(object): +class TestRoiPool: def test_roipool_gradcheck(self): if not torch.cuda.is_available(): diff --git a/tests/test_ops/test_syncbn.py b/tests/test_ops/test_syncbn.py index fb3c1a07b..d1c1605ad 100644 --- a/tests/test_ops/test_syncbn.py +++ b/tests/test_ops/test_syncbn.py @@ -14,7 +14,7 @@ else: import re -class TestSyncBN(object): +class TestSyncBN: def dist_init(self): rank = int(os.environ['SLURM_PROCID']) diff --git a/tests/test_ops/test_tensorrt.py b/tests/test_ops/test_tensorrt.py index d3b737dd0..f7a1057f8 100644 --- a/tests/test_ops/test_tensorrt.py +++ b/tests/test_ops/test_tensorrt.py @@ -30,7 +30,7 @@ if not is_tensorrt_plugin_loaded(): class WrapFunction(nn.Module): def __init__(self, wrapped_function): - super(WrapFunction, self).__init__() + super().__init__() self.wrapped_function = wrapped_function def forward(self, *args, **kwargs): @@ -576,7 +576,7 @@ def test_cummin_cummax(func: Callable): input_list = [ # arbitrary shape, e.g. 1-D, 2-D, 3-D, ... torch.rand((2, 3, 4, 1, 5)).cuda(), - torch.rand((1)).cuda() + torch.rand(1).cuda() ] input_names = ['input'] @@ -756,7 +756,7 @@ def test_corner_pool(mode): class CornerPoolWrapper(CornerPool): def __init__(self, mode): - super(CornerPoolWrapper, self).__init__(mode) + super().__init__(mode) def forward(self, x): # no use `torch.cummax`, instead `corner_pool` is used diff --git a/tests/test_ops/test_upfirdn2d.py b/tests/test_ops/test_upfirdn2d.py index 794869dc4..6037a51c2 100644 --- a/tests/test_ops/test_upfirdn2d.py +++ b/tests/test_ops/test_upfirdn2d.py @@ -10,7 +10,7 @@ except ImportError: _USING_PARROTS = False -class TestUpFirDn2d(object): +class TestUpFirDn2d: """Unit test for UpFirDn2d. Here, we just test the basic case of upsample version. More gerneal tests diff --git a/tests/test_ops/test_voxelization.py b/tests/test_ops/test_voxelization.py index 6f0fa9aef..d3555ac69 100644 --- a/tests/test_ops/test_voxelization.py +++ b/tests/test_ops/test_voxelization.py @@ -96,8 +96,8 @@ def test_voxelization_nondeterministic(): coors_all = dynamic_voxelization.forward(points) coors_all = coors_all.cpu().detach().numpy().tolist() - coors_set = set([tuple(c) for c in coors]) - coors_all_set = set([tuple(c) for c in coors_all]) + coors_set = {tuple(c) for c in coors} + coors_all_set = {tuple(c) for c in coors_all} assert len(coors_set) == len(coors) assert len(coors_set - coors_all_set) == 0 @@ -112,7 +112,7 @@ def test_voxelization_nondeterministic(): for c, ps, n in zip(coors, voxels, num_points_per_voxel): ideal_voxel_points_set = coors_points_dict[tuple(c)] - voxel_points_set = set([tuple(p) for p in ps[:n]]) + voxel_points_set = {tuple(p) for p in ps[:n]} assert len(voxel_points_set) == n if n < max_num_points: assert voxel_points_set == ideal_voxel_points_set @@ -133,7 +133,7 @@ def test_voxelization_nondeterministic(): voxels, coors, num_points_per_voxel = hard_voxelization.forward(points) coors = coors.cpu().detach().numpy().tolist() - coors_set = set([tuple(c) for c in coors]) - coors_all_set = set([tuple(c) for c in coors_all]) + coors_set = {tuple(c) for c in coors} + coors_all_set = {tuple(c) for c in coors_all} assert len(coors_set) == len(coors) == len(coors_all_set) diff --git a/tests/test_parallel.py b/tests/test_parallel.py index e04fa449f..214926ee1 100644 --- a/tests/test_parallel.py +++ b/tests/test_parallel.py @@ -63,7 +63,7 @@ def test_is_module_wrapper(): # test module wrapper registry @MODULE_WRAPPERS.register_module() - class ModuleWrapper(object): + class ModuleWrapper: def __init__(self, module): self.module = module diff --git a/tests/test_runner/test_basemodule.py b/tests/test_runner/test_basemodule.py index 558d7e22f..1f186bf82 100644 --- a/tests/test_runner/test_basemodule.py +++ b/tests/test_runner/test_basemodule.py @@ -105,7 +105,7 @@ def test_initilization_info_logger(): class CheckLoggerModel(BaseModule): def __init__(self, init_cfg=None): - super(CheckLoggerModel, self).__init__(init_cfg) + super().__init__(init_cfg) self.conv1 = nn.Conv2d(1, 1, 1, 1) self.conv2 = OverloadInitConv(1, 1, 1, 1) self.conv3 = nn.Conv2d(1, 1, 1, 1) @@ -151,7 +151,7 @@ def test_initilization_info_logger(): class OverloadInitConvFc(nn.Conv2d, BaseModule): def __init__(self, *args, **kwargs): - super(OverloadInitConvFc, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.conv1 = nn.Linear(1, 1) def init_weights(self): @@ -162,7 +162,7 @@ def test_initilization_info_logger(): class CheckLoggerModel(BaseModule): def __init__(self, init_cfg=None): - super(CheckLoggerModel, self).__init__(init_cfg) + super().__init__(init_cfg) self.conv1 = nn.Conv2d(1, 1, 1, 1) self.conv2 = OverloadInitConvFc(1, 1, 1, 1) self.conv3 = nn.Conv2d(1, 1, 1, 1) @@ -171,7 +171,7 @@ def test_initilization_info_logger(): class TopLevelModule(BaseModule): def __init__(self, init_cfg=None, checklog_init_cfg=None): - super(TopLevelModule, self).__init__(init_cfg) + super().__init__(init_cfg) self.module1 = CheckLoggerModel(checklog_init_cfg) self.module2 = OverloadInitConvFc(1, 1, 1, 1) diff --git a/tests/test_runner/test_checkpoint.py b/tests/test_runner/test_checkpoint.py index 0a0f0885c..95ab7bcaf 100644 --- a/tests/test_runner/test_checkpoint.py +++ b/tests/test_runner/test_checkpoint.py @@ -22,7 +22,7 @@ sys.modules['petrel_client.client'] = MagicMock() @MODULE_WRAPPERS.register_module() -class DDPWrapper(object): +class DDPWrapper: def __init__(self, module): self.module = module @@ -44,7 +44,7 @@ class Model(nn.Module): self.conv = nn.Conv2d(3, 3, 1) -class Mockpavimodel(object): +class Mockpavimodel: def __init__(self, name='fakename'): self.name = name @@ -59,18 +59,18 @@ def assert_tensor_equal(tensor_a, tensor_b): def test_get_state_dict(): if torch.__version__ == 'parrots': - state_dict_keys = set([ + state_dict_keys = { 'block.conv.weight', 'block.conv.bias', 'block.norm.weight', 'block.norm.bias', 'block.norm.running_mean', 'block.norm.running_var', 'conv.weight', 'conv.bias' - ]) + } else: - state_dict_keys = set([ + state_dict_keys = { 'block.conv.weight', 'block.conv.bias', 'block.norm.weight', 'block.norm.bias', 'block.norm.running_mean', 'block.norm.running_var', 'block.norm.num_batches_tracked', 'conv.weight', 'conv.bias' - ]) + } model = Model() state_dict = get_state_dict(model) diff --git a/tests/test_runner/test_fp16.py b/tests/test_runner/test_fp16.py index e9d68d471..e34c909cb 100644 --- a/tests/test_runner/test_fp16.py +++ b/tests/test_runner/test_fp16.py @@ -70,7 +70,7 @@ def test_auto_fp16(): with pytest.raises(TypeError): # ExampleObject is not a subclass of nn.Module - class ExampleObject(object): + class ExampleObject: @auto_fp16() def __call__(self, x): @@ -196,7 +196,7 @@ def test_force_fp32(): with pytest.raises(TypeError): # ExampleObject is not a subclass of nn.Module - class ExampleObject(object): + class ExampleObject: @force_fp32() def __call__(self, x): diff --git a/tests/test_utils/test_config.py b/tests/test_utils/test_config.py index 0e0a3eedd..96118e710 100644 --- a/tests/test_utils/test_config.py +++ b/tests/test_utils/test_config.py @@ -35,12 +35,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=item) assert isinstance(cfg, Config) assert isinstance(cfg.filename, str) and cfg.filename == str(item) - assert cfg.text == open(item, 'r').read() + assert cfg.text == open(item).read() assert cfg.dump() == cfg.pretty_text with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'a.py') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) # test b.json @@ -48,12 +48,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=cfg_file) assert isinstance(cfg, Config) assert cfg.filename == cfg_file - assert cfg.text == open(cfg_file, 'r').read() + assert cfg.text == open(cfg_file).read() assert cfg.dump() == json.dumps(cfg_dict) with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'b.json') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) # test c.yaml @@ -61,12 +61,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=cfg_file) assert isinstance(cfg, Config) assert cfg.filename == cfg_file - assert cfg.text == open(cfg_file, 'r').read() + assert cfg.text == open(cfg_file).read() assert cfg.dump() == yaml.dump(cfg_dict) with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'c.yaml') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) # test h.py @@ -82,12 +82,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=cfg_file) assert isinstance(cfg, Config) assert cfg.filename == cfg_file - assert cfg.text == open(cfg_file, 'r').read() + assert cfg.text == open(cfg_file).read() assert cfg.dump() == cfg.pretty_text with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'h.py') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1'] assert Config.fromfile(dump_file)['item2'] == cfg_dict['item2'] @@ -109,12 +109,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=cfg_file) assert isinstance(cfg, Config) assert cfg.filename == cfg_file - assert cfg.text == open(cfg_file, 'r').read() + assert cfg.text == open(cfg_file).read() assert cfg.dump() == yaml.dump(cfg_dict) with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'p.yaml') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1'] @@ -128,12 +128,12 @@ def test_construct(): cfg = Config(cfg_dict, filename=cfg_file) assert isinstance(cfg, Config) assert cfg.filename == cfg_file - assert cfg.text == open(cfg_file, 'r').read() + assert cfg.text == open(cfg_file).read() assert cfg.dump() == json.dumps(cfg_dict) with tempfile.TemporaryDirectory() as temp_config_dir: dump_file = osp.join(temp_config_dir, 'o.json') cfg.dump(dump_file) - assert cfg.dump() == open(dump_file, 'r').read() + assert cfg.dump() == open(dump_file).read() assert Config.fromfile(dump_file) assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1'] @@ -152,7 +152,7 @@ def test_fromfile(): assert isinstance(cfg, Config) assert isinstance(cfg.filename, str) and cfg.filename == str(item) assert cfg.text == osp.abspath(osp.expanduser(item)) + '\n' + \ - open(item, 'r').read() + open(item).read() # test custom_imports for Config.fromfile cfg_file = osp.join(data_path, 'config', 'q.py') @@ -182,7 +182,7 @@ def test_fromstring(): out_cfg = Config.fromstring(in_cfg.pretty_text, '.py') assert in_cfg._cfg_dict == out_cfg._cfg_dict - cfg_str = open(cfg_file, 'r').read() + cfg_str = open(cfg_file).read() out_cfg = Config.fromstring(cfg_str, file_format) assert in_cfg._cfg_dict == out_cfg._cfg_dict @@ -193,7 +193,7 @@ def test_fromstring(): Config.fromstring(in_cfg.pretty_text, '.json') # test file format error - cfg_str = open(cfg_file, 'r').read() + cfg_str = open(cfg_file).read() with pytest.raises(Exception): Config.fromstring(cfg_str, '.py') @@ -205,9 +205,9 @@ def test_merge_from_base(): assert cfg.filename == cfg_file base_cfg_file = osp.join(data_path, 'config/base.py') merge_text = osp.abspath(osp.expanduser(base_cfg_file)) + '\n' + \ - open(base_cfg_file, 'r').read() + open(base_cfg_file).read() merge_text += '\n' + osp.abspath(osp.expanduser(cfg_file)) + '\n' + \ - open(cfg_file, 'r').read() + open(cfg_file).read() assert cfg.text == merge_text assert cfg.item1 == [2, 3] assert cfg.item2.a == 1 diff --git a/tests/test_utils/test_logging.py b/tests/test_utils/test_logging.py index f6f9cfb36..ab66a34b9 100644 --- a/tests/test_utils/test_logging.py +++ b/tests/test_utils/test_logging.py @@ -101,7 +101,7 @@ def test_print_log_logger(caplog): logger = get_logger('abc', log_file=f.name) print_log('welcome', logger=logger) assert caplog.record_tuples[-1] == ('abc', logging.INFO, 'welcome') - with open(f.name, 'r') as fin: + with open(f.name) as fin: log_text = fin.read() regex_time = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}' match = re.fullmatch(regex_time + r' - abc - INFO - welcome\n', diff --git a/tests/test_utils/test_parrots_jit.py b/tests/test_utils/test_parrots_jit.py index 7b981181e..71be929fb 100644 --- a/tests/test_utils/test_parrots_jit.py +++ b/tests/test_utils/test_parrots_jit.py @@ -10,7 +10,7 @@ skip_no_parrots = pytest.mark.skipif( TORCH_VERSION != 'parrots', reason='test case under parrots environment') -class TestJit(object): +class TestJit: def test_add_dict(self): @@ -255,7 +255,7 @@ class TestJit(object): def test_instance_method(self): - class T(object): + class T: def __init__(self, shape): self._c = torch.rand(shape) diff --git a/tests/test_utils/test_path.py b/tests/test_utils/test_path.py index 299c87fd3..56d65ce26 100644 --- a/tests/test_utils/test_path.py +++ b/tests/test_utils/test_path.py @@ -30,12 +30,14 @@ def test_scandir(): filenames = ['a.bin', '1.txt', '2.txt', '1.json', '2.json', '3.TXT'] assert set(mmcv.scandir(folder)) == set(filenames) assert set(mmcv.scandir(Path(folder))) == set(filenames) - assert set(mmcv.scandir(folder, '.txt')) == set( - [filename for filename in filenames if filename.endswith('.txt')]) - assert set(mmcv.scandir(folder, ('.json', '.txt'))) == set([ - filename for filename in filenames - if filename.endswith(('.txt', '.json')) - ]) + assert set(mmcv.scandir(folder, '.txt')) == { + filename + for filename in filenames if filename.endswith('.txt') + } + assert set(mmcv.scandir(folder, ('.json', '.txt'))) == { + filename + for filename in filenames if filename.endswith(('.txt', '.json')) + } assert set(mmcv.scandir(folder, '.png')) == set() # path of sep is `\\` in windows but `/` in linux, so osp.join should be @@ -46,27 +48,33 @@ def test_scandir(): osp.join('sub', '1.txt'), '.file' ] # .file starts with '.' and is a file so it will not be scanned - assert set(mmcv.scandir(folder, recursive=True)) == set( - [filename for filename in filenames_recursive if filename != '.file']) - assert set(mmcv.scandir(Path(folder), recursive=True)) == set( - [filename for filename in filenames_recursive if filename != '.file']) - assert set(mmcv.scandir(folder, '.txt', recursive=True)) == set([ - filename for filename in filenames_recursive - if filename.endswith('.txt') - ]) + assert set(mmcv.scandir(folder, recursive=True)) == { + filename + for filename in filenames_recursive if filename != '.file' + } + assert set(mmcv.scandir(Path(folder), recursive=True)) == { + filename + for filename in filenames_recursive if filename != '.file' + } + assert set(mmcv.scandir(folder, '.txt', recursive=True)) == { + filename + for filename in filenames_recursive if filename.endswith('.txt') + } assert set( mmcv.scandir(folder, '.TXT', recursive=True, - case_sensitive=False)) == set([ - filename for filename in filenames_recursive + case_sensitive=False)) == { + filename + for filename in filenames_recursive if filename.endswith(('.txt', '.TXT')) - ]) + } assert set( mmcv.scandir( folder, ('.TXT', '.JSON'), recursive=True, - case_sensitive=False)) == set([ - filename for filename in filenames_recursive + case_sensitive=False)) == { + filename + for filename in filenames_recursive if filename.endswith(('.txt', '.json', '.TXT')) - ]) + } with pytest.raises(TypeError): list(mmcv.scandir(123)) with pytest.raises(TypeError): diff --git a/tests/test_utils/test_progressbar.py b/tests/test_utils/test_progressbar.py index 730f45697..982aa247f 100644 --- a/tests/test_utils/test_progressbar.py +++ b/tests/test_utils/test_progressbar.py @@ -1,18 +1,10 @@ # Copyright (c) OpenMMLab. All rights reserved. import os import time +from io import StringIO +from unittest.mock import patch -try: - from unittest.mock import patch -except ImportError: - from mock import patch - -try: - from StringIO import StringIO -except ImportError: - from io import StringIO - -import mmcv # isort:skip +import mmcv def reset_string_io(io): diff --git a/tests/test_utils/test_testing.py b/tests/test_utils/test_testing.py index f428b9de6..c6f8e8d12 100644 --- a/tests/test_utils/test_testing.py +++ b/tests/test_utils/test_testing.py @@ -70,7 +70,7 @@ def test_assert_dict_contains_subset(): def test_assert_attrs_equal(): - class TestExample(object): + class TestExample: a, b, c = 1, ('wvi', 3), [4.5, 3.14] def test_func(self): @@ -104,7 +104,7 @@ def test_assert_attrs_equal(): if torch is not None: - class TestExample(object): + class TestExample: a, b = torch.tensor([1]), torch.tensor([4, 5]) # case 5 diff --git a/tests/test_utils/test_version_utils.py b/tests/test_utils/test_version_utils.py index e20d750fe..5400e3c86 100644 --- a/tests/test_utils/test_version_utils.py +++ b/tests/test_utils/test_version_utils.py @@ -41,7 +41,7 @@ def test_parse_version_info(): def _mock_cmd_success(cmd): - return '3b46d33e90c397869ad5103075838fdfc9812aa0'.encode('ascii') + return b'3b46d33e90c397869ad5103075838fdfc9812aa0' def _mock_cmd_fail(cmd):