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.

377 lines
15 KiB

6 months ago
  1. # --------------------------------------------------------------------------
  2. # Copyright (c) Microsoft, Intel Corporation. All rights reserved.
  3. # Licensed under the MIT License. See License.txt in the project root for
  4. # license information.
  5. # --------------------------------------------------------------------------
  6. """Utilities to run a given ONNX model, while saving input/output tensors of
  7. eligible operator nodes.
  8. A use case is to debug quantization induced accuracy drop. An AI engineer can
  9. run the original float32 model and the quantized model with the same inputs,
  10. then compare the corresponding activations between the two models to find
  11. where the divergence is.
  12. Example Usage:
  13. ```python
  14. class ExampleDataReader(CalibrationDataReader):
  15. def __init__(self):
  16. ...
  17. def get_next(self):
  18. ...
  19. input_data_reader = ExampleDataReader()
  20. aug_model = modify_model_output_intermediate_tensors (path_to_onnx_model)
  21. augmented_model_path = str(Path(self._tmp_model_dir.name).joinpath("augmented_model.onnx"))
  22. onnx.save(
  23. aug_model,
  24. augmented_model_path,
  25. save_as_external_data=False,
  26. )
  27. tensor_dict = collect_activations(augmented_model_path, data_reader)
  28. ```
  29. `tensor_dict` points to a dictionary where the keys are tensor names and each value
  30. is a list of tensors, one from each model run
  31. """
  32. import logging
  33. import math
  34. import time
  35. from pathlib import Path
  36. from typing import Callable, Dict, List, Optional, Sequence, Union
  37. import numpy
  38. import onnx
  39. from onnx import ModelProto, TensorProto, helper, numpy_helper
  40. import onnxruntime
  41. from .calibrate import CalibraterBase, CalibrationDataReader
  42. from .onnx_model import ONNXModel
  43. from .quant_utils import (
  44. DEQUANT_OP_NAME,
  45. DEQUANT_OUTPUT_SUFFIX,
  46. QUANT_INPUT_SUFFIX,
  47. TENSOR_NAME_QUANT_SUFFIX,
  48. clone_model_with_shape_infer,
  49. find_by_name,
  50. load_model,
  51. )
  52. _TENSOR_SAVE_POSTFIX = "_ReshapedSavedOutput"
  53. _TENSOR_SAVE_POSTFIX_LEN = len(_TENSOR_SAVE_POSTFIX)
  54. def modify_model_output_intermediate_tensors(
  55. onnx_model: Union[str, Path, ModelProto], op_types_for_saving: Optional[Sequence[str]] = None
  56. ) -> ModelProto:
  57. """Augment a given ONNX model to save node input/output tensors.
  58. Add all input/output tensors of operator nodes to model outputs
  59. so that their values can be retrieved for debugging purposes.
  60. Args:
  61. model: An ONNX model or the path to load the model.
  62. op_types_for_saving: Operator types for which the
  63. input/output should be saved. By default, saving all the
  64. float32/float16 tensors.
  65. Returns:
  66. The augmented ONNX model
  67. """
  68. if op_types_for_saving is None:
  69. op_types_for_saving = []
  70. saver = CalibraterBase(onnx_model, op_types_to_calibrate=op_types_for_saving)
  71. model: ModelProto = clone_model_with_shape_infer(saver.model)
  72. tensors, _ = saver.select_tensors_to_calibrate(model)
  73. reshape_shape_name = "LinearReshape_" + str(time.time())
  74. reshape_shape = numpy_helper.from_array(numpy.array([-1], dtype=numpy.int64), reshape_shape_name)
  75. model.graph.initializer.append(reshape_shape)
  76. for tensor_name in tensors:
  77. reshape_output = tensor_name + _TENSOR_SAVE_POSTFIX
  78. reshape_node = onnx.helper.make_node(
  79. "Reshape",
  80. inputs=[tensor_name, reshape_shape_name],
  81. outputs=[reshape_output],
  82. name=reshape_output,
  83. )
  84. model.graph.node.append(reshape_node)
  85. reshape_output_value_info = helper.make_tensor_value_info(reshape_output, TensorProto.FLOAT, [-1])
  86. model.graph.output.append(reshape_output_value_info)
  87. return model
  88. def collect_activations(
  89. augmented_model: str,
  90. input_reader: CalibrationDataReader,
  91. session_options=None,
  92. execution_providers: Optional[Sequence[str]] = None,
  93. ) -> Dict[str, List[numpy.ndarray]]:
  94. """Run augmented model and collect activations tensors.
  95. Args:
  96. augmented_model: Path to augmented model created by modify_model_output_intermediate_tensors ()
  97. input_reader: Logic for reading input for the model, augmented model have the same
  98. input with the original model.
  99. session_options: Optional OnnxRuntime session options for controlling model run.
  100. By default graph optimization is turned off
  101. execution_providers: Collection of execution providers for running the model.
  102. Only CPU EP is used by default.
  103. Returns:
  104. A dictionary where the key is tensor name and values are list of tensors from each batch
  105. """
  106. if session_options is None:
  107. session_options = onnxruntime.SessionOptions()
  108. session_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
  109. if execution_providers is None:
  110. execution_providers = ["CPUExecutionProvider"]
  111. inference_session = onnxruntime.InferenceSession(
  112. augmented_model,
  113. sess_options=session_options,
  114. providers=execution_providers,
  115. )
  116. intermediate_outputs = []
  117. for input_d in input_reader:
  118. intermediate_outputs.append(inference_session.run(None, input_d))
  119. if not intermediate_outputs:
  120. raise RuntimeError("No data is collected while running augmented model!")
  121. output_dict = {}
  122. output_info = inference_session.get_outputs()
  123. for batch in intermediate_outputs:
  124. for output, output_data in zip(output_info, batch):
  125. if output.name.endswith(_TENSOR_SAVE_POSTFIX):
  126. output_name = output.name[:-_TENSOR_SAVE_POSTFIX_LEN]
  127. output_dict.setdefault(output_name, []).append(output_data)
  128. return output_dict
  129. _POST_QDQ_POSTFIX1 = DEQUANT_OUTPUT_SUFFIX + "_1"
  130. def _add_pre_post_qdq_pair(
  131. qdq_cmp: Dict[str, Dict[str, Sequence[numpy.ndarray]]],
  132. activation_name: str,
  133. pre_qdq_tensors: Optional[Sequence[numpy.ndarray]],
  134. post_qdq_tensors: Optional[Sequence[numpy.ndarray]],
  135. ) -> None:
  136. if post_qdq_tensors is not None and pre_qdq_tensors is not None:
  137. qdq_cmp[activation_name] = {}
  138. qdq_cmp[activation_name]["pre_qdq"] = pre_qdq_tensors
  139. qdq_cmp[activation_name]["post_qdq"] = post_qdq_tensors
  140. def create_activation_matching(
  141. qdq_activations: Dict[str, Sequence[numpy.ndarray]],
  142. float_activations: Optional[Dict[str, Sequence[numpy.ndarray]]] = None,
  143. ) -> Dict[str, Dict[str, Sequence[numpy.ndarray]]]:
  144. """Comparing activation values to help debugging accuracy loss due to quantization.
  145. This functions takes saved activations from the QDQ model and (optionally) the
  146. float point model, and provides a data structure for comparing:
  147. * from the qdq model, activation values before and after QDQ operation
  148. * across both models, activations from the orignal model vs the corresponding
  149. activations in the QDQ model
  150. Arg:
  151. qdq_activations: Output of `collect_activations`. This must be from a quantized
  152. model with QDQ format.
  153. float_activations: Output of `collect_activations`. This must be from the float
  154. point model.
  155. Returns:
  156. Dict for comparing pre and post quantized activation tensors. E.g.
  157. ```
  158. qdq_cmp = cmp_qdq_input_output(qdq_activations)
  159. print(qdq_cmp['activation1']['pre_qdq'][0])
  160. print(qdq_cmp['activation1'][`post_qdq'][0])
  161. qdq_cmp = cmp_qdq_input_output(qdq_activations, float_activations)
  162. print(qdq_cmp['activation1']['float'][0])
  163. print(qdq_cmp['activation1']['pre_qdq'][0])
  164. print(qdq_cmp['activation1'][`post_qdq'][0])
  165. ```
  166. """
  167. qdq_cmp: Dict[str, Dict[str, Sequence[numpy.ndarray]]] = {}
  168. for tensor_name, tensors in qdq_activations.items():
  169. if tensor_name.endswith(QUANT_INPUT_SUFFIX):
  170. pre_name = tensor_name[: -len(QUANT_INPUT_SUFFIX)]
  171. post_qdq_tensors = qdq_activations.get(pre_name)
  172. pre_qdq_tensors = tensors
  173. _add_pre_post_qdq_pair(qdq_cmp, pre_name, pre_qdq_tensors, post_qdq_tensors)
  174. elif tensor_name.endswith(DEQUANT_OUTPUT_SUFFIX):
  175. pre_name = tensor_name[: -len(DEQUANT_OUTPUT_SUFFIX)]
  176. pre_qdq_tensors = qdq_activations.get(pre_name)
  177. post_qdq_tensors = tensors
  178. _add_pre_post_qdq_pair(qdq_cmp, pre_name, pre_qdq_tensors, post_qdq_tensors)
  179. elif tensor_name.endswith(_POST_QDQ_POSTFIX1):
  180. pre_name = tensor_name[: -len(_POST_QDQ_POSTFIX1)]
  181. pre_qdq_tensors = qdq_activations.get(pre_name)
  182. post_qdq_tensors = tensors
  183. _add_pre_post_qdq_pair(qdq_cmp, pre_name, pre_qdq_tensors, post_qdq_tensors)
  184. if not float_activations:
  185. return qdq_cmp
  186. for act_name, act_values in qdq_cmp.items():
  187. float_acts = float_activations.get(act_name)
  188. if float_acts is not None:
  189. act_values["float"] = float_acts
  190. return qdq_cmp
  191. def _run_dequantize_linear(
  192. weight_tensor: numpy.ndarray, weight_scale: numpy.ndarray, weight_zp: numpy.ndarray, channel_axis: int
  193. ) -> Optional[numpy.ndarray]:
  194. assert weight_scale.shape == weight_zp.shape
  195. if weight_zp.size == 1:
  196. return (weight_tensor - weight_zp) * weight_scale
  197. assert weight_zp.ndim == 1
  198. reshape_dims = list(weight_tensor.shape) # deep copy
  199. reshape_dims[channel_axis] = 1 # only one per channel for reshape
  200. channel_count = weight_tensor.shape[channel_axis]
  201. dequantized_weights = None
  202. for i in range(channel_count):
  203. per_channel_data = weight_tensor.take(i, channel_axis)
  204. dequantized_per_channel_data = (per_channel_data - weight_zp[i]) * weight_scale[i]
  205. if i == 0:
  206. dequantized_weights = numpy.asarray(dequantized_per_channel_data).reshape(reshape_dims)
  207. else:
  208. channel_weights = numpy.asarray(dequantized_per_channel_data).reshape(reshape_dims)
  209. dequantized_weights = numpy.concatenate((dequantized_weights, channel_weights), channel_axis)
  210. if dequantized_weights is None:
  211. return None
  212. dequantized_weights.reshape(weight_tensor.shape)
  213. return dequantized_weights
  214. def create_weight_matching(float_model_path: str, qdq_model_path: str) -> Dict[str, Dict[str, numpy.ndarray]]:
  215. """Comparing weight values to help debugging accuracy loss due to quantization.
  216. This functions takes the float model and the qdq model, and provides a data structure for comparing
  217. their corresponding weights to locate quantization errors
  218. Arg:
  219. float_model_path: Path points to the float point model.
  220. qdq_model_path: Path points to the qdq model.
  221. Returns:
  222. Dict for comparing weight tensors. E.g.
  223. ```
  224. qdq_weight_cmp = create_weight_matching(float_model, qdq_model)
  225. print(qdq_weight_cmp['activation1']['float'])
  226. print(qdq_weight_cmp['activation1']['dequantized'])
  227. ```
  228. """
  229. float_onnx_model = ONNXModel(load_model(Path(float_model_path), need_optimize=False))
  230. qdq_onnx_model = ONNXModel(load_model(Path(qdq_model_path), need_optimize=False))
  231. matched_weights: Dict[str, Dict[str, numpy.ndarray]] = {}
  232. initializers = qdq_onnx_model.initializer()
  233. for node in qdq_onnx_model.nodes():
  234. if node.op_type != DEQUANT_OP_NAME:
  235. continue # Only care about DQ node
  236. weight_name: str = node.input[0]
  237. weight_values = find_by_name(weight_name, initializers)
  238. if not weight_values:
  239. continue # Only care about DQ node with const inputs
  240. if not weight_name.endswith(TENSOR_NAME_QUANT_SUFFIX):
  241. logging.error(f"Model Error in '{qdq_model_path}': Dequantized tensor name '{weight_name}' not recognized!")
  242. continue
  243. axis = -1
  244. for attr in node.attribute:
  245. if attr.name == "axis":
  246. axis = attr.i
  247. weight_tensor = numpy_helper.to_array(weight_values)
  248. weight_scale = numpy_helper.to_array(find_by_name(node.input[1], initializers))
  249. if len(node.input) > 2:
  250. weight_zp = numpy_helper.to_array(find_by_name(node.input[2], initializers))
  251. else:
  252. weight_zp = numpy.zeros(weight_scale.shape, dtype=numpy.int32)
  253. # Perform dequantization:
  254. weight_quant = _run_dequantize_linear(weight_tensor, weight_scale, weight_zp, channel_axis=axis)
  255. weight_name = weight_name[: -len(TENSOR_NAME_QUANT_SUFFIX)]
  256. if weight_quant is None:
  257. logging.error(f"Model Error in '{qdq_model_path}': '{weight_name}' per-channel quantization on 0 channel")
  258. continue
  259. float_values = find_by_name(weight_name, float_onnx_model.initializer())
  260. if not float_values:
  261. logging.error(f"Model Error in '{float_model_path}': weight tensor '{weight_name}' not found!")
  262. continue
  263. weight_float = numpy_helper.to_array(float_values)
  264. matched_weights[weight_name] = {"float": weight_float, "dequantized": weight_quant}
  265. return matched_weights
  266. def compute_signal_to_quantization_noice_ratio(
  267. x: Union[Sequence[numpy.ndarray], numpy.ndarray], y: Union[Sequence[numpy.ndarray], numpy.ndarray]
  268. ) -> float:
  269. if isinstance(x, numpy.ndarray):
  270. xlist = [x]
  271. else:
  272. xlist = x
  273. if isinstance(y, numpy.ndarray):
  274. ylist = [y]
  275. else:
  276. ylist = y
  277. if len(xlist) != len(ylist):
  278. raise RuntimeError("Unequal number of tensors to compare!")
  279. left = numpy.concatenate(xlist).flatten()
  280. right = numpy.concatenate(ylist).flatten()
  281. epsilon = numpy.finfo("float").eps
  282. tensor_norm = max(numpy.linalg.norm(left), epsilon)
  283. diff_norm = max(numpy.linalg.norm(left - right), epsilon)
  284. res = tensor_norm / diff_norm
  285. return 20 * math.log10(res)
  286. def compute_weight_error(
  287. weights_match: Dict[str, Dict[str, numpy.ndarray]],
  288. err_func: Callable[[numpy.ndarray, numpy.ndarray], float] = compute_signal_to_quantization_noice_ratio,
  289. ) -> Dict[str, float]:
  290. result: Dict[str, float] = {}
  291. for weight_name, weight_match in weights_match.items():
  292. result[weight_name] = err_func(weight_match["float"], weight_match["dequantized"])
  293. return result
  294. def compute_activation_error(
  295. activations_match: Dict[str, Dict[str, Sequence[numpy.ndarray]]],
  296. err_func: Callable[
  297. [Sequence[numpy.ndarray], Sequence[numpy.ndarray]], float
  298. ] = compute_signal_to_quantization_noice_ratio,
  299. ) -> Dict[str, Dict[str, float]]:
  300. result: Dict[str, Dict[str, float]] = {}
  301. for name, match in activations_match.items():
  302. err_result: Dict[str, float] = {}
  303. err_result["qdq_err"] = err_func(match["pre_qdq"], match["post_qdq"])
  304. float_activation = match["float"]
  305. if float_activation:
  306. err_result["xmodel_err"] = err_func(float_activation, match["post_qdq"])
  307. result[name] = err_result
  308. return result