mirror of
https://github.com/open-mmlab/mmselfsup.git
synced 2025-06-03 14:59:38 +08:00
* [Enhance] add pre-commit hook for algo-readme and copyright (#213) * [Enhance] add test windows in workflows (#215) * [Enhance] add test windows in workflows * fix lint * add optional requirements * add try-except judgement * add opencv installation in windows test steps * fix path error on windows * update * update path * update * add pytest skip for algorithm test * update requirements/runtime.txt * update pytest skip * [Docs] translate 0_config.md into Chinese (#216) * [Docs] translate 0_config.md into Chinese * [Fix] fix format description in 0_config.md * Update: 0_config.md * [Fix] fix tsne 'no `init_cfg`' error (#222) * [Fix] fix tsne 'no init_cfg' and pool_type errors * [Refactor] fix linting of tsne vis * [Docs] reorganizing OpenMMLab projects and update algorithms in readme (#219) * [Docs] reorganizing OpenMMLab projects and update algorithms in readme * using small letters * fix typo * [Fix] fix image channel bgr/rgb bug and update benchmarks (#210) * [Fix] fix image channel bgr/rgb bug * update model zoo * update readme and metafile * [Fix] fix typo * [Fix] fix typo * [Fix] fix lint * modify Places205 directory according to the downloaded dataset * update results * [Fix] Fix the bug when using prefetch under multi-view methods, e.g., DenseCL (#218) * fig bug for prefetch_loader under multi-view setting * fix lint problem Co-authored-by: liming <liming.ai@bytedance.com> * [Feature]: MAE official (#221) * [Feature]: MAE single image pre-training * [Fix]: Fix config * [Fix]: Fix dataset link * [Feature]: Add run * [Refactor]: Delete spot * [Feature]: ignore nohup output file * [Feature]: Add auto script to generate run cmd * [Refactor]: Refactor mae config file * [Feature]: sz20 settings * [Feature]: Add auto resume * [Fix]: Fix lint * [Feature]: Make git ignore txt * [Refactor]: Delete gpus in script * [Fix]: Make generate_cmd to add --async * [Feature]: Initial version of Vit fine-tune * [Fix]: Add 1424 specific settings * [Fix]: Fix missing file client bug for 1424 * [Feature]: 1424 customized settings * [Fix]: Make drop in eval to False * [Feature]: Change the finetune and pre-training settings * [Feature]: Add debug setting * [Refactor]: Refactor the model * [Feature]: Customized settings * [Feature]: Add A100 settings * [Fix]: Change mae to imagenet * [Feature]: Change mae pretrain num workers to 32 * [Feature]: Change num workers to 16 * [Feature]: Add A100 setting for pre_release ft version * [Feature]: Add img_norm_cfg * [Fix]: Fix mae cls test missing logits bug * [Fix]: Fix mae cls head bias initialize to zero * [Feature]: Rename mae config name * [Feature]: Add MAE README.md * [Fix]: Fix lint * [Feature]: Fix typo * [Fix]: Fix typo * [Feature]: Fix invalid link * [Fix]: Fix finetune config file name * [Feature]: Official pretrain v1 * [Feature]: Change log interval to 100 * [Feature]: pretrain 1600 epochs * [Fix]: Change encoder num head to 12 * [Feature]: Mix precision * [Feature]: Add default value to random masking * [Feature]: Official MAE finetune * [Feature]: Finetune img per gpu 32 * [Feature]: Add multi machine training for lincls * [Fix]: Fix lincls master port master addr * [Feature]: Change img per gpu to 128 * [Feature]: Add linear eval and Refactor * [Fix]: Fix debug mode * [Fix]: Delete MAE dataset in __init__.py * [Feature]: normalize pixel for mae * [Fix]: Fix lint * [Feature]: LARS for linear eval * [Feature]: Add lars for mae linear eval * [Feature]: Change mae linear lars num workers to 32 * [Feature]: Change mae linear lars num workers to 8 * [Feature]: log every 25 iter for mae linear eval lars * [Feature]: Add 1600 epoch and 800 epoch pretraining * [Fix]: Change linear eval to 902 * [Fix]: Add random flip to linear eval * [Fix]: delete fp16 in mae * [Refactor]: Change backbone to mmcls * [Fix]: Align finetune settings * [Fix]: replace timm trunc_normal with mmcv trunc_normal * [Fix]: Change finetune layer_decay to 0.65 * [Fix]: Delete pretrain last norm when global_pooling * [Fix]: set requires_grad of norm1 to False * [Fix]: delete norm1 * [Fix]: Fix docstring bug * [Fix]: Fix lint * [Fix]: Add external link * [Fix]: Delete auto_resume and reformat config readme. * [Fix]: Fix pytest bug * [Fix]: Fix lint * [Refactor]: Rename filename * [Feature]: Add docstring * [Fix]: Rename config file name * [Fix]: Fix name inconsistency bug * [Fix]: Change the default value of persistent_worker in builder to True * [Fix]: Change the default value of CPUS_PER_TASK to 5 * [Fix]: Add a blank line to line136 in tools/train.py * [Fix]: Fix MAE algorithm docstring format and add paper name and url * [Feature]: Add MAE paper name and link, and store mae teaser on github * [Refactor]: Delete mae.png * [Fix]: Fix config file name” * [Fix]: Fix name bug * [Refactor]: Change default GPUS to 8 * [Fix]: Abandon change to drop_last * [Fix]: Fix docstring in mae algorithm * [Fix]: Fix lint * [Fix]: Fix lint * [Fix]: Fix mae finetune algo type bug * [Feature]: Add unit test for algorithm * [Feature]: Add unit test for remaining parts * [Fix]: Fix lint * [Fix]: Fix typo * [Fix]: Delete some unnecessary modification in gitignore * [Feature]: Change finetune setting in mae algo to mixup setting * [Fix]: Change norm_pix_loss to norm_pix in pretrain head * [Fix]: Delete modification in dist_train_linear.sh * [Refactor]: Delete global pool in mae_cls_vit.py * [Fix]: Change finetune param to mixup in test_mae_classification * [Fix]: Change norm_pix_loss to norm_pix of mae_pretrain_head in unit test * [Fix]: Change norm_pix_loss to norm_pix in unit test * [Refactor]: Create init_weights for mae_finetune_head and mae_linprobe_head * [Refactor]: Construct 2d sin-cosine position embedding using torch * [Refactor]: Using classification and using mixup from mmcls * [Fix]: Fix lint * [Fix]: Add False to finetune mae linprobe‘ “ * [Fix]: Set drop_last to False * [Fix]: Fix MAE finetune layerwise lr bug * [Refactor]: Delete redundant MAE when registering MAE * [Refactor]: Split initialize_weights in MAE to submodules * [Fix]: Change the min_lr of mae pretrain to 0.0 * [Refactor]: Delete unused _init_weights in mae_cls_vit * [Refactor]: Change MAE cls vit to a more general name * [Feature]: Add Epoch Fix cosine annealing lr updater * [Fix]: Fix lint * [Feature]: Add layer wise lr decay in optimizer constructor * [Fix]: Fix lint * [Fix]: Fix set layer wise lr decay bug * [Fix]: Fix UT for MAE * [Fix]: Fix lint * [Fix]: update algorithm readme format for MAE * [Fix]: Fix isort * [Fix]: Add Returns inmae_pretrain_vit * [Fix]: Change bgr to rgb * [Fix]: Change norm pix to True * [Fix]: Use cls_token to linear prob * [Fix]: Delete mixup.py * [Fix]: Fix MAE readme * [Feature]: Delete linprobe * [Refactor]: Merge MAE head into one file * [Fix]: Fix lint * [Fix]: rename mae_pretrain_head to mae_head * [Fix]: Fix import error in __init__.py * [Feature]: skip MAE algo UT when running on windows * [Fix]: Fix UT bug * [Feature]: Update model_zoo * [Fix]: Rename MAE pretrain model name * [Fix]: Delete mae ft prefix * [Feature]: Change b to base * [Refactor]: Change b in MAE pt config to base * [Fix]: Fix typo in docstring * [Fix]: Fix name bug * [Feature]: Add new constructor for MAE finetune * [Fix]: Fix model_zoo link * [Fix]: Skip UT for MAE * [Fix]: Change fixed channel order to param Co-authored-by: LIU Yuan <liuyuuan@pjlab.org.cn> Co-authored-by: liu yuan <liuyuan@pjlab.org.cn> * [Feature]: Add diff seeds to diff ranks and set torch seed in worker_init_fn (#228) * [Feature]: Add set diff seeds to diff ranks * [Fix]: Set diff seed to diff workers * Bump version to v0.7.0 (#227) * Bump version to v0.7.0 * [Docs] update readme Co-authored-by: wang11wang <95845452+wang11wang@users.noreply.github.com> Co-authored-by: Liangyu Chen <45140242+c-liangyu@users.noreply.github.com> Co-authored-by: Ming Li <73068772+mitming@users.noreply.github.com> Co-authored-by: liming <liming.ai@bytedance.com> Co-authored-by: Yuan Liu <30762564+YuanLiuuuuuu@users.noreply.github.com> Co-authored-by: LIU Yuan <liuyuuan@pjlab.org.cn> Co-authored-by: liu yuan <liuyuan@pjlab.org.cn>
186 lines
6.7 KiB
Python
186 lines
6.7 KiB
Python
# Copyright (c) OpenMMLab. All rights reserved.
|
|
from __future__ import division
|
|
import argparse
|
|
import os
|
|
import os.path as osp
|
|
import time
|
|
import warnings
|
|
|
|
import mmcv
|
|
import torch
|
|
import torch.distributed as dist
|
|
from mmcv import Config, DictAction
|
|
from mmcv.runner import get_dist_info, init_dist
|
|
|
|
from mmselfsup import __version__
|
|
from mmselfsup.apis import init_random_seed, set_random_seed, train_model
|
|
from mmselfsup.datasets import build_dataset
|
|
from mmselfsup.models import build_algorithm
|
|
from mmselfsup.utils import collect_env, get_root_logger, setup_multi_processes
|
|
|
|
|
|
def parse_args():
|
|
parser = argparse.ArgumentParser(description='Train a model')
|
|
parser.add_argument('config', help='train config file path')
|
|
parser.add_argument('--work_dir', help='the dir to save logs and models')
|
|
parser.add_argument(
|
|
'--resume_from', help='the checkpoint file to resume from')
|
|
group_gpus = parser.add_mutually_exclusive_group()
|
|
group_gpus.add_argument(
|
|
'--gpus',
|
|
type=int,
|
|
default=1,
|
|
help='(Deprecated, please use --gpu-id) number of gpus to use '
|
|
'(only applicable to non-distributed training)')
|
|
group_gpus.add_argument(
|
|
'--gpu_ids',
|
|
type=int,
|
|
nargs='+',
|
|
help='(Deprecated, please use --gpu-id) ids of gpus to use '
|
|
'(only applicable to non-distributed training)')
|
|
group_gpus.add_argument(
|
|
'--gpu-id',
|
|
type=int,
|
|
default=0,
|
|
help='id of gpu to use '
|
|
'(only applicable to non-distributed training)')
|
|
parser.add_argument('--seed', type=int, default=None, help='random seed')
|
|
parser.add_argument(
|
|
'--diff_seed',
|
|
action='store_true',
|
|
help='Whether or not set different seeds for different ranks')
|
|
parser.add_argument(
|
|
'--deterministic',
|
|
action='store_true',
|
|
help='whether to set deterministic options for CUDNN backend.')
|
|
parser.add_argument(
|
|
'--cfg-options',
|
|
nargs='+',
|
|
action=DictAction,
|
|
help='override some settings in the used config, the key-value pair '
|
|
'in xxx=yyy format will be merged into config file. If the value to '
|
|
'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
|
|
'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
|
|
'Note that the quotation marks are necessary and that no white space '
|
|
'is allowed.')
|
|
parser.add_argument(
|
|
'--launcher',
|
|
choices=['none', 'pytorch', 'slurm', 'mpi'],
|
|
default='none',
|
|
help='job launcher')
|
|
parser.add_argument('--local_rank', type=int, default=0)
|
|
args = parser.parse_args()
|
|
if 'LOCAL_RANK' not in os.environ:
|
|
os.environ['LOCAL_RANK'] = str(args.local_rank)
|
|
|
|
return args
|
|
|
|
|
|
def main():
|
|
args = parse_args()
|
|
|
|
cfg = Config.fromfile(args.config)
|
|
if args.cfg_options is not None:
|
|
cfg.merge_from_dict(args.cfg_options)
|
|
|
|
# set multi-process settings
|
|
setup_multi_processes(cfg)
|
|
|
|
# set cudnn_benchmark
|
|
if cfg.get('cudnn_benchmark', False):
|
|
torch.backends.cudnn.benchmark = True
|
|
# work_dir is determined in this priority: CLI > segment in file > filename
|
|
if args.work_dir is not None:
|
|
# update configs according to CLI args if args.work_dir is not None
|
|
cfg.work_dir = args.work_dir
|
|
elif cfg.get('work_dir', None) is None:
|
|
# use config filename as default work_dir if cfg.work_dir is None
|
|
work_type = args.config.split('/')[1]
|
|
cfg.work_dir = osp.join('./work_dirs', work_type,
|
|
osp.splitext(osp.basename(args.config))[0])
|
|
if args.resume_from is not None:
|
|
cfg.resume_from = args.resume_from
|
|
if args.gpus is not None:
|
|
cfg.gpu_ids = range(1)
|
|
warnings.warn('`--gpus` is deprecated because we only support '
|
|
'single GPU mode in non-distributed training. '
|
|
'Use `gpus=1` now.')
|
|
if args.gpu_ids is not None:
|
|
cfg.gpu_ids = args.gpu_ids[0:1]
|
|
warnings.warn('`--gpu-ids` is deprecated, please use `--gpu-id`. '
|
|
'Because we only support single GPU mode in '
|
|
'non-distributed training. Use the first GPU '
|
|
'in `gpu_ids` now.')
|
|
if args.gpus is None and args.gpu_ids is None:
|
|
cfg.gpu_ids = [args.gpu_id]
|
|
|
|
# init distributed env first, since logger depends on the dist info.
|
|
if args.launcher == 'none':
|
|
distributed = False
|
|
assert cfg.model.type not in [
|
|
'DeepCluster', 'MoCo', 'SimCLR', 'ODC', 'NPID', 'SimSiam',
|
|
'DenseCL', 'BYOL'
|
|
], f'{cfg.model.type} does not support non-dist training.'
|
|
else:
|
|
distributed = True
|
|
init_dist(args.launcher, **cfg.dist_params)
|
|
# re-set gpu_ids with distributed training mode
|
|
_, world_size = get_dist_info()
|
|
cfg.gpu_ids = range(world_size)
|
|
|
|
# create work_dir
|
|
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
|
|
|
|
# init the logger before other steps
|
|
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
|
|
log_file = osp.join(cfg.work_dir, f'train_{timestamp}.log')
|
|
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
|
|
|
|
# init the meta dict to record some important information such as
|
|
# environment info and seed, which will be logged
|
|
meta = dict()
|
|
# log env info
|
|
env_info_dict = collect_env()
|
|
env_info = '\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()])
|
|
dash_line = '-' * 60 + '\n'
|
|
logger.info('Environment info:\n' + dash_line + env_info + '\n' +
|
|
dash_line)
|
|
meta['env_info'] = env_info
|
|
meta['config'] = cfg.pretty_text
|
|
# log some basic info
|
|
logger.info(f'Distributed training: {distributed}')
|
|
logger.info(f'Config:\n{cfg.pretty_text}')
|
|
|
|
# set random seeds
|
|
seed = init_random_seed(args.seed)
|
|
seed = seed + dist.get_rank() if args.diff_seed else seed
|
|
logger.info(f'Set random seed to {seed}, '
|
|
f'deterministic: {args.deterministic}')
|
|
set_random_seed(seed, deterministic=args.deterministic)
|
|
cfg.seed = seed
|
|
meta['seed'] = seed
|
|
meta['exp_name'] = osp.basename(args.config)
|
|
|
|
model = build_algorithm(cfg.model)
|
|
model.init_weights()
|
|
|
|
datasets = [build_dataset(cfg.data.train)]
|
|
assert len(cfg.workflow) == 1, 'Validation is called by hook.'
|
|
if cfg.checkpoint_config is not None:
|
|
# save mmselfsup version, config file content and class names in
|
|
# checkpoints as meta data
|
|
cfg.checkpoint_config.meta = dict(
|
|
mmselfsup_version=__version__, config=cfg.pretty_text)
|
|
|
|
train_model(
|
|
model,
|
|
datasets,
|
|
cfg,
|
|
distributed=distributed,
|
|
timestamp=timestamp,
|
|
meta=meta)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|