get_flops.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import tempfile
  4. from functools import partial
  5. from pathlib import Path
  6. import numpy as np
  7. import torch
  8. from mmengine.config import Config, DictAction
  9. from mmengine.logging import MMLogger
  10. from mmengine.model import revert_sync_batchnorm
  11. from mmengine.registry import init_default_scope
  12. from mmengine.runner import Runner
  13. from mmdet.registry import MODELS
  14. try:
  15. from mmengine.analysis import get_model_complexity_info
  16. from mmengine.analysis.print_helper import _format_size
  17. except ImportError:
  18. raise ImportError('Please upgrade mmengine >= 0.6.0')
  19. def parse_args():
  20. parser = argparse.ArgumentParser(description='Get a detector flops')
  21. parser.add_argument('config', help='train config file path')
  22. parser.add_argument(
  23. '--num-images',
  24. type=int,
  25. default=100,
  26. help='num images of calculate model flops')
  27. parser.add_argument(
  28. '--cfg-options',
  29. nargs='+',
  30. action=DictAction,
  31. help='override some settings in the used config, the key-value pair '
  32. 'in xxx=yyy format will be merged into config file. If the value to '
  33. 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
  34. 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
  35. 'Note that the quotation marks are necessary and that no white space '
  36. 'is allowed.')
  37. args = parser.parse_args()
  38. return args
  39. def inference(args, logger):
  40. if str(torch.__version__) < '1.12':
  41. logger.warning(
  42. 'Some config files, such as configs/yolact and configs/detectors,'
  43. 'may have compatibility issues with torch.jit when torch<1.12. '
  44. 'If you want to calculate flops for these models, '
  45. 'please make sure your pytorch version is >=1.12.')
  46. config_name = Path(args.config)
  47. if not config_name.exists():
  48. logger.error(f'{config_name} not found.')
  49. cfg = Config.fromfile(args.config)
  50. cfg.val_dataloader.batch_size = 1
  51. cfg.work_dir = tempfile.TemporaryDirectory().name
  52. if args.cfg_options is not None:
  53. cfg.merge_from_dict(args.cfg_options)
  54. init_default_scope(cfg.get('default_scope', 'mmdet'))
  55. # TODO: The following usage is temporary and not safe
  56. # use hard code to convert mmSyncBN to SyncBN. This is a known
  57. # bug in mmengine, mmSyncBN requires a distributed environment,
  58. # this question involves models like configs/strong_baselines
  59. if hasattr(cfg, 'head_norm_cfg'):
  60. cfg['head_norm_cfg'] = dict(type='SyncBN', requires_grad=True)
  61. cfg['model']['roi_head']['bbox_head']['norm_cfg'] = dict(
  62. type='SyncBN', requires_grad=True)
  63. cfg['model']['roi_head']['mask_head']['norm_cfg'] = dict(
  64. type='SyncBN', requires_grad=True)
  65. result = {}
  66. avg_flops = []
  67. data_loader = Runner.build_dataloader(cfg.val_dataloader)
  68. model = MODELS.build(cfg.model)
  69. if torch.cuda.is_available():
  70. model = model.cuda()
  71. model = revert_sync_batchnorm(model)
  72. model.eval()
  73. _forward = model.forward
  74. for idx, data_batch in enumerate(data_loader):
  75. if idx == args.num_images:
  76. break
  77. data = model.data_preprocessor(data_batch)
  78. result['ori_shape'] = data['data_samples'][0].ori_shape
  79. result['pad_shape'] = data['data_samples'][0].pad_shape
  80. if hasattr(data['data_samples'][0], 'batch_input_shape'):
  81. result['pad_shape'] = data['data_samples'][0].batch_input_shape
  82. model.forward = partial(_forward, data_samples=data['data_samples'])
  83. outputs = get_model_complexity_info(
  84. model,
  85. None,
  86. inputs=data['inputs'],
  87. show_table=False,
  88. show_arch=False)
  89. avg_flops.append(outputs['flops'])
  90. params = outputs['params']
  91. result['compute_type'] = 'dataloader: load a picture from the dataset'
  92. del data_loader
  93. mean_flops = _format_size(int(np.average(avg_flops)))
  94. params = _format_size(params)
  95. result['flops'] = mean_flops
  96. result['params'] = params
  97. return result
  98. def main():
  99. args = parse_args()
  100. logger = MMLogger.get_instance(name='MMLogger')
  101. result = inference(args, logger)
  102. split_line = '=' * 30
  103. ori_shape = result['ori_shape']
  104. pad_shape = result['pad_shape']
  105. flops = result['flops']
  106. params = result['params']
  107. compute_type = result['compute_type']
  108. if pad_shape != ori_shape:
  109. print(f'{split_line}\nUse size divisor set input shape '
  110. f'from {ori_shape} to {pad_shape}')
  111. print(f'{split_line}\nCompute type: {compute_type}\n'
  112. f'Input shape: {pad_shape}\nFlops: {flops}\n'
  113. f'Params: {params}\n{split_line}')
  114. print('!!!Please be cautious if you use the results in papers. '
  115. 'You may need to check if all ops are supported and verify '
  116. 'that the flops computation is correct.')
  117. if __name__ == '__main__':
  118. main()