benchmark_valid_flops.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import logging
  2. import re
  3. import tempfile
  4. from argparse import ArgumentParser
  5. from collections import OrderedDict
  6. from functools import partial
  7. from pathlib import Path
  8. import numpy as np
  9. import pandas as pd
  10. import torch
  11. from mmengine import Config, DictAction
  12. from mmengine.analysis import get_model_complexity_info
  13. from mmengine.analysis.print_helper import _format_size
  14. from mmengine.fileio import FileClient
  15. from mmengine.logging import MMLogger
  16. from mmengine.model import revert_sync_batchnorm
  17. from mmengine.runner import Runner
  18. from modelindex.load_model_index import load
  19. from rich.console import Console
  20. from rich.table import Table
  21. from rich.text import Text
  22. from tqdm import tqdm
  23. from mmdet.registry import MODELS
  24. from mmdet.utils import register_all_modules
  25. console = Console()
  26. MMDET_ROOT = Path(__file__).absolute().parents[1]
  27. def parse_args():
  28. parser = ArgumentParser(description='Valid all models in model-index.yml')
  29. parser.add_argument(
  30. '--shape',
  31. type=int,
  32. nargs='+',
  33. default=[1280, 800],
  34. help='input image size')
  35. parser.add_argument(
  36. '--checkpoint_root',
  37. help='Checkpoint file root path. If set, load checkpoint before test.')
  38. parser.add_argument('--img', default='demo/demo.jpg', help='Image file')
  39. parser.add_argument('--models', nargs='+', help='models name to inference')
  40. parser.add_argument(
  41. '--batch-size',
  42. type=int,
  43. default=1,
  44. help='The batch size during the inference.')
  45. parser.add_argument(
  46. '--flops', action='store_true', help='Get Flops and Params of models')
  47. parser.add_argument(
  48. '--flops-str',
  49. action='store_true',
  50. help='Output FLOPs and params counts in a string form.')
  51. parser.add_argument(
  52. '--cfg-options',
  53. nargs='+',
  54. action=DictAction,
  55. help='override some settings in the used config, the key-value pair '
  56. 'in xxx=yyy format will be merged into config file. If the value to '
  57. 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
  58. 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
  59. 'Note that the quotation marks are necessary and that no white space '
  60. 'is allowed.')
  61. parser.add_argument(
  62. '--size_divisor',
  63. type=int,
  64. default=32,
  65. help='Pad the input image, the minimum size that is divisible '
  66. 'by size_divisor, -1 means do not pad the image.')
  67. args = parser.parse_args()
  68. return args
  69. def inference(config_file, checkpoint, work_dir, args, exp_name):
  70. logger = MMLogger.get_instance(name='MMLogger')
  71. logger.warning('if you want test flops, please make sure torch>=1.12')
  72. cfg = Config.fromfile(config_file)
  73. cfg.work_dir = work_dir
  74. cfg.load_from = checkpoint
  75. cfg.log_level = 'WARN'
  76. cfg.experiment_name = exp_name
  77. if args.cfg_options is not None:
  78. cfg.merge_from_dict(args.cfg_options)
  79. # forward the model
  80. result = {'model': config_file.stem}
  81. if args.flops:
  82. if len(args.shape) == 1:
  83. h = w = args.shape[0]
  84. elif len(args.shape) == 2:
  85. h, w = args.shape
  86. else:
  87. raise ValueError('invalid input shape')
  88. divisor = args.size_divisor
  89. if divisor > 0:
  90. h = int(np.ceil(h / divisor)) * divisor
  91. w = int(np.ceil(w / divisor)) * divisor
  92. input_shape = (3, h, w)
  93. result['resolution'] = input_shape
  94. try:
  95. cfg = Config.fromfile(config_file)
  96. if hasattr(cfg, 'head_norm_cfg'):
  97. cfg['head_norm_cfg'] = dict(type='SyncBN', requires_grad=True)
  98. cfg['model']['roi_head']['bbox_head']['norm_cfg'] = dict(
  99. type='SyncBN', requires_grad=True)
  100. cfg['model']['roi_head']['mask_head']['norm_cfg'] = dict(
  101. type='SyncBN', requires_grad=True)
  102. if args.cfg_options is not None:
  103. cfg.merge_from_dict(args.cfg_options)
  104. model = MODELS.build(cfg.model)
  105. input = torch.rand(1, *input_shape)
  106. if torch.cuda.is_available():
  107. model.cuda()
  108. input = input.cuda()
  109. model = revert_sync_batchnorm(model)
  110. inputs = (input, )
  111. model.eval()
  112. outputs = get_model_complexity_info(
  113. model, input_shape, inputs, show_table=False, show_arch=False)
  114. flops = outputs['flops']
  115. params = outputs['params']
  116. activations = outputs['activations']
  117. result['Get Types'] = 'direct'
  118. except: # noqa 772
  119. logger = MMLogger.get_instance(name='MMLogger')
  120. logger.warning(
  121. 'Direct get flops failed, try to get flops with data')
  122. cfg = Config.fromfile(config_file)
  123. if hasattr(cfg, 'head_norm_cfg'):
  124. cfg['head_norm_cfg'] = dict(type='SyncBN', requires_grad=True)
  125. cfg['model']['roi_head']['bbox_head']['norm_cfg'] = dict(
  126. type='SyncBN', requires_grad=True)
  127. cfg['model']['roi_head']['mask_head']['norm_cfg'] = dict(
  128. type='SyncBN', requires_grad=True)
  129. data_loader = Runner.build_dataloader(cfg.val_dataloader)
  130. data_batch = next(iter(data_loader))
  131. model = MODELS.build(cfg.model)
  132. if torch.cuda.is_available():
  133. model = model.cuda()
  134. model = revert_sync_batchnorm(model)
  135. model.eval()
  136. _forward = model.forward
  137. data = model.data_preprocessor(data_batch)
  138. del data_loader
  139. model.forward = partial(
  140. _forward, data_samples=data['data_samples'])
  141. outputs = get_model_complexity_info(
  142. model,
  143. input_shape,
  144. data['inputs'],
  145. show_table=False,
  146. show_arch=False)
  147. flops = outputs['flops']
  148. params = outputs['params']
  149. activations = outputs['activations']
  150. result['Get Types'] = 'dataloader'
  151. if args.flops_str:
  152. flops = _format_size(flops)
  153. params = _format_size(params)
  154. activations = _format_size(activations)
  155. result['flops'] = flops
  156. result['params'] = params
  157. return result
  158. def show_summary(summary_data, args):
  159. table = Table(title='Validation Benchmark Regression Summary')
  160. table.add_column('Model')
  161. table.add_column('Validation')
  162. table.add_column('Resolution (c, h, w)')
  163. if args.flops:
  164. table.add_column('Flops', justify='right', width=11)
  165. table.add_column('Params', justify='right')
  166. for model_name, summary in summary_data.items():
  167. row = [model_name]
  168. valid = summary['valid']
  169. color = 'green' if valid == 'PASS' else 'red'
  170. row.append(f'[{color}]{valid}[/{color}]')
  171. if valid == 'PASS':
  172. row.append(str(summary['resolution']))
  173. if args.flops:
  174. row.append(str(summary['flops']))
  175. row.append(str(summary['params']))
  176. table.add_row(*row)
  177. console.print(table)
  178. table_data = {
  179. x.header: [Text.from_markup(y).plain for y in x.cells]
  180. for x in table.columns
  181. }
  182. table_pd = pd.DataFrame(table_data)
  183. table_pd.to_csv('./mmdetection_flops.csv')
  184. # Sample test whether the inference code is correct
  185. def main(args):
  186. register_all_modules()
  187. model_index_file = MMDET_ROOT / 'model-index.yml'
  188. model_index = load(str(model_index_file))
  189. model_index.build_models_with_collections()
  190. models = OrderedDict({model.name: model for model in model_index.models})
  191. logger = MMLogger(
  192. 'validation',
  193. logger_name='validation',
  194. log_file='benchmark_test_image.log',
  195. log_level=logging.INFO)
  196. if args.models:
  197. patterns = [
  198. re.compile(pattern.replace('+', '_')) for pattern in args.models
  199. ]
  200. filter_models = {}
  201. for k, v in models.items():
  202. k = k.replace('+', '_')
  203. if any([re.match(pattern, k) for pattern in patterns]):
  204. filter_models[k] = v
  205. if len(filter_models) == 0:
  206. print('No model found, please specify models in:')
  207. print('\n'.join(models.keys()))
  208. return
  209. models = filter_models
  210. summary_data = {}
  211. tmpdir = tempfile.TemporaryDirectory()
  212. for model_name, model_info in tqdm(models.items()):
  213. if model_info.config is None:
  214. continue
  215. model_info.config = model_info.config.replace('%2B', '+')
  216. config = Path(model_info.config)
  217. try:
  218. config.exists()
  219. except: # noqa 722
  220. logger.error(f'{model_name}: {config} not found.')
  221. continue
  222. logger.info(f'Processing: {model_name}')
  223. http_prefix = 'https://download.openmmlab.com/mmdetection/'
  224. if args.checkpoint_root is not None:
  225. root = args.checkpoint_root
  226. if 's3://' in args.checkpoint_root:
  227. from petrel_client.common.exception import AccessDeniedError
  228. file_client = FileClient.infer_client(uri=root)
  229. checkpoint = file_client.join_path(
  230. root, model_info.weights[len(http_prefix):])
  231. try:
  232. exists = file_client.exists(checkpoint)
  233. except AccessDeniedError:
  234. exists = False
  235. else:
  236. checkpoint = Path(root) / model_info.weights[len(http_prefix):]
  237. exists = checkpoint.exists()
  238. if exists:
  239. checkpoint = str(checkpoint)
  240. else:
  241. print(f'WARNING: {model_name}: {checkpoint} not found.')
  242. checkpoint = None
  243. else:
  244. checkpoint = None
  245. try:
  246. # build the model from a config file and a checkpoint file
  247. result = inference(MMDET_ROOT / config, checkpoint, tmpdir.name,
  248. args, model_name)
  249. result['valid'] = 'PASS'
  250. except Exception: # noqa 722
  251. import traceback
  252. logger.error(f'"{config}" :\n{traceback.format_exc()}')
  253. result = {'valid': 'FAIL'}
  254. summary_data[model_name] = result
  255. tmpdir.cleanup()
  256. show_summary(summary_data, args)
  257. if __name__ == '__main__':
  258. args = parse_args()
  259. main(args)