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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 functools import partial
  9. import numpy as np
  10. import tabulate
  11. import megengine as mge
  12. import megengine.module as m
  13. import megengine.module.qat as qatm
  14. import megengine.module.quantized as qm
  15. from megengine.core.tensor.dtype import get_dtype_bit
  16. from megengine.functional.tensor import zeros
  17. try:
  18. mge.logger.MegEngineLogFormatter.max_lines = float("inf")
  19. except AttributeError as e:
  20. raise ValueError("set logger max lines failed")
  21. logger = mge.get_logger(__name__)
  22. logger.setLevel("INFO")
  23. _calc_flops_dict = {}
  24. _calc_receptive_field_dict = {}
  25. def _receptive_field_fallback(module, inputs, outputs):
  26. if not _receptive_field_enabled:
  27. return
  28. assert not hasattr(module, "_rf")
  29. assert not hasattr(module, "_stride")
  30. if len(inputs) == 0:
  31. # TODO: support other dimension
  32. module._rf = (1, 1)
  33. module._stride = (1, 1)
  34. return module._rf, module._stride
  35. rf, stride = preprocess_receptive_field(module, inputs, outputs)
  36. module._rf = rf
  37. module._stride = stride
  38. return rf, stride
  39. # key tuple, impl_dict, fallback
  40. _iter_list = [
  41. ("flops_num", _calc_flops_dict, None),
  42. (
  43. ("receptive_field", "stride"),
  44. _calc_receptive_field_dict,
  45. _receptive_field_fallback,
  46. ),
  47. ]
  48. _receptive_field_enabled = False
  49. def _register_dict(*modules, dict=None):
  50. def callback(impl):
  51. for module in modules:
  52. dict[module] = impl
  53. return impl
  54. return callback
  55. def register_flops(*modules):
  56. return _register_dict(*modules, dict=_calc_flops_dict)
  57. def register_receptive_field(*modules):
  58. return _register_dict(*modules, dict=_calc_receptive_field_dict)
  59. def enable_receptive_field():
  60. global _receptive_field_enabled
  61. _receptive_field_enabled = True
  62. def disable_receptive_field():
  63. global _receptive_field_enabled
  64. _receptive_field_enabled = False
  65. @register_flops(
  66. m.Conv1d, m.Conv2d, m.Conv3d,
  67. )
  68. def flops_convNd(module: m.Conv2d, inputs, outputs):
  69. bias = 1 if module.bias is not None else 0
  70. group = module.groups
  71. ic = inputs[0].shape[1]
  72. oc = outputs[0].shape[1]
  73. goc = oc // group
  74. gic = ic // group
  75. N = outputs[0].shape[0]
  76. HW = np.prod(outputs[0].shape[2:])
  77. # N x Cout x H x W x (Cin x Kw x Kh + bias)
  78. return N * HW * goc * (gic * np.prod(module.kernel_size) + bias)
  79. @register_flops(m.ConvTranspose2d)
  80. def flops_deconvNd(module: m.ConvTranspose2d, inputs, outputs):
  81. return np.prod(inputs[0].shape) * outputs[0].shape[1] * np.prod(module.kernel_size)
  82. @register_flops(m.Linear)
  83. def flops_linear(module: m.Linear, inputs, outputs):
  84. bias = 1 if module.bias is not None else 0
  85. return np.prod(outputs[0].shape) * module.in_features
  86. @register_flops(m.BatchMatMulActivation)
  87. def flops_batchmatmul(module: m.BatchMatMulActivation, inputs, outputs):
  88. bias = 1 if module.bias is not None else 0
  89. x = inputs[0]
  90. w = module.weight
  91. batch_size = x.shape[0]
  92. n, p = x.shape[1:]
  93. _, m = w.shape[1:]
  94. return n * (p + bias) * m * batch_size
  95. # does not need import qat and quantized module since they inherit from float module.
  96. hook_modules = (
  97. m.conv._ConvNd,
  98. m.Linear,
  99. m.BatchMatMulActivation,
  100. )
  101. def dict2table(list_of_dict, header):
  102. table_data = [header]
  103. for d in list_of_dict:
  104. row = []
  105. for h in header:
  106. v = ""
  107. if h in d:
  108. v = d[h]
  109. row.append(v)
  110. table_data.append(row)
  111. return table_data
  112. def sizeof_fmt(num, suffix="B"):
  113. for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
  114. if abs(num) < 1024.0:
  115. return "{:3.3f} {}{}".format(num, unit, suffix)
  116. num /= 1024.0
  117. sign_str = "-" if num < 0 else ""
  118. return "{}{:.1f} {}{}".format(sign_str, num, "Yi", suffix)
  119. def preprocess_receptive_field(module, inputs, outputs):
  120. # TODO: support other dimensions
  121. pre_rf = (
  122. max(getattr(i.owner, "_rf", (1, 1))[0] for i in inputs),
  123. max(getattr(i.owner, "_rf", (1, 1))[1] for i in inputs),
  124. )
  125. pre_stride = (
  126. max(getattr(i.owner, "_stride", (1, 1))[0] for i in inputs),
  127. max(getattr(i.owner, "_stride", (1, 1))[1] for i in inputs),
  128. )
  129. return pre_rf, pre_stride
  130. def get_op_stats(module, inputs, outputs):
  131. rst = {
  132. "input_shapes": [i.shape for i in inputs],
  133. "output_shapes": [o.shape for o in outputs],
  134. }
  135. valid_flag = False
  136. for key, _dict, fallback in _iter_list:
  137. for _type in _dict:
  138. if isinstance(module, _type):
  139. value = _dict[_type](module, inputs, outputs)
  140. valid_flag = True
  141. break
  142. else:
  143. if fallback is not None:
  144. value = fallback(module, inputs, outputs)
  145. continue
  146. if isinstance(key, tuple):
  147. assert isinstance(value, tuple)
  148. for k, v in zip(key, value):
  149. rst[k] = v
  150. else:
  151. rst[key] = value
  152. if valid_flag:
  153. return rst
  154. else:
  155. return None
  156. return
  157. def print_op_stats(flops, bar_length_max=20):
  158. max_flops_num = max([i["flops_num"] for i in flops] + [0])
  159. total_flops_num = 0
  160. for d in flops:
  161. total_flops_num += int(d["flops_num"])
  162. d["flops_cum"] = sizeof_fmt(total_flops_num, suffix="OPs")
  163. for d in flops:
  164. ratio = d["ratio"] = d["flops_num"] / total_flops_num
  165. d["percentage"] = "{:.2f}%".format(ratio * 100)
  166. bar_length = int(d["flops_num"] / max_flops_num * bar_length_max)
  167. d["bar"] = "#" * bar_length
  168. d["flops"] = sizeof_fmt(d["flops_num"], suffix="OPs")
  169. header = [
  170. "name",
  171. "class_name",
  172. "input_shapes",
  173. "output_shapes",
  174. "flops",
  175. "flops_cum",
  176. "percentage",
  177. "bar",
  178. ]
  179. if _receptive_field_enabled:
  180. header.insert(4, "receptive_field")
  181. header.insert(5, "stride")
  182. total_flops_str = sizeof_fmt(total_flops_num, suffix="OPs")
  183. total_var_size = sum(
  184. sum(s[1] if len(s) > 1 else 0 for s in d["output_shapes"]) for d in flops
  185. )
  186. flops.append(
  187. dict(name="total", flops=total_flops_str, output_shapes=total_var_size)
  188. )
  189. logger.info("flops stats: \n" + tabulate.tabulate(dict2table(flops, header=header)))
  190. return total_flops_num
  191. def get_param_stats(param: np.ndarray):
  192. nbits = get_dtype_bit(param.dtype.name)
  193. shape = param.shape
  194. param_dim = np.prod(param.shape)
  195. param_size = param_dim * nbits // 8
  196. return {
  197. "dtype": param.dtype,
  198. "shape": shape,
  199. "mean": "{:.3g}".format(param.mean()),
  200. "std": "{:.3g}".format(param.std()),
  201. "param_dim": param_dim,
  202. "nbits": nbits,
  203. "size": param_size,
  204. }
  205. def print_param_stats(params, bar_length_max=20):
  206. max_size = max([d["size"] for d in params] + [0])
  207. total_param_dims, total_param_size = 0, 0
  208. for d in params:
  209. total_param_dims += int(d["param_dim"])
  210. total_param_size += int(d["size"])
  211. d["size_cum"] = sizeof_fmt(total_param_size)
  212. for d in params:
  213. ratio = d["size"] / total_param_size
  214. d["ratio"] = ratio
  215. d["percentage"] = "{:.2f}%".format(ratio * 100)
  216. bar_length = int(d["size"] / max_size * bar_length_max)
  217. d["size_bar"] = "#" * bar_length
  218. d["size"] = sizeof_fmt(d["size"])
  219. param_size = sizeof_fmt(total_param_size)
  220. params.append(dict(name="total", param_dim=total_param_dims, size=param_size,))
  221. header = [
  222. "name",
  223. "dtype",
  224. "shape",
  225. "mean",
  226. "std",
  227. "param_dim",
  228. "bits",
  229. "size",
  230. "size_cum",
  231. "percentage",
  232. "size_bar",
  233. ]
  234. logger.info(
  235. "param stats: \n" + tabulate.tabulate(dict2table(params, header=header))
  236. )
  237. return total_param_dims, total_param_size
  238. def print_summary(**kwargs):
  239. data = [["item", "value"]]
  240. data.extend(list(kwargs.items()))
  241. logger.info("summary\n" + tabulate.tabulate(data))
  242. def module_stats(
  243. model: m.Module,
  244. input_size: int,
  245. bar_length_max: int = 20,
  246. log_params: bool = True,
  247. log_flops: bool = True,
  248. ):
  249. r"""
  250. Calculate and print ``model``'s statistics by adding hook and record Module's inputs outputs size.
  251. :param model: model that need to get stats info.
  252. :param input_size: size of input for running model and calculating stats.
  253. :param bar_length_max: size of bar indicating max flops or parameter size in net stats.
  254. :param log_params: whether print and record params size.
  255. :param log_flops: whether print and record op flops.
  256. """
  257. disable_receptive_field()
  258. def module_stats_hook(module, inputs, outputs, name=""):
  259. class_name = str(module.__class__).split(".")[-1].split("'")[0]
  260. flops_stats = get_op_stats(module, inputs, outputs)
  261. if flops_stats is not None:
  262. flops_stats["name"] = name
  263. flops_stats["class_name"] = class_name
  264. flops.append(flops_stats)
  265. if hasattr(module, "weight") and module.weight is not None:
  266. w = module.weight
  267. param_stats = get_param_stats(w.numpy())
  268. param_stats["name"] = name + "-w"
  269. params.append(param_stats)
  270. if hasattr(module, "bias") and module.bias is not None:
  271. b = module.bias
  272. param_stats = get_param_stats(b.numpy())
  273. param_stats["name"] = name + "-b"
  274. params.append(param_stats)
  275. # multiple inputs to the network
  276. if not isinstance(input_size[0], tuple):
  277. input_size = [input_size]
  278. params = []
  279. flops = []
  280. hooks = []
  281. for (name, module) in model.named_modules():
  282. if isinstance(module, hook_modules):
  283. hooks.append(
  284. module.register_forward_hook(partial(module_stats_hook, name=name))
  285. )
  286. inputs = [zeros(in_size, dtype=np.float32) for in_size in input_size]
  287. model.eval()
  288. model(*inputs)
  289. for h in hooks:
  290. h.remove()
  291. extra_info = {
  292. "#params": len(params),
  293. }
  294. total_flops, total_param_dims, total_param_size = 0, 0, 0
  295. if log_params:
  296. total_param_dims, total_param_size = print_param_stats(params, bar_length_max)
  297. extra_info["total_param_dims"] = sizeof_fmt(total_param_dims)
  298. extra_info["total_param_size"] = sizeof_fmt(total_param_size)
  299. if log_flops:
  300. total_flops = print_op_stats(flops, bar_length_max)
  301. extra_info["total_flops"] = sizeof_fmt(total_flops, suffix="OPs")
  302. if log_params and log_flops:
  303. extra_info["flops/param_size"] = "{:3.3f}".format(
  304. total_flops / total_param_size
  305. )
  306. print_summary(**extra_info)
  307. return total_param_size, total_flops

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