You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

module_stats.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. from collections import namedtuple
  9. from functools import partial
  10. import numpy as np
  11. import tabulate
  12. import megengine as mge
  13. import megengine.module as m
  14. import megengine.module.qat as qatm
  15. import megengine.module.quantized as qm
  16. from megengine.core.tensor.dtype import get_dtype_bit
  17. from megengine.functional.tensor import zeros
  18. from .module_utils import set_module_mode_safe
  19. try:
  20. mge.logger.MegEngineLogFormatter.max_lines = float("inf")
  21. except AttributeError as e:
  22. raise ValueError("set logger max lines failed")
  23. logger = mge.get_logger(__name__)
  24. logger.setLevel("INFO")
  25. _calc_flops_dict = {}
  26. _calc_receptive_field_dict = {}
  27. def _receptive_field_fallback(module, inputs, outputs):
  28. if not _receptive_field_enabled:
  29. return
  30. assert not hasattr(module, "_rf")
  31. assert not hasattr(module, "_stride")
  32. if len(inputs) == 0:
  33. # TODO: support other dimension
  34. module._rf = (1, 1)
  35. module._stride = (1, 1)
  36. return module._rf, module._stride
  37. rf, stride = preprocess_receptive_field(module, inputs, outputs)
  38. module._rf = rf
  39. module._stride = stride
  40. return rf, stride
  41. # key tuple, impl_dict, fallback
  42. _iter_list = [
  43. ("flops_num", _calc_flops_dict, None),
  44. (
  45. ("receptive_field", "stride"),
  46. _calc_receptive_field_dict,
  47. _receptive_field_fallback,
  48. ),
  49. ]
  50. _receptive_field_enabled = False
  51. def _register_dict(*modules, dict=None):
  52. def callback(impl):
  53. for module in modules:
  54. dict[module] = impl
  55. return impl
  56. return callback
  57. def register_flops(*modules):
  58. return _register_dict(*modules, dict=_calc_flops_dict)
  59. def register_receptive_field(*modules):
  60. return _register_dict(*modules, dict=_calc_receptive_field_dict)
  61. def enable_receptive_field():
  62. global _receptive_field_enabled
  63. _receptive_field_enabled = True
  64. def disable_receptive_field():
  65. global _receptive_field_enabled
  66. _receptive_field_enabled = False
  67. @register_flops(
  68. m.Conv1d, m.Conv2d, m.Conv3d, m.ConvTranspose2d, m.LocalConv2d, m.DeformableConv2d
  69. )
  70. def flops_convNd(module: m.Conv2d, inputs, outputs):
  71. bias = 1 if module.bias is not None else 0
  72. # N x Cout x H x W x (Cin x Kw x Kh + bias)
  73. return np.prod(outputs[0].shape) * (
  74. module.in_channels // module.groups * np.prod(module.kernel_size) + bias
  75. )
  76. @register_flops(
  77. m.batchnorm._BatchNorm, m.SyncBatchNorm, m.GroupNorm, m.LayerNorm, m.InstanceNorm,
  78. )
  79. def flops_norm(module: m.Linear, inputs, outputs):
  80. return np.prod(inputs[0].shape) * 7
  81. @register_flops(m.AvgPool2d, m.MaxPool2d)
  82. def flops_pool(module: m.AvgPool2d, inputs, outputs):
  83. return np.prod(outputs[0].shape) * (module.kernel_size ** 2)
  84. @register_flops(m.AdaptiveAvgPool2d, m.AdaptiveMaxPool2d)
  85. def flops_adaptivePool(module: m.AdaptiveAvgPool2d, inputs, outputs):
  86. stride_h = np.floor(inputs[0].shape[2] / (inputs[0].shape[2] - 1))
  87. kernel_h = inputs[0].shape[2] - (inputs[0].shape[2] - 1) * stride_h
  88. stride_w = np.floor(inputs[0].shape[3] / (inputs[0].shape[3] - 1))
  89. kernel_w = inputs[0].shape[3] - (inputs[0].shape[3] - 1) * stride_w
  90. return np.prod(outputs[0].shape) * kernel_h * kernel_w
  91. @register_flops(m.Linear)
  92. def flops_linear(module: m.Linear, inputs, outputs):
  93. bias = module.out_features if module.bias is not None else 0
  94. return np.prod(outputs[0].shape) * module.in_features + bias
  95. @register_flops(m.BatchMatMulActivation)
  96. def flops_batchmatmul(module: m.BatchMatMulActivation, inputs, outputs):
  97. bias = 1 if module.bias is not None else 0
  98. x = inputs[0]
  99. w = module.weight
  100. batch_size = x.shape[0]
  101. n, p = x.shape[1:]
  102. _, m = w.shape[1:]
  103. return n * (p + bias) * m * batch_size
  104. # does not need import qat and quantized module since they inherit from float module.
  105. hook_modules = (
  106. m.conv._ConvNd,
  107. m.Linear,
  108. m.BatchMatMulActivation,
  109. m.batchnorm._BatchNorm,
  110. m.LayerNorm,
  111. m.GroupNorm,
  112. m.InstanceNorm,
  113. m.pooling._PoolNd,
  114. m.adaptive_pooling._AdaptivePoolNd,
  115. )
  116. def dict2table(list_of_dict, header):
  117. table_data = [header]
  118. for d in list_of_dict:
  119. row = []
  120. for h in header:
  121. v = ""
  122. if h in d:
  123. v = d[h]
  124. row.append(v)
  125. table_data.append(row)
  126. return table_data
  127. def sizeof_fmt(num, suffix="B"):
  128. if suffix == "B":
  129. scale = 1024.0
  130. units = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"]
  131. else:
  132. scale = 1000.0
  133. units = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]
  134. for unit in units:
  135. if abs(num) < scale or unit == units[-1]:
  136. return "{:3.3f} {}{}".format(num, unit, suffix)
  137. num /= scale
  138. def preprocess_receptive_field(module, inputs, outputs):
  139. # TODO: support other dimensions
  140. pre_rf = (
  141. max(getattr(i.owner, "_rf", (1, 1))[0] for i in inputs),
  142. max(getattr(i.owner, "_rf", (1, 1))[1] for i in inputs),
  143. )
  144. pre_stride = (
  145. max(getattr(i.owner, "_stride", (1, 1))[0] for i in inputs),
  146. max(getattr(i.owner, "_stride", (1, 1))[1] for i in inputs),
  147. )
  148. return pre_rf, pre_stride
  149. def get_op_stats(module, inputs, outputs):
  150. if not isinstance(outputs, tuple) and not isinstance(outputs, list):
  151. outputs = (outputs,)
  152. rst = {
  153. "input_shapes": [i.shape for i in inputs],
  154. "output_shapes": [o.shape for o in outputs],
  155. }
  156. valid_flag = False
  157. for key, _dict, fallback in _iter_list:
  158. for _type in _dict:
  159. if isinstance(module, _type):
  160. value = _dict[_type](module, inputs, outputs)
  161. valid_flag = True
  162. break
  163. else:
  164. if fallback is not None:
  165. value = fallback(module, inputs, outputs)
  166. continue
  167. if isinstance(key, tuple):
  168. assert isinstance(value, tuple)
  169. for k, v in zip(key, value):
  170. rst[k] = v
  171. else:
  172. rst[key] = value
  173. if valid_flag:
  174. return rst
  175. else:
  176. return None
  177. return
  178. def sum_op_stats(flops, bar_length_max=20):
  179. max_flops_num = max([i["flops_num"] for i in flops] + [0])
  180. total_flops_num = 0
  181. for d in flops:
  182. total_flops_num += int(d["flops_num"])
  183. d["flops_cum"] = sizeof_fmt(total_flops_num, suffix="OPs")
  184. for d in flops:
  185. ratio = d["ratio"] = d["flops_num"] / total_flops_num
  186. d["percentage"] = "{:.2f}%".format(ratio * 100)
  187. bar_length = int(d["flops_num"] / max_flops_num * bar_length_max)
  188. d["bar"] = "#" * bar_length
  189. d["flops"] = sizeof_fmt(d["flops_num"], suffix="OPs")
  190. total_flops_str = sizeof_fmt(total_flops_num, suffix="OPs")
  191. total_var_size = sum(
  192. sum(s[1] if len(s) > 1 else 0 for s in d["output_shapes"]) for d in flops
  193. )
  194. flops.append(
  195. dict(name="total", flops=total_flops_str, output_shapes=total_var_size)
  196. )
  197. return total_flops_num, flops
  198. def print_op_stats(flops):
  199. header = [
  200. "name",
  201. "class_name",
  202. "input_shapes",
  203. "output_shapes",
  204. "flops",
  205. "flops_cum",
  206. "percentage",
  207. "bar",
  208. ]
  209. if _receptive_field_enabled:
  210. header.insert(4, "receptive_field")
  211. header.insert(5, "stride")
  212. logger.info("flops stats: \n" + tabulate.tabulate(dict2table(flops, header=header)))
  213. def get_param_stats(param: np.ndarray):
  214. nbits = get_dtype_bit(param.dtype.name)
  215. shape = param.shape
  216. param_dim = np.prod(param.shape)
  217. param_size = param_dim * nbits // 8
  218. return {
  219. "dtype": param.dtype,
  220. "shape": shape,
  221. "mean": "{:.3g}".format(param.mean()),
  222. "std": "{:.3g}".format(param.std()),
  223. "param_dim": param_dim,
  224. "nbits": nbits,
  225. "size": param_size,
  226. }
  227. def sum_param_stats(params, bar_length_max=20):
  228. max_size = max([d["size"] for d in params] + [0])
  229. total_param_dims, total_param_size = 0, 0
  230. for d in params:
  231. total_param_dims += int(d["param_dim"])
  232. total_param_size += int(d["size"])
  233. d["size_cum"] = sizeof_fmt(total_param_size)
  234. for d in params:
  235. ratio = d["size"] / total_param_size
  236. d["ratio"] = ratio
  237. d["percentage"] = "{:.2f}%".format(ratio * 100)
  238. bar_length = int(d["size"] / max_size * bar_length_max)
  239. d["size_bar"] = "#" * bar_length
  240. d["size"] = sizeof_fmt(d["size"])
  241. param_size = sizeof_fmt(total_param_size)
  242. params.append(dict(name="total", param_dim=total_param_dims, size=param_size,))
  243. return total_param_dims, total_param_size, params
  244. def print_param_stats(params):
  245. header = [
  246. "name",
  247. "dtype",
  248. "shape",
  249. "mean",
  250. "std",
  251. "param_dim",
  252. "nbits",
  253. "size",
  254. "size_cum",
  255. "percentage",
  256. "size_bar",
  257. ]
  258. logger.info(
  259. "param stats: \n" + tabulate.tabulate(dict2table(params, header=header))
  260. )
  261. def get_activation_stats(output: np.ndarray):
  262. out_shape = output.shape
  263. activations_dtype = output.dtype
  264. nbits = get_dtype_bit(activations_dtype.name)
  265. act_dim = np.prod(out_shape)
  266. act_size = act_dim * nbits // 8
  267. return {
  268. "dtype": activations_dtype,
  269. "shape": out_shape,
  270. "act_dim": act_dim,
  271. "mean": "{:.3g}".format(output.mean()),
  272. "std": "{:.3g}".format(output.std()),
  273. "nbits": nbits,
  274. "size": act_size,
  275. }
  276. def sum_activations_stats(activations, bar_length_max=20):
  277. max_act_size = max([i["size"] for i in activations] + [0])
  278. total_act_dims, total_act_size = 0, 0
  279. for d in activations:
  280. total_act_size += int(d["size"])
  281. total_act_dims += int(d["act_dim"])
  282. d["size_cum"] = sizeof_fmt(total_act_size)
  283. for d in activations:
  284. ratio = d["ratio"] = d["size"] / total_act_size
  285. d["percentage"] = "{:.2f}%".format(ratio * 100)
  286. bar_length = int(d["size"] / max_act_size * bar_length_max)
  287. d["size_bar"] = "#" * bar_length
  288. d["size"] = sizeof_fmt(d["size"])
  289. act_size = sizeof_fmt(total_act_size)
  290. activations.append(dict(name="total", act_dim=total_act_dims, size=act_size,))
  291. return total_act_dims, total_act_size, activations
  292. def print_activations_stats(activations):
  293. header = [
  294. "name",
  295. "class_name",
  296. "dtype",
  297. "shape",
  298. "mean",
  299. "std",
  300. "nbits",
  301. "act_dim",
  302. "size",
  303. "size_cum",
  304. "percentage",
  305. "size_bar",
  306. ]
  307. logger.info(
  308. "activations stats: \n"
  309. + tabulate.tabulate(dict2table(activations, header=header))
  310. )
  311. def print_summary(**kwargs):
  312. data = [["item", "value"]]
  313. data.extend(list(kwargs.items()))
  314. logger.info("summary\n" + tabulate.tabulate(data))
  315. def module_stats(
  316. model: m.Module,
  317. input_shapes: list,
  318. bar_length_max: int = 20,
  319. log_params: bool = True,
  320. log_flops: bool = True,
  321. log_activations: bool = True,
  322. ):
  323. r"""
  324. Calculate and print ``model``'s statistics by adding hook and record Module's inputs outputs size.
  325. :param model: model that need to get stats info.
  326. :param input_shapes: shapes of inputs for running model and calculating stats.
  327. :param bar_length_max: size of bar indicating max flops or parameter size in net stats.
  328. :param log_params: whether print and record params size.
  329. :param log_flops: whether print and record op flops.
  330. :param log_activations: whether print and record op activations.
  331. """
  332. disable_receptive_field()
  333. def module_stats_hook(module, inputs, outputs, name=""):
  334. class_name = str(module.__class__).split(".")[-1].split("'")[0]
  335. flops_stats = get_op_stats(module, inputs, outputs)
  336. if flops_stats is not None:
  337. flops_stats["name"] = name
  338. flops_stats["class_name"] = class_name
  339. flops.append(flops_stats)
  340. if hasattr(module, "weight") and module.weight is not None:
  341. w = module.weight
  342. param_stats = get_param_stats(w.numpy())
  343. param_stats["name"] = name + "-w"
  344. params.append(param_stats)
  345. if hasattr(module, "bias") and module.bias is not None:
  346. b = module.bias
  347. param_stats = get_param_stats(b.numpy())
  348. param_stats["name"] = name + "-b"
  349. params.append(param_stats)
  350. if not isinstance(outputs, tuple) or not isinstance(outputs, list):
  351. output = outputs.numpy()
  352. else:
  353. output = outputs[0].numpy()
  354. activation_stats = get_activation_stats(output)
  355. activation_stats["name"] = name
  356. activation_stats["class_name"] = class_name
  357. activations.append(activation_stats)
  358. # multiple inputs to the network
  359. if not isinstance(input_shapes[0], tuple):
  360. input_shapes = [input_shapes]
  361. params = []
  362. flops = []
  363. hooks = []
  364. activations = []
  365. total_stats = namedtuple("total_stats", ["param_size", "flops", "act_size"])
  366. stats_details = namedtuple("module_stats", ["params", "flops", "activations"])
  367. for (name, module) in model.named_modules():
  368. if isinstance(module, hook_modules):
  369. hooks.append(
  370. module.register_forward_hook(partial(module_stats_hook, name=name))
  371. )
  372. inputs = [zeros(in_size, dtype=np.float32) for in_size in input_shapes]
  373. with set_module_mode_safe(model, training=False) as model:
  374. model(*inputs)
  375. for h in hooks:
  376. h.remove()
  377. extra_info = {
  378. "#params": len(params),
  379. }
  380. (
  381. total_flops,
  382. total_param_dims,
  383. total_param_size,
  384. total_act_dims,
  385. total_param_size,
  386. ) = (0, 0, 0, 0, 0)
  387. total_param_dims, total_param_size, params = sum_param_stats(params, bar_length_max)
  388. extra_info["total_param_dims"] = sizeof_fmt(total_param_dims, suffix="")
  389. extra_info["total_param_size"] = sizeof_fmt(total_param_size)
  390. if log_params:
  391. print_param_stats(params)
  392. total_flops, flops = sum_op_stats(flops, bar_length_max)
  393. extra_info["total_flops"] = sizeof_fmt(total_flops, suffix="OPs")
  394. if log_flops:
  395. print_op_stats(flops)
  396. total_act_dims, total_act_size, activations = sum_activations_stats(
  397. activations, bar_length_max
  398. )
  399. extra_info["total_act_dims"] = sizeof_fmt(total_act_dims, suffix="")
  400. extra_info["total_act_size"] = sizeof_fmt(total_act_size)
  401. if log_activations:
  402. print_activations_stats(activations)
  403. extra_info["flops/param_size"] = "{:3.3f}".format(total_flops / total_param_size)
  404. print_summary(**extra_info)
  405. return (
  406. total_stats(
  407. param_size=total_param_size, flops=total_flops, act_size=total_act_size,
  408. ),
  409. stats_details(params=params, flops=flops, activations=activations),
  410. )

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台