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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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.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. module.in_channels // module.groups * np.prod(module.kernel_size) + bias
  70. )
  71. @register_flops(
  72. M.ConvTranspose2d
  73. )
  74. def flops_convNdTranspose(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(inputs[0].shape) * (
  78. module.out_channels // module.groups * np.prod(module.kernel_size)
  79. ) + np.prod(outputs[0].shape) * bias
  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 = Tensor(inp).astype(np.float32)
  127. return F.mean(inp).numpy()
  128. def _std(inp):
  129. inp = 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"""Calculate and print ``model``'s statistics by adding hook and record Module's inputs outputs size.
  344. Args:
  345. model: model that need to get stats info.
  346. inputs: user defined input data for running model and calculating stats, alternative with input_shapes.
  347. input_shapes: shapes to generate random inputs for running model and calculating stats, alternative with inputs.
  348. cal_params: whether calculate and record params size.
  349. cal_flops: whether calculate and record op flops.
  350. cal_activations: whether calculate and record op activations.
  351. logging_to_stdout: whether print all calculated statistic details.
  352. 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. def load_tensor(x):
  360. if isinstance(x, np.ndarray):
  361. return Tensor(x)
  362. elif isinstance(x, collections.abc.Mapping):
  363. return {k: load_tensor(v) for k, v in x.items()}
  364. elif isinstance(x, tuple) and hasattr(x, "_fields"): # nametuple
  365. return type(x)(*(load_tensor(value) for value in x))
  366. elif isinstance(x, collections.abc.Sequence):
  367. return [load_tensor(v) for v in x]
  368. else:
  369. return Tensor(x, dtype=np.float32)
  370. inputs = load_tensor(inputs)
  371. else:
  372. if input_shapes:
  373. if not isinstance(input_shapes[0], tuple):
  374. input_shapes = [input_shapes]
  375. inputs = [F.zeros(in_size, dtype=np.float32) for in_size in input_shapes]
  376. else:
  377. logger.error(
  378. "Inputs or input_shapes is required for running model and calculating stats.",
  379. exc_info=True,
  380. )
  381. return
  382. if not cal_activations:
  383. log_activations = False
  384. disable_receptive_field()
  385. def module_stats_hook(module, inputs, outputs, name=""):
  386. class_name = str(module.__class__).split(".")[-1].split("'")[0]
  387. if cal_flops:
  388. flops_stats = get_op_stats(module, inputs, outputs)
  389. if flops_stats is not None:
  390. flops_stats["name"] = name
  391. flops_stats["class_name"] = class_name
  392. flops.append(flops_stats)
  393. if cal_params:
  394. if hasattr(module, "weight") and module.weight is not None:
  395. w = module.weight
  396. param_stats = get_param_stats(w)
  397. param_stats["name"] = name + "-w"
  398. params.append(param_stats)
  399. if hasattr(module, "bias") and module.bias is not None:
  400. b = module.bias
  401. param_stats = get_param_stats(b)
  402. param_stats["name"] = name + "-b"
  403. params.append(param_stats)
  404. if cal_activations:
  405. if not isinstance(outputs, (tuple, list)):
  406. output = outputs
  407. else:
  408. output = outputs[0]
  409. activation_stats = get_activation_stats(output, has_inputs)
  410. activation_stats["name"] = name
  411. activation_stats["class_name"] = class_name
  412. activations.append(activation_stats)
  413. params = []
  414. flops = []
  415. hooks = []
  416. activations = []
  417. total_stats = namedtuple(
  418. "total_stats", ["param_size", "param_dims", "flops", "act_size", "act_dims"]
  419. )
  420. stats_details = namedtuple("module_stats", ["params", "flops", "activations"])
  421. for (name, module) in model.named_modules():
  422. if isinstance(module, hook_modules):
  423. hooks.append(
  424. module.register_forward_hook(partial(module_stats_hook, name=name))
  425. )
  426. with set_module_mode_safe(model, training=False) as model:
  427. model(*inputs)
  428. for h in hooks:
  429. h.remove()
  430. extra_info = {
  431. "#params": len(params),
  432. }
  433. (
  434. total_flops,
  435. total_param_dims,
  436. total_param_size,
  437. total_act_dims,
  438. total_act_size,
  439. ) = (0, 0, 0, 0, 0)
  440. if cal_params:
  441. total_param_dims, total_param_size, params = sum_param_stats(
  442. params, bar_length_max
  443. )
  444. extra_info["total_param_dims"] = sizeof_fmt(total_param_dims, suffix="")
  445. extra_info["total_param_size"] = sizeof_fmt(total_param_size)
  446. if logging_to_stdout:
  447. print_param_stats(params)
  448. if cal_flops:
  449. total_flops, flops = sum_op_stats(flops, bar_length_max)
  450. extra_info["total_flops"] = sizeof_fmt(total_flops, suffix="OPs")
  451. if logging_to_stdout:
  452. print_op_stats(flops)
  453. if cal_activations:
  454. total_act_dims, total_act_size, activations = sum_activations_stats(
  455. activations, bar_length_max
  456. )
  457. extra_info["total_act_dims"] = sizeof_fmt(total_act_dims, suffix="")
  458. extra_info["total_act_size"] = sizeof_fmt(total_act_size)
  459. if logging_to_stdout:
  460. print_activations_stats(activations, has_inputs)
  461. if cal_flops and cal_params and total_param_size != 0:
  462. extra_info["flops/param_size"] = "{:3.3f}".format(
  463. total_flops / total_param_size
  464. )
  465. print_summary(**extra_info)
  466. return (
  467. total_stats(
  468. param_size=total_param_size,
  469. param_dims=total_param_dims,
  470. flops=total_flops,
  471. act_size=total_act_size,
  472. act_dims=total_act_dims,
  473. ),
  474. stats_details(params=params, flops=flops, activations=activations),
  475. )