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

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

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