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 17 kB

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

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