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

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