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.

compare_binary_iodump.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #! /usr/bin/env python3
  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. import argparse
  10. import os
  11. import struct
  12. import textwrap
  13. from pathlib import Path
  14. import numpy as np
  15. def load_tensor_binary(fobj):
  16. """
  17. Load a tensor dumped by the :class:`BinaryOprIODump` plugin; the actual
  18. tensor value dump is implemented by ``mgb::debug::dump_tensor``.
  19. :param fobj: file object, or a string that contains the file name.
  20. :return: tuple ``(tensor_value, tensor_name)``.
  21. """
  22. if isinstance(fobj, str):
  23. with open(fobj, "rb") as fin:
  24. return load_tensor_binary(fin)
  25. DTYPE_LIST = {
  26. 0: np.float32,
  27. 1: np.uint8,
  28. 2: np.int8,
  29. 3: np.int16,
  30. 4: np.int32,
  31. # 5: _mgb.intb1,
  32. # 6: _mgb.intb2,
  33. # 7: _mgb.intb4,
  34. 8: None,
  35. 9: np.float16,
  36. # quantized dtype start from 100000
  37. # see MEGDNN_PARAMETERIZED_DTYPE_ENUM_BASE in
  38. # dnn/include/megdnn/dtype.h
  39. 100000: np.uint8,
  40. 100001: np.int32,
  41. 100002: np.int8,
  42. }
  43. header_fmt = struct.Struct("III")
  44. name_len, dtype, max_ndim = header_fmt.unpack(fobj.read(header_fmt.size))
  45. assert (
  46. DTYPE_LIST[dtype] is not None
  47. ), "Cannot load this tensor: dtype Byte is unsupported."
  48. shape = list(struct.unpack("I" * max_ndim, fobj.read(max_ndim * 4)))
  49. while shape[-1] == 0:
  50. shape.pop(-1)
  51. name = fobj.read(name_len).decode("ascii")
  52. return np.fromfile(fobj, dtype=DTYPE_LIST[dtype]).reshape(shape), name
  53. def check(v0, v1, name, max_err):
  54. v0 = np.ascontiguousarray(v0, dtype=np.float32)
  55. v1 = np.ascontiguousarray(v1, dtype=np.float32)
  56. assert np.isfinite(v0.sum()) and np.isfinite(
  57. v1.sum()
  58. ), "{} not finite: sum={} vs sum={}".format(name, v0.sum(), v1.sum())
  59. assert v0.shape == v1.shape, "{} shape mismatch: {} vs {}".format(
  60. name, v0.shape, v1.shape
  61. )
  62. vdiv = np.max([np.abs(v0), np.abs(v1), np.ones_like(v0)], axis=0)
  63. err = np.abs(v0 - v1) / vdiv
  64. rst = err > max_err
  65. if rst.sum():
  66. idx = tuple(i[0] for i in np.nonzero(rst))
  67. raise AssertionError(
  68. "{} not equal: "
  69. "shape={} nonequal_idx={} v0={} v1={} err={}".format(
  70. name, v0.shape, idx, v0[idx], v1[idx], err[idx]
  71. )
  72. )
  73. def main():
  74. parser = argparse.ArgumentParser(
  75. description=(
  76. "compare tensor dumps generated BinaryOprIODump plugin, "
  77. "it can compare two dirs or two single files"
  78. ),
  79. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  80. )
  81. parser.add_argument("input0", help="dirname or filename")
  82. parser.add_argument("input1", help="dirname or filename")
  83. parser.add_argument(
  84. "-e", "--max-err", type=float, default=1e-3, help="max allowed error"
  85. )
  86. parser.add_argument(
  87. "-s", "--stop-on-error", action="store_true", help="do not compare "
  88. )
  89. args = parser.parse_args()
  90. files0 = set()
  91. files1 = set()
  92. if os.path.isdir(args.input0):
  93. assert os.path.isdir(args.input1)
  94. name0 = set()
  95. name1 = set()
  96. for i in os.listdir(args.input0):
  97. files0.add(str(Path(args.input0) / i))
  98. name0.add(i)
  99. for i in os.listdir(args.input1):
  100. files1.add(str(Path(args.input1) / i))
  101. name1.add(i)
  102. assert name0 == name1, "dir files mismatch: a-b={} b-a={}".format(
  103. name0 - name1, name1 - name0
  104. )
  105. else:
  106. files0.add(args.input0)
  107. files1.add(args.input1)
  108. files0 = sorted(files0)
  109. files1 = sorted(files1)
  110. for i, j in zip(files0, files1):
  111. val0, name0 = load_tensor_binary(i)
  112. val1, name1 = load_tensor_binary(j)
  113. name = "{}: \n{}\n{}\n".format(
  114. i, "\n ".join(textwrap.wrap(name0)), "\n ".join(textwrap.wrap(name1))
  115. )
  116. try:
  117. check(val0, val1, name, args.max_err)
  118. except Exception as exc:
  119. if args.stop_on_error:
  120. raise exc
  121. print(exc)
  122. if __name__ == "__main__":
  123. main()

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