m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

202 lines
9.7 KiB

6 months ago
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License.
  3. import os
  4. # Check if the flatbuffers module is available. If not we cannot handle type reduction information in the config.
  5. try:
  6. import flatbuffers # noqa
  7. have_flatbuffers = True
  8. from .ort_format_model import GloballyAllowedTypesOpTypeImplFilter, OperatorTypeUsageManager # noqa
  9. except ImportError:
  10. have_flatbuffers = False
  11. def parse_config(config_file: str, enable_type_reduction: bool = False):
  12. """
  13. Parse the configuration file and return the required operators dictionary and an
  14. OpTypeImplFilterInterface instance.
  15. Configuration file lines can do the following:
  16. 1. specify required operators
  17. 2. specify globally allowed types for all operators
  18. 3. specify what it means for no required operators to be specified
  19. 1. Specifying required operators
  20. The basic format for specifying required operators is `domain;opset1,opset2;op1,op2...`
  21. e.g. `ai.onnx;11;Add,Cast,Clip,... for a single opset
  22. `ai.onnx;11,12;Add,Cast,Clip,... for multiple opsets
  23. note: Configuration information is accrued as the file is parsed. If an operator requires support from multiple
  24. opsets that can be done with one entry for each opset, or one entry with multiple opsets in it.
  25. If the configuration file is generated from ORT format models it may optionally contain JSON for per-operator
  26. type reduction. The required types are generally listed per input and/or output of the operator.
  27. The type information is in a map, with 'inputs' and 'outputs' keys. The value for 'inputs' or 'outputs' is a map
  28. between the index number of the input/output and the required list of types.
  29. For example, both the input and output types are relevant to ai.onnx:Cast.
  30. Type information for input 0 and output 0 could look like this:
  31. `{"inputs": {"0": ["float", "int32_t"]}, "outputs": {"0": ["float", "int64_t"]}}`
  32. which is added directly after the operator name in the configuration file.
  33. e.g.
  34. `ai.onnx;12;Add,Cast{"inputs": {"0": ["float", "int32_t"]}, "outputs": {"0": ["float", "int64_t"]}},Concat`
  35. If for example the types of inputs 0 and 1 were important, the entry may look like this (e.g. ai.onnx:Gather):
  36. `{"inputs": {"0": ["float", "int32_t"], "1": ["int32_t"]}}`
  37. Finally some operators do non-standard things and store their type information under a 'custom' key.
  38. ai.onnx.OneHot is an example of this, where the three input types are combined into a triple.
  39. `{"custom": [["float", "int64_t", "int64_t"], ["int64_t", "std::string", "int64_t"]]}`
  40. 2. Specifying globally allowed types for all operators
  41. The format for specifying globally allowed types for all operators is:
  42. `!globally_allowed_types;T0,T1,...`
  43. Ti should be a C++ scalar type supported by ONNX and ORT.
  44. At most one globally allowed types specification is allowed.
  45. Specifying per-operator type information and specifying globally allowed types are mutually exclusive - it is an
  46. error to specify both.
  47. 3. Specify what it means for no required operators to be specified
  48. By default, if no required operators are specified, NO operators are required.
  49. With the following line, if no required operators are specified, ALL operators are required:
  50. `!no_ops_specified_means_all_ops_are_required`
  51. :param config_file: Configuration file to parse
  52. :param enable_type_reduction: Set to True to use the type information in the config.
  53. If False the type information will be ignored.
  54. If the flatbuffers module is unavailable type information will be ignored as the
  55. type-based filtering has a dependency on the ORT flatbuffers schema.
  56. :return: required_ops: Dictionary of domain:opset:[ops] for required operators. If None, all operators are
  57. required.
  58. op_type_impl_filter: OpTypeImplFilterInterface instance if type reduction is enabled, the flatbuffers
  59. module is available, and type reduction information is present. None otherwise.
  60. """
  61. if not os.path.isfile(config_file):
  62. raise ValueError("Configuration file {} does not exist".format(config_file))
  63. # only enable type reduction when flatbuffers is available
  64. enable_type_reduction = enable_type_reduction and have_flatbuffers
  65. required_ops = {}
  66. no_ops_specified_means_all_ops_are_required = False
  67. op_type_usage_manager = OperatorTypeUsageManager() if enable_type_reduction else None
  68. has_op_type_reduction_info = False
  69. globally_allowed_types = None
  70. def process_non_op_line(line):
  71. if not line or line.startswith("#"): # skip empty lines and comments
  72. return True
  73. if line.startswith("!globally_allowed_types;"): # handle globally allowed types
  74. if enable_type_reduction:
  75. nonlocal globally_allowed_types
  76. if globally_allowed_types is not None:
  77. raise RuntimeError("Globally allowed types were already specified.")
  78. globally_allowed_types = set(segment.strip() for segment in line.split(";")[1].split(","))
  79. return True
  80. if line == "!no_ops_specified_means_all_ops_are_required": # handle all ops required line
  81. nonlocal no_ops_specified_means_all_ops_are_required
  82. no_ops_specified_means_all_ops_are_required = True
  83. return True
  84. return False
  85. with open(config_file, "r") as config:
  86. for line in [orig_line.strip() for orig_line in config.readlines()]:
  87. if process_non_op_line(line):
  88. continue
  89. domain, opset_str, operators_str = [segment.strip() for segment in line.split(";")]
  90. opsets = [int(s) for s in opset_str.split(",")]
  91. # any type reduction information is serialized json that starts/ends with { and }.
  92. # type info is optional for each operator.
  93. if "{" in operators_str:
  94. has_op_type_reduction_info = True
  95. # parse the entries in the json dictionary with type info
  96. operators = set()
  97. cur = 0
  98. end = len(operators_str)
  99. while cur < end:
  100. next_comma = operators_str.find(",", cur)
  101. next_open_brace = operators_str.find("{", cur)
  102. if next_comma == -1:
  103. next_comma = end
  104. # the json string starts with '{', so if that is found (next_open_brace != -1)
  105. # before the next comma (which would be the start of the next operator if there is no type info
  106. # for the current operator), we have type info to parse.
  107. # e.g. need to handle extracting the operator name and type info for OpB and OpD,
  108. # and just the operator names for OpA and OpC from this example string
  109. # OpA,OpB{"inputs": {"0": ["float", "int32_t"]}},OpC,OpD{"outputs": {"0": ["int32_t"]}}
  110. if 0 < next_open_brace < next_comma:
  111. operator = operators_str[cur:next_open_brace].strip()
  112. operators.add(operator)
  113. # parse out the json dictionary with the type info by finding the closing brace that matches
  114. # the opening brace
  115. i = next_open_brace + 1
  116. num_open_braces = 1
  117. while num_open_braces > 0 and i < end:
  118. if operators_str[i] == "{":
  119. num_open_braces += 1
  120. elif operators_str[i] == "}":
  121. num_open_braces -= 1
  122. i += 1
  123. if num_open_braces != 0:
  124. raise RuntimeError("Mismatched { and } in type string: " + operators_str[next_open_brace:])
  125. if op_type_usage_manager:
  126. type_str = operators_str[next_open_brace:i]
  127. op_type_usage_manager.restore_from_config_entry(domain, operator, type_str)
  128. cur = i + 1
  129. else:
  130. # comma or end of line is next
  131. end_str = next_comma if next_comma != -1 else end
  132. operators.add(operators_str[cur:end_str].strip())
  133. cur = end_str + 1
  134. else:
  135. operators = set([op.strip() for op in operators_str.split(",")])
  136. for opset in opsets:
  137. if domain not in required_ops:
  138. required_ops[domain] = {opset: operators}
  139. elif opset not in required_ops[domain]:
  140. required_ops[domain][opset] = operators
  141. else:
  142. required_ops[domain][opset].update(operators)
  143. if len(required_ops) == 0 and no_ops_specified_means_all_ops_are_required:
  144. required_ops = None
  145. op_type_impl_filter = None
  146. if enable_type_reduction:
  147. if not has_op_type_reduction_info:
  148. op_type_usage_manager = None
  149. if globally_allowed_types is not None and op_type_usage_manager is not None:
  150. raise RuntimeError(
  151. "Specifying globally allowed types and per-op type reduction info together is unsupported."
  152. )
  153. if globally_allowed_types is not None:
  154. op_type_impl_filter = GloballyAllowedTypesOpTypeImplFilter(globally_allowed_types)
  155. elif op_type_usage_manager is not None:
  156. op_type_impl_filter = op_type_usage_manager.make_op_type_impl_filter()
  157. return required_ops, op_type_impl_filter