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

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