def main():
    args = parse_args()
    cfg = mmcv.Config.fromfile(args.config)
    if cfg.get('cudnn_benchmark', False):
        torch.backends.cudnn.benchmark = True
    if (args.work_dir is not None):
        cfg.work_dir = args.work_dir
    layer_ind = [int(idx) for idx in args.layer_ind.split(',')]
    cfg.model.backbone.out_indices = layer_ind
    assert ((args.pretrained == 'random') or (args.checkpoint is None)), 'Checkpoint and pretrained are exclusive.'
    if (importlib.util.find_spec('mc') is None):
        for field in ['train', 'val', 'test']:
            if hasattr(cfg.data, field):
                getattr(cfg.data, field).data_source.memcached = False
    if (args.launcher == 'none'):
        distributed = False
    else:
        distributed = True
        if (args.launcher == 'slurm'):
            cfg.dist_params['port'] = args.port
        init_dist(args.launcher, **cfg.dist_params)
    mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
    timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
    log_file = osp.join(cfg.work_dir, 'extract_{}.log'.format(timestamp))
    logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
    dataset_cfg = mmcv.Config.fromfile(args.dataset_config)
    dataset = build_dataset(dataset_cfg.data.extract)
    data_loader = build_dataloader(dataset, imgs_per_gpu=dataset_cfg.data.imgs_per_gpu, workers_per_gpu=dataset_cfg.data.workers_per_gpu, dist=distributed, shuffle=False)
    if (args.pretrained != 'random'):
        assert isinstance(args.pretrained, str)
        cfg.model.pretrained = args.pretrained
    model = build_model(cfg.model)
    if (args.checkpoint is not None):
        logger.info('Use checkpoint: {} to extract features'.format(args.checkpoint))
        load_checkpoint(model, args.checkpoint, map_location='cpu')
    elif (args.pretrained != 'random'):
        logger.info('Use pretrained model: {} to extract features'.format(args.pretrained))
    else:
        logger.info('No checkpoint or pretrained is give, use random init.')
    if (not distributed):
        model = MMDataParallel(model, device_ids=[0])
    else:
        model = MMDistributedDataParallel(model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False)
    extractor = ExtractProcess(pool_type='specified', backbone='resnet50', layer_indices=layer_ind)
    outputs = extractor.extract(model, data_loader, distributed=distributed)
    (rank, _) = get_dist_info()
    mmcv.mkdir_or_exist('{}/features/'.format(args.work_dir))
    if (rank == 0):
        for (key, val) in outputs.items():
            split_num = len(dataset_cfg.split_name)
            split_at = dataset_cfg.split_at
            for ss in range(split_num):
                output_file = '{}/features/{}_{}.npy'.format(args.work_dir, dataset_cfg.split_name[ss], key)
                if (ss == 0):
                    np.save(output_file, val[:split_at[0]])
                elif (ss == (split_num - 1)):
                    np.save(output_file, val[split_at[(- 1)]:])
                else:
                    np.save(output_file, val[split_at[(ss - 1)]:split_at[ss]])
def main():
    args = parse_args()
    cfg = mmcv.Config.fromfile(args.config)
    if cfg.get('cudnn_benchmark', False):
        torch.backends.cudnn.benchmark = True
    if (args.work_dir is not None):
        cfg.work_dir = args.work_dir
    layer_ind = [int(idx) for idx in args.layer_ind.split(',')]
    cfg.model.backbone.out_indices = layer_ind
    assert ((args.pretrained == 'random') or (args.checkpoint is None)), 'Checkpoint and pretrained are exclusive.'
    if (importlib.util.find_spec('mc') is None):
        for field in ['train', 'val', 'test']:
            if hasattr(cfg.data, field):
                getattr(cfg.data, field).data_source.memcached = False
    if (args.launcher == 'none'):
        distributed = False
    else:
        distributed = True
        if (args.launcher == 'slurm'):
            cfg.dist_params['port'] = args.port
        init_dist(args.launcher, **cfg.dist_params)
    mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
    timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
    log_file = osp.join(cfg.work_dir, 'extract_{}.log'.format(timestamp))
    logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
    dataset_cfg = mmcv.Config.fromfile(args.dataset_config)
    dataset = build_dataset(dataset_cfg.data.extract)
    data_loader = build_dataloader(dataset, imgs_per_gpu=dataset_cfg.data.imgs_per_gpu, workers_per_gpu=dataset_cfg.data.workers_per_gpu, dist=distributed, shuffle=False)
    if (args.pretrained != 'random'):
        assert isinstance(args.pretrained, str)
        cfg.model.pretrained = args.pretrained
    model = build_model(cfg.model)
    if (args.checkpoint is not None):
        logger.info('Use checkpoint: {} to extract features'.format(args.checkpoint))
        load_checkpoint(model, args.checkpoint, map_location='cpu')
    elif (args.pretrained != 'random'):
        logger.info('Use pretrained model: {} to extract features'.format(args.pretrained))
    else:
        logger.info('No checkpoint or pretrained is give, use random init.')
    if (not distributed):
        model = MMDataParallel(model, device_ids=[0])
    else:
        model = MMDistributedDataParallel(model.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False)
    extractor = ExtractProcess(pool_type='specified', backbone='resnet50', layer_indices=layer_ind)
    outputs = extractor.extract(model, data_loader, distributed=distributed)
    (rank, _) = get_dist_info()
    mmcv.mkdir_or_exist('{}/features/'.format(args.work_dir))
    if (rank == 0):
        for (key, val) in outputs.items():
            split_num = len(dataset_cfg.split_name)
            split_at = dataset_cfg.split_at
            for ss in range(split_num):
                output_file = '{}/features/{}_{}.npy'.format(args.work_dir, dataset_cfg.split_name[ss], key)
                if (ss == 0):
                    np.save(output_file, val[:split_at[0]])
                elif (ss == (split_num - 1)):
                    np.save(output_file, val[split_at[(- 1)]:])
                else:
                    np.save(output_file, val[split_at[(ss - 1)]:split_at[ss]])