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.

net_stats.py 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 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._internal as mgb
  13. import megengine.module as m
  14. import megengine.module.qat as qatm
  15. import megengine.module.quantized as qm
  16. try:
  17. mge.logger.MegEngineLogFormatter.max_lines = float("inf")
  18. except AttributeError as e:
  19. raise ValueError("set logger max lines failed")
  20. logger = mge.get_logger(__name__)
  21. CALC_FLOPS = {}
  22. def _register_modules(*modules):
  23. def callback(impl):
  24. for module in modules:
  25. CALC_FLOPS[module] = impl
  26. return impl
  27. return callback
  28. @_register_modules(
  29. m.Conv2d,
  30. m.ConvTranspose2d,
  31. m.LocalConv2d,
  32. qm.Conv2d,
  33. qm.ConvRelu2d,
  34. qm.ConvBn2d,
  35. qm.ConvBnRelu2d,
  36. qatm.Conv2d,
  37. qatm.ConvRelu2d,
  38. qatm.ConvBn2d,
  39. qatm.ConvBnRelu2d,
  40. )
  41. def count_convNd(module, input, output):
  42. bias = 1 if module.bias is not None else 0
  43. group = module.groups
  44. ic = input[0].shape[1]
  45. oc = output[0].shape[1]
  46. goc = oc // group
  47. gic = ic // group
  48. N = output[0].shape[0]
  49. HW = np.prod(output[0].shape[2:])
  50. # N x Cout x H x W x (Cin x Kw x Kh + bias)
  51. return N * HW * goc * (gic * np.prod(module.kernel_size) + bias)
  52. @_register_modules(m.ConvTranspose2d)
  53. def count_deconvNd(module, input, output):
  54. return np.prod(input[0].shape) * output[0].shape[1] * np.prod(module.kernel_size)
  55. @_register_modules(m.Linear, qatm.Linear, qm.Linear)
  56. def count_linear(module, input, output):
  57. return np.prod(output[0].shape) * module.in_features
  58. # does not need import qat and quantized module since they inherit from float module.
  59. hook_modules = (
  60. m.Conv2d,
  61. m.ConvTranspose2d,
  62. m.LocalConv2d,
  63. m.BatchNorm2d,
  64. m.Linear,
  65. )
  66. def net_stats(model, input_size, bar_length_max=20, log_params=True, log_flops=True):
  67. def dict2table(list_of_dict, header):
  68. table_data = [header]
  69. for d in list_of_dict:
  70. row = []
  71. for h in header:
  72. v = ""
  73. if h in d:
  74. v = d[h]
  75. row.append(v)
  76. table_data.append(row)
  77. return table_data
  78. def sizeof_fmt(num, suffix="B"):
  79. for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
  80. if abs(num) < 1024.0:
  81. return "{:3.3f} {}{}".format(num, unit, suffix)
  82. num /= 1024.0
  83. sign_str = "-" if num < 0 else ""
  84. return "{}{:.1f} {}{}".format(sign_str, num, "Yi", suffix)
  85. def get_byteswidth(tensor):
  86. dtype = tensor.dtype
  87. if mgb.dtype.is_quantize(dtype):
  88. return 1
  89. elif mgb.dtype.is_bfloat16(dtype):
  90. return 2
  91. else:
  92. return 4
  93. def print_flops_stats(flops):
  94. flops_list = [i["flops_num"] for i in flops]
  95. max_flops_num = max(flops_list + [0])
  96. # calc total flops and set flops_cum
  97. total_flops_num = 0
  98. for d in flops:
  99. total_flops_num += int(d["flops_num"])
  100. d["flops_cum"] = sizeof_fmt(total_flops_num, suffix="OPs")
  101. for i in flops:
  102. f = i["flops_num"]
  103. i["flops"] = sizeof_fmt(f, suffix="OPs")
  104. r = i["ratio"] = f / total_flops_num
  105. i["percentage"] = "{:.2f}%".format(r * 100)
  106. bar_length = int(f / max_flops_num * bar_length_max)
  107. i["bar"] = "#" * bar_length
  108. header = [
  109. "name",
  110. "class_name",
  111. "input_shapes",
  112. "output_shapes",
  113. "flops",
  114. "flops_cum",
  115. "percentage",
  116. "bar",
  117. ]
  118. total_flops_str = sizeof_fmt(total_flops_num, suffix="OPs")
  119. total_var_size = sum(sum(s[1] for s in i["output_shapes"]) for i in flops)
  120. flops.append(
  121. dict(name="total", flops=total_flops_str, output_shapes=total_var_size)
  122. )
  123. logger.info(
  124. "flops stats: \n" + tabulate.tabulate(dict2table(flops, header=header))
  125. )
  126. return total_flops_num
  127. def print_params_stats(params):
  128. total_param_dims, total_param_size = 0, 0
  129. for d in params:
  130. total_param_dims += int(d["param_dim"])
  131. total_param_size += int(d["size"])
  132. d["size"] = sizeof_fmt(d["size"])
  133. d["size_cum"] = sizeof_fmt(total_param_size)
  134. for d in params:
  135. ratio = d["param_dim"] / total_param_dims
  136. d["ratio"] = ratio
  137. d["percentage"] = "{:.2f}%".format(ratio * 100)
  138. # construct bar
  139. max_ratio = max([d["ratio"] for d in params])
  140. for d in params:
  141. bar_length = int(d["ratio"] / max_ratio * bar_length_max)
  142. d["size_bar"] = "#" * bar_length
  143. param_size = sizeof_fmt(total_param_size)
  144. params.append(dict(name="total", param_dim=total_param_dims, size=param_size,))
  145. header = [
  146. "name",
  147. "shape",
  148. "mean",
  149. "std",
  150. "param_dim",
  151. "bits",
  152. "size",
  153. "size_cum",
  154. "percentage",
  155. "size_bar",
  156. ]
  157. logger.info(
  158. "param stats: \n" + tabulate.tabulate(dict2table(params, header=header))
  159. )
  160. return total_param_size
  161. def net_stats_hook(module, input, output, name=""):
  162. class_name = str(module.__class__).split(".")[-1].split("'")[0]
  163. flops_fun = CALC_FLOPS.get(type(module))
  164. if callable(flops_fun):
  165. flops_num = flops_fun(module, input, output)
  166. if not isinstance(output, (list, tuple)):
  167. output = [output]
  168. flops.append(
  169. dict(
  170. name=name,
  171. class_name=class_name,
  172. input_shapes=[i.shape for i in input],
  173. output_shapes=[o.shape for o in output],
  174. flops_num=flops_num,
  175. flops_cum=0,
  176. )
  177. )
  178. if hasattr(module, "weight") and module.weight is not None:
  179. w = module.weight
  180. value = w.numpy()
  181. param_dim = np.prod(w.shape)
  182. param_bytes = get_byteswidth(w)
  183. params.append(
  184. dict(
  185. name=name + "-w",
  186. shape=w.shape,
  187. param_dim=param_dim,
  188. bits=param_bytes * 8,
  189. size=param_dim * param_bytes,
  190. size_cum=0,
  191. mean="{:.2g}".format(value.mean()),
  192. std="{:.2g}".format(value.std()),
  193. )
  194. )
  195. if hasattr(module, "bias") and module.bias is not None:
  196. b = module.bias
  197. value = b.numpy()
  198. param_dim = np.prod(b.shape)
  199. param_bytes = get_byteswidth(b)
  200. params.append(
  201. dict(
  202. name=name + "-b",
  203. shape=b.shape,
  204. param_dim=param_dim,
  205. bits=param_bytes * 8,
  206. size=param_dim * param_bytes,
  207. size_cum=0,
  208. mean="{:.2g}".format(value.mean()),
  209. std="{:.2g}".format(value.std()),
  210. )
  211. )
  212. # multiple inputs to the network
  213. if not isinstance(input_size[0], tuple):
  214. input_size = [input_size]
  215. params = []
  216. flops = []
  217. hooks = []
  218. for (name, module) in model.named_modules():
  219. if isinstance(module, hook_modules):
  220. hooks.append(
  221. module.register_forward_hook(partial(net_stats_hook, name=name))
  222. )
  223. inputs = [mge.zeros(in_size, dtype=np.float32) for in_size in input_size]
  224. model.eval()
  225. model(*inputs)
  226. for h in hooks:
  227. h.remove()
  228. total_flops, total_params = 0, 0
  229. if log_params:
  230. total_params = print_params_stats(params)
  231. if log_flops:
  232. total_flops = print_flops_stats(flops)
  233. return total_params, total_flops

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