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

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