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.

dump_model_mgb.py 6.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from megskull.graph import NodeFilter, FpropEnv
  10. from megskull.opr.all import AssertEqual, DataProvider, BatchNormalization
  11. from megskull.utils.logconf import get_logger
  12. from meghair.utils import io
  13. import megbrain as mgb
  14. import argparse
  15. import struct
  16. import re
  17. import os
  18. import numpy as np
  19. import cv2
  20. logger = get_logger(__name__)
  21. def optimize_for_inference(args, outputs):
  22. args_map = {
  23. 'enable_io16xc32': 'f16_io_f32_comp',
  24. 'enable_ioc16': 'f16_io_comp',
  25. 'enable_hwcd4': 'use_nhwcd4',
  26. 'enable_nchw4': 'use_nchw4',
  27. 'enable_nchw88': 'use_nchw88',
  28. 'enable_nchw44': 'use_nchw44',
  29. 'enable_nchw44_dot': 'use_nchw44_dot',
  30. 'enable_nchw32': 'use_nchw32',
  31. 'enable_chwn4': 'use_chwn4',
  32. 'enable_fuse_conv_bias_nonlinearity': 'fuse_conv_bias_nonlinearity',
  33. 'enable_fuse_conv_bias_with_z': 'fuse_conv_bias_with_z',
  34. }
  35. kwargs = {}
  36. for k, v in args_map.items():
  37. if getattr(args, k):
  38. assert args.optimize_for_inference, (
  39. 'optimize_for_inference should be set when {} is given'.format(
  40. k))
  41. kwargs[v] = True
  42. if args.optimize_for_inference:
  43. return mgb.optimize_for_inference(outputs, **kwargs)
  44. return outputs
  45. def main():
  46. parser = argparse.ArgumentParser(
  47. description='Dump the Python Megbrain model to C++ model, by the way '
  48. 'optimizing for inference',
  49. formatter_class=argparse.ArgumentDefaultsHelpFormatter
  50. )
  51. parser.add_argument('input', help='input pkl model file ')
  52. parser.add_argument('-o', '--output', help='output file', required=True)
  53. parser.add_argument('--init-bn', action='store_true',
  54. help='initialize untrained batch-normalization, to '
  55. 'avoid NaN or Inf results')
  56. parser.add_argument('--silent', action='store_true',
  57. help='set verbose to False in AssertEqual opr')
  58. parser.add_argument('--optimize-for-inference', action='store_true',
  59. help='enbale optimization for inference')
  60. parser.add_argument('--discard-var-name', action='store_true',
  61. help='discard variable and param names in the '
  62. 'generated output')
  63. parser.add_argument('--output-strip-info', action='store_true',
  64. help='output code strip information')
  65. parser.add_argument('--enable-io16xc32', action='store_true',
  66. help='transform the mode to float16 io float32 compute')
  67. parser.add_argument('--enable-ioc16', action='store_true',
  68. help='transform the dtype of the model to float16 io '
  69. 'and compute')
  70. parser.add_argument('--enable-fuse-conv-bias-nonlinearity',
  71. action='store_true',
  72. help='fuse convolution bias and nonlinearity opr to a '
  73. 'conv_bias opr and compute')
  74. parser.add_argument('--enable-hwcd4', action='store_true',
  75. help='transform the model format from NCHW to NHWCD4 '
  76. 'for inference; you may need to disable CUDA and set '
  77. 'MGB_USE_MEGDNN_DBG=2')
  78. parser.add_argument('--enable-nchw4', action='store_true',
  79. help='transform the model format from NCHW to NCHW4 '
  80. 'for inference')
  81. parser.add_argument('--enable-nchw88', action='store_true',
  82. help='transform the model format from NCHW to NCHW88 '
  83. 'for inference')
  84. parser.add_argument('--enable-nchw44', action='store_true',
  85. help='transform the model format from NCHW to NCHW44 '
  86. 'for inference')
  87. parser.add_argument('--enable-nchw44-dot', action='store_true',
  88. help='transform the model format from NCHW to NCHW44_DOT '
  89. 'for optimizing armv8.2 dot in inference')
  90. parser.add_argument('--enable-chwn4', action='store_true',
  91. help='transform the model format to CHWN4 '
  92. 'for inference, mainly used for nvidia tensorcore')
  93. parser.add_argument('--enable-nchw32', action='store_true',
  94. help='transform the model format from NCHW4 to NCHW32 '
  95. 'for inference on nvidia TensoCore')
  96. parser.add_argument('--enable-fuse-conv-bias-with-z', action='store_true',
  97. help='fuse conv_bias with z input for inference on '
  98. 'nvidia GPU (this optimization pass will result in mismatch '
  99. 'of the precision of output of training and inference)')
  100. args = parser.parse_args()
  101. env = FpropEnv(verbose_fprop=False)
  102. outputs = io.load_network(args.input).outputs
  103. output_mgbvars = list(map(env.get_mgbvar, outputs))
  104. output_mgbvars = optimize_for_inference(args, output_mgbvars)
  105. if args.discard_var_name:
  106. sereg_kwargs = dict(keep_var_name=0, keep_param_name=False)
  107. else:
  108. sereg_kwargs = dict(keep_var_name=2, keep_param_name=True)
  109. stat = mgb.serialize_comp_graph_to_file(
  110. args.output, output_mgbvars, append=False,
  111. output_strip_info=args.output_strip_info,
  112. **sereg_kwargs)
  113. logger.info('graph dump sizes: tot_size={:.3f}KiB overhead={:.3f}KiB'.
  114. format(stat.tot_bytes / 1024,
  115. (stat.tot_bytes - stat.tensor_value_bytes) / 1024))
  116. if __name__ == '__main__':
  117. main()

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