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

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

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