onnxruntime-directml 1.20.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. onnxruntime/LICENSE +21 -0
  2. onnxruntime/Privacy.md +21 -0
  3. onnxruntime/ThirdPartyNotices.txt +6508 -0
  4. onnxruntime/__init__.py +78 -0
  5. onnxruntime/backend/__init__.py +6 -0
  6. onnxruntime/backend/backend.py +174 -0
  7. onnxruntime/backend/backend_rep.py +53 -0
  8. onnxruntime/capi/DirectML.dll +0 -0
  9. onnxruntime/capi/__init__.py +4 -0
  10. onnxruntime/capi/_ld_preload.py +7 -0
  11. onnxruntime/capi/_pybind_state.py +33 -0
  12. onnxruntime/capi/convert_npz_to_onnx_adapter.py +48 -0
  13. onnxruntime/capi/onnxruntime.dll +0 -0
  14. onnxruntime/capi/onnxruntime_collect_build_info.py +47 -0
  15. onnxruntime/capi/onnxruntime_inference_collection.py +1108 -0
  16. onnxruntime/capi/onnxruntime_providers_shared.dll +0 -0
  17. onnxruntime/capi/onnxruntime_pybind11_state.pyd +0 -0
  18. onnxruntime/capi/onnxruntime_validation.py +150 -0
  19. onnxruntime/capi/version_info.py +2 -0
  20. onnxruntime/datasets/__init__.py +17 -0
  21. onnxruntime/datasets/logreg_iris.onnx +0 -0
  22. onnxruntime/datasets/mul_1.onnx +0 -0
  23. onnxruntime/datasets/sigmoid.onnx +13 -0
  24. onnxruntime/quantization/CalTableFlatBuffers/KeyValue.py +78 -0
  25. onnxruntime/quantization/CalTableFlatBuffers/TrtTable.py +90 -0
  26. onnxruntime/quantization/CalTableFlatBuffers/__init__.py +0 -0
  27. onnxruntime/quantization/__init__.py +16 -0
  28. onnxruntime/quantization/base_quantizer.py +532 -0
  29. onnxruntime/quantization/calibrate.py +1245 -0
  30. onnxruntime/quantization/execution_providers/qnn/__init__.py +2 -0
  31. onnxruntime/quantization/execution_providers/qnn/fusion_lpnorm.py +132 -0
  32. onnxruntime/quantization/execution_providers/qnn/mixed_precision_overrides_utils.py +413 -0
  33. onnxruntime/quantization/execution_providers/qnn/preprocess.py +307 -0
  34. onnxruntime/quantization/execution_providers/qnn/quant_config.py +387 -0
  35. onnxruntime/quantization/fusions/__init__.py +3 -0
  36. onnxruntime/quantization/fusions/fusion.py +311 -0
  37. onnxruntime/quantization/fusions/fusion_gelu.py +272 -0
  38. onnxruntime/quantization/fusions/fusion_layernorm.py +135 -0
  39. onnxruntime/quantization/matmul_4bits_quantizer.py +1480 -0
  40. onnxruntime/quantization/matmul_bnb4_quantizer.py +240 -0
  41. onnxruntime/quantization/onnx_model.py +580 -0
  42. onnxruntime/quantization/onnx_quantizer.py +1008 -0
  43. onnxruntime/quantization/operators/__init__.py +2 -0
  44. onnxruntime/quantization/operators/activation.py +119 -0
  45. onnxruntime/quantization/operators/argmax.py +18 -0
  46. onnxruntime/quantization/operators/attention.py +73 -0
  47. onnxruntime/quantization/operators/base_operator.py +26 -0
  48. onnxruntime/quantization/operators/binary_op.py +72 -0
  49. onnxruntime/quantization/operators/concat.py +62 -0
  50. onnxruntime/quantization/operators/conv.py +258 -0
  51. onnxruntime/quantization/operators/direct_q8.py +78 -0
  52. onnxruntime/quantization/operators/embed_layernorm.py +121 -0
  53. onnxruntime/quantization/operators/gather.py +64 -0
  54. onnxruntime/quantization/operators/gavgpool.py +62 -0
  55. onnxruntime/quantization/operators/gemm.py +166 -0
  56. onnxruntime/quantization/operators/lstm.py +117 -0
  57. onnxruntime/quantization/operators/matmul.py +231 -0
  58. onnxruntime/quantization/operators/maxpool.py +34 -0
  59. onnxruntime/quantization/operators/norm.py +40 -0
  60. onnxruntime/quantization/operators/pad.py +100 -0
  61. onnxruntime/quantization/operators/pooling.py +67 -0
  62. onnxruntime/quantization/operators/qdq_base_operator.py +22 -0
  63. onnxruntime/quantization/operators/resize.py +34 -0
  64. onnxruntime/quantization/operators/softmax.py +74 -0
  65. onnxruntime/quantization/operators/split.py +63 -0
  66. onnxruntime/quantization/operators/where.py +87 -0
  67. onnxruntime/quantization/preprocess.py +141 -0
  68. onnxruntime/quantization/qdq_loss_debug.py +389 -0
  69. onnxruntime/quantization/qdq_quantizer.py +1187 -0
  70. onnxruntime/quantization/quant_utils.py +891 -0
  71. onnxruntime/quantization/quantize.py +748 -0
  72. onnxruntime/quantization/registry.py +106 -0
  73. onnxruntime/quantization/shape_inference.py +187 -0
  74. onnxruntime/quantization/tensor_quant_overrides.py +516 -0
  75. onnxruntime/tools/__init__.py +10 -0
  76. onnxruntime/tools/check_onnx_model_mobile_usability.py +47 -0
  77. onnxruntime/tools/convert_onnx_models_to_ort.py +377 -0
  78. onnxruntime/tools/file_utils.py +46 -0
  79. onnxruntime/tools/logger.py +11 -0
  80. onnxruntime/tools/make_dynamic_shape_fixed.py +72 -0
  81. onnxruntime/tools/mobile_helpers/__init__.py +0 -0
  82. onnxruntime/tools/mobile_helpers/coreml_supported_mlprogram_ops.md +33 -0
  83. onnxruntime/tools/mobile_helpers/coreml_supported_neuralnetwork_ops.md +43 -0
  84. onnxruntime/tools/mobile_helpers/nnapi_supported_ops.md +58 -0
  85. onnxruntime/tools/mobile_helpers/usability_checker.py +739 -0
  86. onnxruntime/tools/offline_tuning.py +169 -0
  87. onnxruntime/tools/onnx_model_utils.py +413 -0
  88. onnxruntime/tools/onnx_randomizer.py +85 -0
  89. onnxruntime/tools/onnxruntime_test.py +164 -0
  90. onnxruntime/tools/optimize_onnx_model.py +55 -0
  91. onnxruntime/tools/ort_format_model/__init__.py +25 -0
  92. onnxruntime/tools/ort_format_model/operator_type_usage_processors.py +663 -0
  93. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/__init__.py +0 -0
  94. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgType.py +7 -0
  95. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ArgTypeAndIndex.py +67 -0
  96. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Attribute.py +337 -0
  97. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/AttributeType.py +18 -0
  98. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Checkpoint.py +125 -0
  99. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedKernelCreateInfos.py +120 -0
  100. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py +68 -0
  101. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSessionState.py +96 -0
  102. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DeprecatedSubGraphSessionState.py +72 -0
  103. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Dimension.py +71 -0
  104. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValue.py +80 -0
  105. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/DimensionValueType.py +8 -0
  106. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/EdgeEnd.py +32 -0
  107. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/FloatProperty.py +67 -0
  108. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Graph.py +320 -0
  109. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/InferenceSession.py +88 -0
  110. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/IntProperty.py +67 -0
  111. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrArgsEntry.py +91 -0
  112. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/KernelTypeStrResolver.py +78 -0
  113. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/MapType.py +71 -0
  114. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Model.py +223 -0
  115. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ModuleState.py +141 -0
  116. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Node.py +317 -0
  117. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeEdge.py +126 -0
  118. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodeType.py +7 -0
  119. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/NodesToOptimizeIndices.py +160 -0
  120. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OpIdKernelTypeStrArgsEntry.py +91 -0
  121. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OperatorSetId.py +67 -0
  122. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/OptimizerGroup.py +117 -0
  123. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ParameterOptimizerState.py +91 -0
  124. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/PropertyBag.py +152 -0
  125. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecord.py +105 -0
  126. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizationRecordContainerEntry.py +91 -0
  127. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/RuntimeOptimizations.py +79 -0
  128. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SequenceType.py +58 -0
  129. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Shape.py +78 -0
  130. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/SparseTensor.py +114 -0
  131. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringProperty.py +67 -0
  132. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/StringStringEntry.py +67 -0
  133. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/Tensor.py +203 -0
  134. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorDataType.py +26 -0
  135. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TensorTypeAndShape.py +71 -0
  136. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfo.py +83 -0
  137. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/TypeInfoValue.py +9 -0
  138. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/ValueInfo.py +84 -0
  139. onnxruntime/tools/ort_format_model/ort_flatbuffers_py/fbs/__init__.py +6 -0
  140. onnxruntime/tools/ort_format_model/ort_model_processor.py +86 -0
  141. onnxruntime/tools/ort_format_model/types.py +84 -0
  142. onnxruntime/tools/ort_format_model/utils.py +62 -0
  143. onnxruntime/tools/pytorch_export_contrib_ops.py +108 -0
  144. onnxruntime/tools/pytorch_export_helpers.py +131 -0
  145. onnxruntime/tools/qdq_helpers/__init__.py +0 -0
  146. onnxruntime/tools/qdq_helpers/optimize_qdq_model.py +37 -0
  147. onnxruntime/tools/reduced_build_config_parser.py +202 -0
  148. onnxruntime/tools/symbolic_shape_infer.py +3016 -0
  149. onnxruntime/tools/update_onnx_opset.py +31 -0
  150. onnxruntime/transformers/__init__.py +8 -0
  151. onnxruntime/transformers/affinity_helper.py +40 -0
  152. onnxruntime/transformers/benchmark.py +944 -0
  153. onnxruntime/transformers/benchmark_helper.py +646 -0
  154. onnxruntime/transformers/bert_perf_test.py +634 -0
  155. onnxruntime/transformers/bert_test_data.py +642 -0
  156. onnxruntime/transformers/compare_bert_results.py +246 -0
  157. onnxruntime/transformers/constants.py +47 -0
  158. onnxruntime/transformers/convert_generation.py +3124 -0
  159. onnxruntime/transformers/convert_tf_models_to_pytorch.py +205 -0
  160. onnxruntime/transformers/convert_to_packing_mode.py +387 -0
  161. onnxruntime/transformers/dynamo_onnx_helper.py +104 -0
  162. onnxruntime/transformers/float16.py +501 -0
  163. onnxruntime/transformers/fusion_attention.py +1235 -0
  164. onnxruntime/transformers/fusion_attention_clip.py +257 -0
  165. onnxruntime/transformers/fusion_attention_sam2.py +534 -0
  166. onnxruntime/transformers/fusion_attention_unet.py +1304 -0
  167. onnxruntime/transformers/fusion_attention_vae.py +301 -0
  168. onnxruntime/transformers/fusion_bart_attention.py +640 -0
  169. onnxruntime/transformers/fusion_base.py +137 -0
  170. onnxruntime/transformers/fusion_bias_add.py +58 -0
  171. onnxruntime/transformers/fusion_biasgelu.py +66 -0
  172. onnxruntime/transformers/fusion_biassplitgelu.py +111 -0
  173. onnxruntime/transformers/fusion_conformer_attention.py +143 -0
  174. onnxruntime/transformers/fusion_embedlayer.py +811 -0
  175. onnxruntime/transformers/fusion_fastgelu.py +360 -0
  176. onnxruntime/transformers/fusion_gelu.py +259 -0
  177. onnxruntime/transformers/fusion_gelu_approximation.py +25 -0
  178. onnxruntime/transformers/fusion_gemmfastgelu.py +122 -0
  179. onnxruntime/transformers/fusion_gpt_attention.py +546 -0
  180. onnxruntime/transformers/fusion_gpt_attention_megatron.py +355 -0
  181. onnxruntime/transformers/fusion_gpt_attention_no_past.py +260 -0
  182. onnxruntime/transformers/fusion_group_norm.py +179 -0
  183. onnxruntime/transformers/fusion_layernorm.py +465 -0
  184. onnxruntime/transformers/fusion_nhwc_conv.py +100 -0
  185. onnxruntime/transformers/fusion_options.py +340 -0
  186. onnxruntime/transformers/fusion_qordered_attention.py +421 -0
  187. onnxruntime/transformers/fusion_qordered_gelu.py +119 -0
  188. onnxruntime/transformers/fusion_qordered_layernorm.py +123 -0
  189. onnxruntime/transformers/fusion_qordered_matmul.py +217 -0
  190. onnxruntime/transformers/fusion_quickgelu.py +74 -0
  191. onnxruntime/transformers/fusion_reshape.py +173 -0
  192. onnxruntime/transformers/fusion_rotary_attention.py +1592 -0
  193. onnxruntime/transformers/fusion_shape.py +110 -0
  194. onnxruntime/transformers/fusion_simplified_layernorm.py +159 -0
  195. onnxruntime/transformers/fusion_skip_group_norm.py +255 -0
  196. onnxruntime/transformers/fusion_skiplayernorm.py +209 -0
  197. onnxruntime/transformers/fusion_transpose.py +168 -0
  198. onnxruntime/transformers/fusion_utils.py +307 -0
  199. onnxruntime/transformers/huggingface_models.py +167 -0
  200. onnxruntime/transformers/import_utils.py +20 -0
  201. onnxruntime/transformers/io_binding_helper.py +442 -0
  202. onnxruntime/transformers/large_model_exporter.py +395 -0
  203. onnxruntime/transformers/machine_info.py +221 -0
  204. onnxruntime/transformers/metrics.py +164 -0
  205. onnxruntime/transformers/models/bart/__init__.py +12 -0
  206. onnxruntime/transformers/models/bart/export.py +98 -0
  207. onnxruntime/transformers/models/bert/__init__.py +12 -0
  208. onnxruntime/transformers/models/bert/eval_squad.py +329 -0
  209. onnxruntime/transformers/models/gpt2/__init__.py +12 -0
  210. onnxruntime/transformers/models/gpt2/benchmark_gpt2.py +413 -0
  211. onnxruntime/transformers/models/gpt2/convert_to_onnx.py +561 -0
  212. onnxruntime/transformers/models/gpt2/gpt2_helper.py +1032 -0
  213. onnxruntime/transformers/models/gpt2/gpt2_parity.py +513 -0
  214. onnxruntime/transformers/models/gpt2/gpt2_tester.py +501 -0
  215. onnxruntime/transformers/models/gpt2/parity_check_helper.py +146 -0
  216. onnxruntime/transformers/models/llama/__init__.py +12 -0
  217. onnxruntime/transformers/models/llama/benchmark.py +703 -0
  218. onnxruntime/transformers/models/llama/benchmark_all.py +488 -0
  219. onnxruntime/transformers/models/llama/benchmark_e2e.py +606 -0
  220. onnxruntime/transformers/models/llama/convert_to_onnx.py +1027 -0
  221. onnxruntime/transformers/models/llama/dist_settings.py +57 -0
  222. onnxruntime/transformers/models/llama/llama_inputs.py +503 -0
  223. onnxruntime/transformers/models/llama/llama_parity.py +309 -0
  224. onnxruntime/transformers/models/llama/llama_torch.py +47 -0
  225. onnxruntime/transformers/models/llama/quant_kv_dataloader.py +108 -0
  226. onnxruntime/transformers/models/longformer/__init__.py +12 -0
  227. onnxruntime/transformers/models/longformer/benchmark_longformer.py +821 -0
  228. onnxruntime/transformers/models/longformer/convert_to_onnx.py +413 -0
  229. onnxruntime/transformers/models/longformer/generate_test_data.py +347 -0
  230. onnxruntime/transformers/models/longformer/longformer_helper.py +77 -0
  231. onnxruntime/transformers/models/phi2/__init__.py +12 -0
  232. onnxruntime/transformers/models/phi2/convert_to_onnx.py +576 -0
  233. onnxruntime/transformers/models/phi2/inference_example.py +414 -0
  234. onnxruntime/transformers/models/sam2/__init__.py +12 -0
  235. onnxruntime/transformers/models/sam2/benchmark_sam2.py +625 -0
  236. onnxruntime/transformers/models/sam2/convert_to_onnx.py +260 -0
  237. onnxruntime/transformers/models/sam2/image_decoder.py +273 -0
  238. onnxruntime/transformers/models/sam2/image_encoder.py +186 -0
  239. onnxruntime/transformers/models/sam2/mask_decoder.py +208 -0
  240. onnxruntime/transformers/models/sam2/nvtx_helper.py +33 -0
  241. onnxruntime/transformers/models/sam2/prompt_encoder.py +189 -0
  242. onnxruntime/transformers/models/sam2/sam2_demo.py +322 -0
  243. onnxruntime/transformers/models/sam2/sam2_image_onnx_predictor.py +280 -0
  244. onnxruntime/transformers/models/sam2/sam2_utils.py +147 -0
  245. onnxruntime/transformers/models/stable_diffusion/__init__.py +12 -0
  246. onnxruntime/transformers/models/stable_diffusion/benchmark.py +1429 -0
  247. onnxruntime/transformers/models/stable_diffusion/benchmark_controlnet.py +426 -0
  248. onnxruntime/transformers/models/stable_diffusion/demo_txt2img.py +102 -0
  249. onnxruntime/transformers/models/stable_diffusion/demo_txt2img_xl.py +268 -0
  250. onnxruntime/transformers/models/stable_diffusion/demo_utils.py +778 -0
  251. onnxruntime/transformers/models/stable_diffusion/diffusion_models.py +1319 -0
  252. onnxruntime/transformers/models/stable_diffusion/diffusion_schedulers.py +1181 -0
  253. onnxruntime/transformers/models/stable_diffusion/engine_builder.py +296 -0
  254. onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_cuda.py +388 -0
  255. onnxruntime/transformers/models/stable_diffusion/engine_builder_ort_trt.py +288 -0
  256. onnxruntime/transformers/models/stable_diffusion/engine_builder_tensorrt.py +395 -0
  257. onnxruntime/transformers/models/stable_diffusion/engine_builder_torch.py +108 -0
  258. onnxruntime/transformers/models/stable_diffusion/optimize_pipeline.py +350 -0
  259. onnxruntime/transformers/models/stable_diffusion/ort_optimizer.py +136 -0
  260. onnxruntime/transformers/models/stable_diffusion/pipeline_stable_diffusion.py +831 -0
  261. onnxruntime/transformers/models/stable_diffusion/trt_utilities.py +12 -0
  262. onnxruntime/transformers/models/t5/__init__.py +12 -0
  263. onnxruntime/transformers/models/t5/convert_to_onnx.py +278 -0
  264. onnxruntime/transformers/models/t5/past_helper.py +150 -0
  265. onnxruntime/transformers/models/t5/t5_decoder.py +438 -0
  266. onnxruntime/transformers/models/t5/t5_encoder.py +171 -0
  267. onnxruntime/transformers/models/t5/t5_encoder_decoder_init.py +299 -0
  268. onnxruntime/transformers/models/t5/t5_helper.py +272 -0
  269. onnxruntime/transformers/models/whisper/__init__.py +12 -0
  270. onnxruntime/transformers/models/whisper/benchmark.py +610 -0
  271. onnxruntime/transformers/models/whisper/benchmark_all.py +528 -0
  272. onnxruntime/transformers/models/whisper/convert_to_onnx.py +536 -0
  273. onnxruntime/transformers/models/whisper/whisper_chain.py +329 -0
  274. onnxruntime/transformers/models/whisper/whisper_decoder.py +402 -0
  275. onnxruntime/transformers/models/whisper/whisper_encoder.py +164 -0
  276. onnxruntime/transformers/models/whisper/whisper_encoder_decoder_init.py +306 -0
  277. onnxruntime/transformers/models/whisper/whisper_helper.py +524 -0
  278. onnxruntime/transformers/models/whisper/whisper_openai_helper.py +84 -0
  279. onnxruntime/transformers/onnx_exporter.py +717 -0
  280. onnxruntime/transformers/onnx_model.py +1569 -0
  281. onnxruntime/transformers/onnx_model_bart.py +142 -0
  282. onnxruntime/transformers/onnx_model_bert.py +481 -0
  283. onnxruntime/transformers/onnx_model_bert_keras.py +475 -0
  284. onnxruntime/transformers/onnx_model_bert_tf.py +589 -0
  285. onnxruntime/transformers/onnx_model_clip.py +40 -0
  286. onnxruntime/transformers/onnx_model_conformer.py +33 -0
  287. onnxruntime/transformers/onnx_model_gpt2.py +101 -0
  288. onnxruntime/transformers/onnx_model_phi.py +930 -0
  289. onnxruntime/transformers/onnx_model_sam2.py +138 -0
  290. onnxruntime/transformers/onnx_model_t5.py +791 -0
  291. onnxruntime/transformers/onnx_model_tnlr.py +227 -0
  292. onnxruntime/transformers/onnx_model_unet.py +259 -0
  293. onnxruntime/transformers/onnx_model_vae.py +43 -0
  294. onnxruntime/transformers/onnx_utils.py +55 -0
  295. onnxruntime/transformers/optimizer.py +612 -0
  296. onnxruntime/transformers/profiler.py +725 -0
  297. onnxruntime/transformers/quantize_helper.py +76 -0
  298. onnxruntime/transformers/shape_infer_helper.py +122 -0
  299. onnxruntime/transformers/shape_optimizer.py +401 -0
  300. onnxruntime/transformers/torch_onnx_export_helper.py +74 -0
  301. onnxruntime_directml-1.20.0.dist-info/METADATA +187 -0
  302. onnxruntime_directml-1.20.0.dist-info/RECORD +305 -0
  303. onnxruntime_directml-1.20.0.dist-info/WHEEL +5 -0
  304. onnxruntime_directml-1.20.0.dist-info/entry_points.txt +2 -0
  305. onnxruntime_directml-1.20.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1245 @@
1
+ #!/usr/bin/env python
2
+ # -------------------------------------------------------------------------
3
+ # Copyright (c) Microsoft, Intel Corporation. All rights reserved.
4
+ # Licensed under the MIT License. See License.txt in the project root for
5
+ # license information.
6
+ # --------------------------------------------------------------------------
7
+ import abc
8
+ import copy
9
+ import itertools
10
+ import os
11
+ import uuid
12
+ from enum import Enum
13
+ from pathlib import Path
14
+ from typing import Dict, Optional, Sequence, Tuple, Union
15
+
16
+ import numpy as np
17
+ import onnx
18
+ from onnx import ModelProto, TensorProto, helper, numpy_helper
19
+
20
+ import onnxruntime
21
+
22
+ from .quant_utils import apply_plot, load_model_with_shape_infer, smooth_distribution
23
+
24
+
25
+ def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray:
26
+ """
27
+ See https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.rel_entr.html#scipy.special.rel_entr.
28
+ Python implementation.
29
+ """
30
+ res = np.empty(pk.shape, dtype=pk.dtype)
31
+ res[:] = pk[:] * np.log(pk[:] / qk[:])
32
+ c2 = (pk == 0) & (qk >= 0)
33
+ res[c2] = 0
34
+ c1 = (pk > 0) & (qk > 0)
35
+ res[~c1] = np.inf
36
+ return res
37
+
38
+
39
+ def entropy(
40
+ pk: np.ndarray,
41
+ qk: np.ndarray,
42
+ base: Optional[float] = None,
43
+ axis: int = 0,
44
+ ) -> np.ndarray:
45
+ """
46
+ Simplifeied version of entropy.
47
+ Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html.
48
+ This avoids taking a dependency on scipy just for this function.
49
+ """
50
+ assert base is None or base > 0, "base={base} must be a positive number or `None`."
51
+ assert qk is not None, "qk is None"
52
+
53
+ pk = np.asarray(pk).astype(np.float32)
54
+ pk = 1.0 * pk / np.sum(pk, axis=axis, keepdims=True)
55
+
56
+ qk = np.asarray(qk).astype(np.float32)
57
+ pk, qk = np.broadcast_arrays(pk, qk)
58
+ qk = 1.0 * qk / np.sum(qk, axis=axis, keepdims=True)
59
+ vec = rel_entr(pk, qk)
60
+
61
+ s = np.sum(vec, axis=axis)
62
+ if base is not None:
63
+ s /= np.log(base)
64
+ return s.astype(pk.dtype)
65
+
66
+
67
+ class TensorData:
68
+ _allowed = frozenset(["avg", "std", "lowest", "highest", "hist", "hist_edges", "bins"])
69
+ _floats = frozenset(["avg", "std", "lowest", "highest", "hist_edges"])
70
+
71
+ def __init__(self, **kwargs):
72
+ self._attrs = list(kwargs.keys())
73
+ for k, v in kwargs.items():
74
+ if k not in TensorData._allowed:
75
+ raise ValueError(f"Unexpected value {k!r} not in {TensorData._allowed}.")
76
+ if k in TensorData._floats:
77
+ if not hasattr(v, "dtype"):
78
+ raise ValueError(f"Unexpected type {type(v)} for k={k!r}")
79
+ if v.dtype not in (np.float16, np.float32):
80
+ raise ValueError(f"Unexpected dtype {v.dtype} for k={k!r}")
81
+ setattr(self, k, v)
82
+
83
+ @property
84
+ def range_value(self):
85
+ if not hasattr(self, "lowest") or not hasattr(self, "highest"):
86
+ raise AttributeError(f"Attributes 'lowest' and/or 'highest' missing in {dir(self)}.")
87
+ return (self.lowest, self.highest)
88
+
89
+ @property
90
+ def avg_std(self):
91
+ if not hasattr(self, "avg") or not hasattr(self, "std"):
92
+ raise AttributeError(f"Attributes 'avg' and/or 'std' missing in {dir(self)}.")
93
+ return (self.avg, self.std)
94
+
95
+ def to_dict(self):
96
+ # This is needed to serialize the data into JSON.
97
+ data = {k: getattr(self, k) for k in self._attrs}
98
+ data["CLS"] = self.__class__.__name__
99
+ return data
100
+
101
+
102
+ class TensorsData:
103
+ def __init__(self, calibration_method, data: Dict[str, Union[TensorData, Tuple]]):
104
+ self.calibration_method = calibration_method
105
+ self.data = {}
106
+ for k, v in data.items():
107
+ if not isinstance(k, str):
108
+ raise TypeError(f"Keys must be strings not {type(k)}.")
109
+ if isinstance(v, tuple):
110
+ if calibration_method == CalibrationMethod.MinMax and len(v) == 2:
111
+ self.data[k] = TensorData(lowest=v[0], highest=v[1])
112
+ continue
113
+ if len(v) == 4:
114
+ self.data[k] = TensorData(lowest=v[0], highest=v[1], hist=v[2], bins=v[3])
115
+ continue
116
+ raise TypeError(f"Unexpected tuple for {k:r}, it has {len(v)} elements: {v}.")
117
+ if not isinstance(v, TensorData):
118
+ raise TypeError(f"Values must be TensorData not {type(v)}.")
119
+ self.data[k] = v
120
+
121
+ def __iter__(self):
122
+ yield from self.data
123
+
124
+ def __contains__(self, key):
125
+ return key in self.data
126
+
127
+ def __getitem__(self, key):
128
+ return self.data[key]
129
+
130
+ def __setitem__(self, key, value):
131
+ if key not in self.data:
132
+ raise RuntimeError(f"Only an existing tensor can be modified, {key!r} is not.")
133
+ self.data[key] = value
134
+
135
+ def keys(self):
136
+ return self.data.keys()
137
+
138
+ def values(self):
139
+ return self.data.values()
140
+
141
+ def items(self):
142
+ return self.data.items()
143
+
144
+ def to_dict(self):
145
+ # This is needed to serialize the data into JSON.
146
+ data = {
147
+ "CLS": self.__class__.__name__,
148
+ "data": self.data,
149
+ "calibration_method": self.calibration_method,
150
+ }
151
+ return data
152
+
153
+
154
+ class CalibrationMethod(Enum):
155
+ MinMax = 0
156
+ Entropy = 1
157
+ Percentile = 2
158
+ Distribution = 3
159
+
160
+
161
+ class CalibrationDataReader(metaclass=abc.ABCMeta):
162
+ @classmethod
163
+ def __subclasshook__(cls, subclass):
164
+ return hasattr(subclass, "get_next") and callable(subclass.get_next) or NotImplemented
165
+
166
+ @abc.abstractmethod
167
+ def get_next(self) -> dict:
168
+ """generate the input data dict for ONNXinferenceSession run"""
169
+ raise NotImplementedError
170
+
171
+ def __iter__(self):
172
+ return self
173
+
174
+ def __next__(self):
175
+ result = self.get_next()
176
+ if result is None:
177
+ raise StopIteration
178
+ return result
179
+
180
+ def __len__(self):
181
+ raise NotImplementedError
182
+
183
+ def set_range(self, start_index: int, end_index: int):
184
+ raise NotImplementedError
185
+
186
+
187
+ class CalibraterBase:
188
+ def __init__(
189
+ self,
190
+ model_path: Union[str, Path],
191
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
192
+ augmented_model_path="augmented_model.onnx",
193
+ symmetric=False,
194
+ use_external_data_format=False,
195
+ per_channel=False,
196
+ ):
197
+ """
198
+ :param model_path: ONNX model to calibrate. It should be a model file path
199
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
200
+ :param augmented_model_path: save augmented model to this path.
201
+ :param symmetric: make range of tensor symmetric (central point is 0).
202
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb.
203
+ :param per_channel: whether to compute ranges per each channel.
204
+ """
205
+ if isinstance(model_path, str):
206
+ self.model = load_model_with_shape_infer(Path(model_path))
207
+ elif isinstance(model_path, Path):
208
+ self.model = load_model_with_shape_infer(model_path)
209
+ else:
210
+ raise ValueError("model_path should be model path.")
211
+
212
+ self.op_types_to_calibrate = op_types_to_calibrate
213
+ self.augmented_model_path = augmented_model_path
214
+ self.symmetric = symmetric
215
+ self.use_external_data_format = use_external_data_format
216
+ self.per_channel = per_channel
217
+
218
+ self.augment_model = None
219
+ self.infer_session = None
220
+ self.execution_providers = ["CPUExecutionProvider"]
221
+
222
+ def set_execution_providers(self, execution_providers=["CPUExecutionProvider"]): # noqa: B006
223
+ """
224
+ reset the execution providers to execute the collect_data. It triggers to re-creating inference session.
225
+ """
226
+ self.execution_providers = execution_providers
227
+ self.create_inference_session()
228
+
229
+ def create_inference_session(self):
230
+ """
231
+ create an OnnxRuntime InferenceSession.
232
+ """
233
+ sess_options = onnxruntime.SessionOptions()
234
+ sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
235
+ self.infer_session = onnxruntime.InferenceSession(
236
+ self.augmented_model_path,
237
+ sess_options=sess_options,
238
+ providers=self.execution_providers,
239
+ )
240
+
241
+ def select_tensors_to_calibrate(self, model: ModelProto):
242
+ """
243
+ select input/output tensors of candidate nodes to calibrate.
244
+ returns:
245
+ tensors (set): set of tensor name.
246
+ value_infos (dict): tensor name to value info.
247
+ """
248
+ value_infos = {vi.name: vi for vi in model.graph.value_info}
249
+ value_infos.update({ot.name: ot for ot in model.graph.output})
250
+ value_infos.update({it.name: it for it in model.graph.input})
251
+ initializer = {init.name for init in model.graph.initializer}
252
+
253
+ tensors_to_calibrate = set()
254
+ tensor_type_to_calibrate = {TensorProto.FLOAT, TensorProto.FLOAT16}
255
+
256
+ for node in model.graph.node:
257
+ if not self.op_types_to_calibrate or node.op_type in self.op_types_to_calibrate:
258
+ for tensor_name in itertools.chain(node.input, node.output):
259
+ if tensor_name in value_infos:
260
+ vi = value_infos[tensor_name]
261
+ if (
262
+ vi.type.HasField("tensor_type")
263
+ and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate)
264
+ and (tensor_name not in initializer)
265
+ ):
266
+ tensors_to_calibrate.add(tensor_name)
267
+
268
+ return tensors_to_calibrate, value_infos
269
+
270
+ def get_augment_model(self):
271
+ """
272
+ return: augmented onnx model. Call after calling augment_graph
273
+ """
274
+ return self.model
275
+
276
+ def augment_graph(self):
277
+ """
278
+ abstract method: augment the input model to prepare for collecting data. It will:
279
+ 1. augment the model to be able to collect desired statistics data
280
+ 2. save augmented model to augmented_model_paths
281
+ """
282
+ raise NotImplementedError
283
+
284
+ def collect_data(self, data_reader: CalibrationDataReader):
285
+ """
286
+ abstract method: collect the tensors that will be used for range computation. It can be called multiple times.
287
+ """
288
+ raise NotImplementedError
289
+
290
+ def compute_data(self) -> TensorsData:
291
+ """
292
+ abstract method: compute data based on the calibration method stored in TensorsData
293
+ """
294
+ raise NotImplementedError
295
+
296
+
297
+ class MinMaxCalibrater(CalibraterBase):
298
+ def __init__(
299
+ self,
300
+ model_path: Union[str, Path],
301
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
302
+ augmented_model_path="augmented_model.onnx",
303
+ symmetric=False,
304
+ use_external_data_format=False,
305
+ moving_average=False,
306
+ averaging_constant=0.01,
307
+ max_intermediate_outputs=None,
308
+ per_channel=False,
309
+ ):
310
+ """
311
+ :param model_path: ONNX model to calibrate. It is a model path
312
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
313
+ :param augmented_model_path: save augmented model to this path.
314
+ :param symmetric: make range of tensor symmetric (central point is 0).
315
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
316
+ :param moving_average: compute the moving average of the minimum and maximum values instead of the global minimum and maximum.
317
+ :param averaging_constant: constant smoothing factor to use when computing the moving average.
318
+ :param max_intermediate_outputs: maximum number of intermediate outputs before an intermediate range is computed.
319
+ :param per_channel: whether to compute ranges per each channel.
320
+ """
321
+ super().__init__(
322
+ model_path,
323
+ op_types_to_calibrate=op_types_to_calibrate,
324
+ augmented_model_path=augmented_model_path,
325
+ symmetric=symmetric,
326
+ use_external_data_format=use_external_data_format,
327
+ per_channel=per_channel,
328
+ )
329
+ self.intermediate_outputs = []
330
+ self.calibrate_tensors_range = None
331
+ self.num_model_outputs = len(self.model.graph.output)
332
+ self.model_original_outputs = {output.name for output in self.model.graph.output}
333
+ self.moving_average = moving_average
334
+ if moving_average and (averaging_constant < 0 or averaging_constant > 1):
335
+ raise ValueError("Invalid averaging constant, which should not be < 0 or > 1.")
336
+ self.averaging_constant = averaging_constant
337
+ self.max_intermediate_outputs = max_intermediate_outputs
338
+
339
+ def augment_graph(self):
340
+ """
341
+ Adds ReduceMin and ReduceMax nodes to all quantization_candidates op type nodes in
342
+ model and ensures their outputs are stored as part of the graph output
343
+ :return: augmented ONNX model
344
+ """
345
+ tensors, _ = self.select_tensors_to_calibrate(self.model)
346
+ reshape_shape_name = str(uuid.uuid4())
347
+ reshape_shape = numpy_helper.from_array(np.array([-1], dtype=np.int64), reshape_shape_name)
348
+ self.model.graph.initializer.append(reshape_shape)
349
+
350
+ def get_op_version(op_type, model):
351
+ for opset_import in model.opset_import:
352
+ if onnx.defs.has(op_type, opset_import.domain):
353
+ return opset_import.version
354
+ raise RuntimeError(f"Model does not contain a version for '{op_type}'.")
355
+
356
+ def add_reduce_min_max(tensor_name, reduce_op_name):
357
+ # When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false.
358
+ # To make the code simple, we always let keepdims to be 1.
359
+ keepdims = 1
360
+
361
+ # Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output)
362
+ reduce_output = tensor_name + "_" + reduce_op_name
363
+ intermediate_output = reduce_output + "_Reshape"
364
+ reduce_node = onnx.helper.make_node(
365
+ reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output
366
+ )
367
+
368
+ reshape_node = onnx.helper.make_node(
369
+ "Reshape",
370
+ inputs=[intermediate_output, reshape_shape_name],
371
+ outputs=[reduce_output],
372
+ name=intermediate_output,
373
+ )
374
+
375
+ value_infos = {vi.name: vi for vi in self.model.graph.value_info}
376
+ value_infos.update({o.name: o for o in self.model.graph.output})
377
+ value_infos.update({i.name: i for i in self.model.graph.input})
378
+ if tensor_name in value_infos:
379
+ onnx_type = value_infos[tensor_name].type.tensor_type.elem_type
380
+ else:
381
+ raise ValueError(
382
+ f"Unable to guess tensor type for tensor {tensor_name!r}, "
383
+ f"running shape inference before quantization may resolve this issue."
384
+ )
385
+
386
+ # Include axes in reduce_op when per_channel, always keeping axis=1
387
+ if self.per_channel:
388
+ tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim)
389
+ reduced_axes = [0, *range(2, tensor_rank)]
390
+ # Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs
391
+ if get_op_version(reduce_op_name, self.model) < 18:
392
+ reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes))
393
+ else:
394
+ reduce_axes_name = str(uuid.uuid4())
395
+ reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name)
396
+ reduce_node.input.append(reduce_axes_name)
397
+ self.model.graph.initializer.append(reduce_axes)
398
+
399
+ self.model.graph.node.extend([reduce_node, reshape_node])
400
+ self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
401
+
402
+ for tensor in tensors:
403
+ add_reduce_min_max(tensor, "ReduceMin")
404
+ add_reduce_min_max(tensor, "ReduceMax")
405
+
406
+ onnx.save(
407
+ self.model,
408
+ self.augmented_model_path,
409
+ save_as_external_data=self.use_external_data_format,
410
+ )
411
+
412
+ def clear_collected_data(self):
413
+ self.intermediate_outputs = []
414
+
415
+ def collect_data(self, data_reader: CalibrationDataReader):
416
+ while True:
417
+ inputs = data_reader.get_next()
418
+ if not inputs:
419
+ break
420
+ self.intermediate_outputs.append(self.infer_session.run(None, inputs))
421
+ if (
422
+ self.max_intermediate_outputs is not None
423
+ and len(self.intermediate_outputs) == self.max_intermediate_outputs
424
+ ):
425
+ self.clear_collected_data()
426
+
427
+ if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None:
428
+ raise ValueError("No data is collected.")
429
+
430
+ t = self.compute_data()
431
+ if not isinstance(t, TensorsData):
432
+ raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
433
+ self.clear_collected_data()
434
+
435
+ def merge_range(self, old_range, new_range):
436
+ if not old_range:
437
+ return new_range
438
+
439
+ for key, value in old_range.items():
440
+ # Handling for structured data types with TensorData
441
+ if isinstance(value, TensorData):
442
+ old_min = value.range_value[0]
443
+ old_max = value.range_value[1]
444
+ else:
445
+ old_min, old_max = value
446
+
447
+ if isinstance(new_range[key], TensorData):
448
+ new_min = new_range[key].range_value[0]
449
+ new_max = new_range[key].range_value[1]
450
+ else:
451
+ new_min, new_max = new_range[key]
452
+
453
+ if self.moving_average:
454
+ min_value = old_min + self.averaging_constant * (new_min - old_min)
455
+ max_value = old_max + self.averaging_constant * (new_max - old_max)
456
+ else:
457
+ min_value = min(old_min, new_min)
458
+ max_value = max(old_max, new_max)
459
+
460
+ # If structured as TensorData, wrap the result accordingly
461
+ if isinstance(value, TensorData) or isinstance(new_range[key], TensorData):
462
+ new_range[key] = TensorData(lowest=min_value, highest=max_value)
463
+ else:
464
+ new_range[key] = (min_value, max_value)
465
+
466
+ return new_range
467
+
468
+ def compute_data(self) -> TensorsData:
469
+ """
470
+ Compute the min-max range of tensor
471
+ :return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
472
+ """
473
+
474
+ if len(self.intermediate_outputs) == 0:
475
+ return self.calibrate_tensors_range
476
+
477
+ output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
478
+ output_dicts_list = [
479
+ dict(zip(output_names, intermediate_output)) for intermediate_output in self.intermediate_outputs
480
+ ]
481
+
482
+ merged_output_dict = {}
483
+ for d in output_dicts_list:
484
+ for k, v in d.items():
485
+ merged_output_dict.setdefault(k, []).append(v)
486
+ added_output_names = output_names[self.num_model_outputs :]
487
+ calibrate_tensor_names = [
488
+ added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
489
+ ] # output names
490
+
491
+ merged_added_output_dict = {
492
+ i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs
493
+ }
494
+
495
+ pairs = []
496
+ for i in range(0, len(added_output_names), 2):
497
+ if self.moving_average:
498
+ min_value_array = np.mean(merged_added_output_dict[added_output_names[i]], axis=0)
499
+ max_value_array = np.mean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
500
+ else:
501
+ min_value_array = np.min(merged_added_output_dict[added_output_names[i]], axis=0)
502
+ max_value_array = np.max(merged_added_output_dict[added_output_names[i + 1]], axis=0)
503
+
504
+ if self.symmetric:
505
+ max_absolute_value = np.max([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
506
+ pairs.append(tuple([-max_absolute_value, max_absolute_value]))
507
+ else:
508
+ pairs.append(tuple([min_value_array, max_value_array]))
509
+
510
+ new_calibrate_tensors_range = TensorsData(CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs)))
511
+ if self.calibrate_tensors_range:
512
+ self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
513
+ else:
514
+ self.calibrate_tensors_range = new_calibrate_tensors_range
515
+
516
+ return self.calibrate_tensors_range
517
+
518
+
519
+ class HistogramCalibrater(CalibraterBase):
520
+ def __init__(
521
+ self,
522
+ model_path: Union[str, Path],
523
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
524
+ augmented_model_path="augmented_model.onnx",
525
+ use_external_data_format=False,
526
+ method="percentile",
527
+ symmetric=False,
528
+ num_bins=128,
529
+ num_quantized_bins=2048,
530
+ percentile=99.999,
531
+ scenario="same",
532
+ ):
533
+ """
534
+ :param model_path: ONNX model to calibrate. It is a model path.
535
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
536
+ :param augmented_model_path: save augmented model to this path.
537
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
538
+ :param method: A string. One of ['entropy', 'percentile'].
539
+ :param symmetric: make range of tensor symmetric (central point is 0).
540
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
541
+ :param num_quantized_bins: number of quantized bins. Default 128.
542
+ :param percentile: A float number between [0, 100]. Default 99.99.
543
+ :param scenario: see :class:`DistributionCalibrater`
544
+ """
545
+ super().__init__(
546
+ model_path,
547
+ op_types_to_calibrate=op_types_to_calibrate,
548
+ augmented_model_path=augmented_model_path,
549
+ symmetric=symmetric,
550
+ use_external_data_format=use_external_data_format,
551
+ )
552
+ self.intermediate_outputs = []
553
+ self.calibrate_tensors_range = None
554
+ self.num_model_outputs = len(self.model.graph.output)
555
+ self.model_original_outputs = {output.name for output in self.model.graph.output}
556
+ self.collector = None
557
+ self.method = method
558
+ self.num_bins = num_bins
559
+ self.num_quantized_bins = num_quantized_bins
560
+ self.percentile = percentile
561
+ self.tensors_to_calibrate = None
562
+ self.scenario = scenario
563
+
564
+ def augment_graph(self):
565
+ """
566
+ make all quantization_candidates op type nodes as part of the graph output.
567
+ :return: augmented ONNX model
568
+ """
569
+ self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model)
570
+ for tensor in self.tensors_to_calibrate:
571
+ if tensor not in self.model_original_outputs:
572
+ self.model.graph.output.append(value_infos[tensor])
573
+
574
+ onnx.save(
575
+ self.model,
576
+ self.augmented_model_path,
577
+ save_as_external_data=self.use_external_data_format,
578
+ )
579
+
580
+ def clear_collected_data(self):
581
+ self.intermediate_outputs = []
582
+
583
+ def collect_data(self, data_reader: CalibrationDataReader):
584
+ """
585
+ Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator.
586
+ """
587
+ input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()}
588
+ output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
589
+
590
+ while True:
591
+ inputs = data_reader.get_next()
592
+ if not inputs:
593
+ break
594
+ outputs = self.infer_session.run(None, inputs)
595
+
596
+ # Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug:
597
+ # https://github.com/microsoft/onnxruntime/issues/21922
598
+ fixed_outputs = []
599
+ for output_index, output in enumerate(outputs):
600
+ if output_names[output_index] in input_names_set:
601
+ fixed_outputs.append(copy.copy(output))
602
+ else:
603
+ fixed_outputs.append(output)
604
+
605
+ self.intermediate_outputs.append(fixed_outputs)
606
+
607
+ if len(self.intermediate_outputs) == 0:
608
+ raise ValueError("No data is collected.")
609
+
610
+ output_dicts_list = [
611
+ dict(zip(output_names, intermediate_output)) for intermediate_output in self.intermediate_outputs
612
+ ]
613
+
614
+ merged_dict = {}
615
+ for d in output_dicts_list:
616
+ for k, v in d.items():
617
+ merged_dict.setdefault(k, []).append(v)
618
+
619
+ clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
620
+
621
+ if not self.collector:
622
+ self.collector = HistogramCollector(
623
+ method=self.method,
624
+ symmetric=self.symmetric,
625
+ num_bins=self.num_bins,
626
+ num_quantized_bins=self.num_quantized_bins,
627
+ percentile=self.percentile,
628
+ scenario=self.scenario,
629
+ )
630
+ self.collector.collect(clean_merged_dict)
631
+
632
+ self.clear_collected_data()
633
+
634
+ def compute_data(self) -> TensorsData:
635
+ """
636
+ Compute the min-max range of tensor
637
+ :return: dictionary mapping: {tensor name: (min value, max value)}
638
+ """
639
+ if not self.collector:
640
+ raise ValueError("No collector created and can't generate calibration data.")
641
+
642
+ if isinstance(self, EntropyCalibrater):
643
+ cal = CalibrationMethod.Entropy
644
+ elif isinstance(self, PercentileCalibrater):
645
+ cal = CalibrationMethod.Percentile
646
+ elif isinstance(self, DistributionCalibrater):
647
+ cal = CalibrationMethod.Distribution
648
+ else:
649
+ raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.")
650
+ return TensorsData(cal, self.collector.compute_collection_result())
651
+
652
+
653
+ class EntropyCalibrater(HistogramCalibrater):
654
+ def __init__(
655
+ self,
656
+ model_path: Union[str, Path],
657
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
658
+ augmented_model_path="augmented_model.onnx",
659
+ use_external_data_format=False,
660
+ method="entropy",
661
+ symmetric=False,
662
+ num_bins=128,
663
+ num_quantized_bins=128,
664
+ ):
665
+ """
666
+ :param model_path: ONNX model to calibrate. It is a model path
667
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
668
+ :param augmented_model_path: save augmented model to this path.
669
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
670
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
671
+ :param symmetric: make range of tensor symmetric (central point is 0).
672
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
673
+ :param num_quantized_bins: number of quantized bins. Default 128.
674
+ """
675
+ super().__init__(
676
+ model_path,
677
+ op_types_to_calibrate,
678
+ augmented_model_path,
679
+ use_external_data_format,
680
+ method=method,
681
+ symmetric=symmetric,
682
+ num_bins=num_bins,
683
+ num_quantized_bins=num_quantized_bins,
684
+ )
685
+
686
+
687
+ class PercentileCalibrater(HistogramCalibrater):
688
+ def __init__(
689
+ self,
690
+ model_path: Union[str, Path],
691
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
692
+ augmented_model_path="augmented_model.onnx",
693
+ use_external_data_format=False,
694
+ method="percentile",
695
+ symmetric=False,
696
+ num_bins=2048,
697
+ percentile=99.999,
698
+ ):
699
+ """
700
+ :param model_path: ONNX model to calibrate. It is a model path
701
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
702
+ :param augmented_model_path: save augmented model to this path.
703
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
704
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
705
+ :param symmetric: make range of tensor symmetric (central point is 0).
706
+ :param num_quantized_bins: number of quantized bins. Default 128.
707
+ :param percentile: A float number between [0, 100]. Default 99.99.
708
+ """
709
+ super().__init__(
710
+ model_path,
711
+ op_types_to_calibrate,
712
+ augmented_model_path,
713
+ use_external_data_format,
714
+ method=method,
715
+ symmetric=symmetric,
716
+ num_bins=num_bins,
717
+ percentile=percentile,
718
+ )
719
+
720
+
721
+ class DistributionCalibrater(HistogramCalibrater):
722
+ def __init__(
723
+ self,
724
+ model_path: Union[str, Path],
725
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
726
+ augmented_model_path="augmented_model.onnx",
727
+ use_external_data_format=False,
728
+ method="distribution",
729
+ num_bins=128,
730
+ scenario="same",
731
+ ):
732
+ """
733
+ :param model_path: ONNX model to calibrate. It is a model path
734
+ :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
735
+ :param augmented_model_path: save augmented model to this path.
736
+ :param use_external_data_format: use external data format to store model which size is >= 2Gb
737
+ :param method: A string. One of ['entropy', 'percentile', 'distribution'].
738
+ :param symmetric: make range of tensor symmetric (central point is 0).
739
+ :param num_bins: number of bins to create a new histogram for collecting tensor values.
740
+ :param scenario: for float 8 only, if `scenario="same"`,
741
+ the algorithm weights and float 8 follow the same distribution,
742
+ if `scenario="p3"`, it assumes the weights follow
743
+ a gaussian law and float 8 ~ X^3 where X is a gaussian law
744
+ """
745
+ super().__init__(
746
+ model_path,
747
+ op_types_to_calibrate,
748
+ augmented_model_path,
749
+ use_external_data_format,
750
+ method=method,
751
+ num_bins=num_bins,
752
+ scenario=scenario,
753
+ )
754
+
755
+
756
+ class CalibrationDataCollector(metaclass=abc.ABCMeta):
757
+ """
758
+ Base class for collecting data for calibration-based quantization.
759
+ """
760
+
761
+ @abc.abstractmethod
762
+ def collect(self, name_to_arr):
763
+ """
764
+ Generate informative data based on given data.
765
+ name_to_arr : dict
766
+ tensor name to NDArray data
767
+ """
768
+ raise NotImplementedError
769
+
770
+ @abc.abstractmethod
771
+ def compute_collection_result(self):
772
+ """
773
+ Get the optimal result among collection data.
774
+ """
775
+ raise NotImplementedError
776
+
777
+
778
+ class HistogramCollector(CalibrationDataCollector):
779
+ """
780
+ Collecting histogram for each tensor. Percentile and Entropy method are supported.
781
+
782
+ ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
783
+ ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/
784
+ pytorch_quantization/calib/histogram.html
785
+ """
786
+
787
+ def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario):
788
+ self.histogram_dict = {}
789
+ self.method = method
790
+ self.symmetric = symmetric
791
+ self.num_bins = num_bins
792
+ self.num_quantized_bins = num_quantized_bins
793
+ self.percentile = percentile
794
+ self.scenario = scenario
795
+
796
+ def get_histogram_dict(self):
797
+ return self.histogram_dict
798
+
799
+ def collect(self, name_to_arr):
800
+ print("Collecting tensor data and making histogram ...")
801
+
802
+ # TODO: Currently we have different collect() for entropy and percentile method respectively.
803
+ # Need unified collect in the future.
804
+ if self.method in {"distribution", "entropy"}:
805
+ return self.collect_value(name_to_arr)
806
+ elif self.method == "percentile":
807
+ if self.symmetric:
808
+ return self.collect_absolute_value(name_to_arr)
809
+ else:
810
+ return self.collect_value(name_to_arr)
811
+ else:
812
+ raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
813
+
814
+ def collect_absolute_value(self, name_to_arr):
815
+ """
816
+ Collect histogram on absolute value
817
+ """
818
+ for tensor, data_arr in name_to_arr.items():
819
+ if isinstance(data_arr, list):
820
+ for arr in data_arr:
821
+ assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}"
822
+ dtypes = set(a.dtype for a in data_arr)
823
+ assert (
824
+ len(dtypes) == 1
825
+ ), f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
826
+ data_arr_np = np.asarray(data_arr)
827
+ elif not isinstance(data_arr, np.ndarray):
828
+ raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
829
+ else:
830
+ data_arr_np = data_arr
831
+ data_arr_np = data_arr_np.flatten()
832
+ if data_arr_np.size > 0:
833
+ min_value = np.min(data_arr_np)
834
+ max_value = np.max(data_arr_np)
835
+ else:
836
+ min_value = np.array(0, dtype=data_arr_np.dtype)
837
+ max_value = np.array(0, dtype=data_arr_np.dtype)
838
+
839
+ data_arr_np = np.absolute(data_arr_np) # only consider absolute value
840
+
841
+ if tensor not in self.histogram_dict:
842
+ # first time it uses num_bins to compute histogram.
843
+ hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins)
844
+ hist_edges = hist_edges.astype(data_arr_np.dtype)
845
+ assert (
846
+ data_arr_np.dtype != np.float64
847
+ ), "only float32 or float16 is supported, every constant must be explicitly typed"
848
+ self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
849
+ else:
850
+ old_histogram = self.histogram_dict[tensor]
851
+ old_min = old_histogram[2]
852
+ old_max = old_histogram[3]
853
+ assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}"
854
+ assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}"
855
+ old_hist = old_histogram[0]
856
+ old_hist_edges = old_histogram[1]
857
+ temp_amax = np.max(data_arr_np)
858
+ if temp_amax > old_hist_edges[-1]:
859
+ # increase the number of bins
860
+ width = old_hist_edges[1] - old_hist_edges[0]
861
+ # NOTE: np.arange may create an extra bin after the one containing temp_amax
862
+ new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
863
+ old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
864
+ hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
865
+ hist_edges = hist_edges.astype(data_arr_np.dtype)
866
+ hist[: len(old_hist)] += old_hist
867
+ assert (
868
+ data_arr_np.dtype != np.float64
869
+ ), "only float32 or float16 is supported, every constant must be explicitly typed"
870
+ self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
871
+
872
+ def collect_value(self, name_to_arr):
873
+ """
874
+ Collect histogram on real value
875
+ """
876
+ for tensor, data_arr in name_to_arr.items():
877
+ data_arr = np.asarray(data_arr) # noqa: PLW2901
878
+ data_arr = data_arr.flatten() # noqa: PLW2901
879
+
880
+ if data_arr.size > 0:
881
+ min_value = np.min(data_arr)
882
+ max_value = np.max(data_arr)
883
+ else:
884
+ min_value = np.array(0, dtype=data_arr.dtype)
885
+ max_value = np.array(0, dtype=data_arr.dtype)
886
+
887
+ threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
888
+
889
+ if tensor in self.histogram_dict:
890
+ old_histogram = self.histogram_dict[tensor]
891
+ self.histogram_dict[tensor] = self.merge_histogram(
892
+ old_histogram, data_arr, min_value, max_value, threshold
893
+ )
894
+ else:
895
+ hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold))
896
+ self.histogram_dict[tensor] = (
897
+ hist,
898
+ hist_edges,
899
+ min_value,
900
+ max_value,
901
+ threshold,
902
+ )
903
+
904
+ def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold):
905
+ (old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
906
+
907
+ if new_threshold <= old_threshold:
908
+ new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold))
909
+ return (
910
+ new_hist + old_hist,
911
+ old_hist_edges,
912
+ min(old_min, new_min),
913
+ max(old_max, new_max),
914
+ old_threshold,
915
+ )
916
+ else:
917
+ if old_threshold == 0:
918
+ hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold))
919
+ hist += old_hist
920
+ else:
921
+ old_num_bins = len(old_hist)
922
+ old_stride = 2 * old_threshold / old_num_bins
923
+ half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1)
924
+ new_num_bins = old_num_bins + 2 * half_increased_bins
925
+ new_threshold = half_increased_bins * old_stride + old_threshold
926
+ hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold))
927
+ hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist
928
+ return (
929
+ hist,
930
+ hist_edges,
931
+ min(old_min, new_min),
932
+ max(old_max, new_max),
933
+ new_threshold,
934
+ )
935
+
936
+ def compute_collection_result(self):
937
+ if not self.histogram_dict or len(self.histogram_dict) == 0:
938
+ raise ValueError("Histogram has not been collected. Please run collect() first.")
939
+ print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
940
+
941
+ if self.method == "entropy":
942
+ return self.compute_entropy()
943
+ elif self.method == "percentile":
944
+ return self.compute_percentile()
945
+ elif self.method == "distribution":
946
+ return self.compute_distribution()
947
+ else:
948
+ raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
949
+
950
+ def compute_percentile(self):
951
+ if self.percentile < 0 or self.percentile > 100:
952
+ raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
953
+
954
+ histogram_dict = self.histogram_dict
955
+ percentile = self.percentile
956
+
957
+ thresholds_dict = {} # per tensor thresholds
958
+
959
+ print(f"Number of tensors : {len(histogram_dict)}")
960
+ print(f"Number of histogram bins : {self.num_bins}")
961
+ print(f"Percentile : ({100.0 - percentile},{percentile})")
962
+
963
+ for tensor, histogram in histogram_dict.items():
964
+ hist = histogram[0]
965
+ hist_edges = histogram[1]
966
+ total = hist.sum()
967
+ cdf = np.cumsum(hist / total)
968
+ if self.symmetric:
969
+ idx_right = np.searchsorted(cdf, percentile / 100.0)
970
+
971
+ thresholds_dict[tensor] = (
972
+ -np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
973
+ np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
974
+ )
975
+ else:
976
+ percent_to_cut_one_side = (100.0 - percentile) / 200.0
977
+ idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side)
978
+ idx_left = np.searchsorted(cdf, percent_to_cut_one_side)
979
+ thresholds_dict[tensor] = (
980
+ np.array(hist_edges[idx_left], dtype=hist_edges.dtype),
981
+ np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
982
+ )
983
+ min_value = histogram[2]
984
+ max_value = histogram[3]
985
+ if thresholds_dict[tensor][0] < min_value:
986
+ thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1])
987
+ if thresholds_dict[tensor][1] > max_value:
988
+ thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value)
989
+ thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2])
990
+ # Plot histogram for debug only
991
+ if os.environ.get("QUANTIZATION_DEBUG", 0) in (1, "1"):
992
+ apply_plot(hist, hist_edges)
993
+
994
+ return thresholds_dict
995
+
996
+ def compute_entropy(self):
997
+ histogram_dict = self.histogram_dict
998
+ num_quantized_bins = self.num_quantized_bins
999
+
1000
+ thresholds_dict = {} # per tensor thresholds
1001
+
1002
+ print(f"Number of tensors : {len(histogram_dict)}")
1003
+ print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)")
1004
+ print(f"Number of quantized bins : {self.num_quantized_bins}")
1005
+
1006
+ for tensor, histogram in histogram_dict.items():
1007
+ optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins)
1008
+ thresholds_dict[tensor] = optimal_threshold
1009
+ thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
1010
+
1011
+ # Plot histogram for debug only
1012
+ if os.environ.get("QUANTIZATION_DEBUG", 0) in (1, "1"):
1013
+ apply_plot(histogram[0], histogram[1])
1014
+
1015
+ return thresholds_dict
1016
+
1017
+ @staticmethod
1018
+ def _avg_std(hist, hist_edges, power=1):
1019
+ if power <= 0:
1020
+ raise ValueError(f"power={power} <= 0 is invalid.")
1021
+ values = (hist_edges[:-1] + hist_edges[1:]) * 0.5
1022
+ if power == 1:
1023
+ avg = (hist * values).sum() / hist.sum()
1024
+ std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
1025
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1026
+ if int(power) == power and int(power) % 2 == 1:
1027
+ avg = (hist * values**power).sum() / hist.sum()
1028
+ std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5
1029
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1030
+
1031
+ fact = np.abs(values) / values
1032
+ fact[np.isnan(fact)] = 1
1033
+ fact[np.isinf(fact)] = 1
1034
+ values = np.abs(values) ** power * fact
1035
+ avg = (hist * values).sum() / hist.sum()
1036
+ std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
1037
+ return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
1038
+
1039
+ def compute_distribution(self):
1040
+ if self.num_bins < 512:
1041
+ raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
1042
+
1043
+ histogram_dict = self.histogram_dict
1044
+ thresholds_dict = {} # per tensor thresholds
1045
+
1046
+ print(f"Number of tensors : {len(histogram_dict)}")
1047
+ print(f"Number of histogram bins : {self.num_bins}")
1048
+ print(f"Scenario : {self.scenario!r})")
1049
+
1050
+ for tensor, histogram in histogram_dict.items():
1051
+ hist = histogram[0]
1052
+ hist_edges = histogram[1]
1053
+
1054
+ assert hist_edges.dtype != np.float64
1055
+ if self.scenario == "same":
1056
+ avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1)
1057
+ elif self.scenario == "p3":
1058
+ avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0)
1059
+ else:
1060
+ raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.")
1061
+ assert avg_coef.dtype != np.float64
1062
+ assert std_coef.dtype != np.float64
1063
+ assert hist_edges.dtype != np.float64
1064
+ thresholds_dict[tensor] = TensorData(
1065
+ avg=avg_coef,
1066
+ std=std_coef,
1067
+ hist=hist,
1068
+ hist_edges=hist_edges,
1069
+ lowest=hist_edges.min(),
1070
+ highest=hist_edges.max(),
1071
+ )
1072
+
1073
+ # Plot histogram for debug only
1074
+ if os.environ.get("QUANTIZATION_DEBUG", 0) in (1, "1"):
1075
+ apply_plot(hist, hist_edges)
1076
+
1077
+ return thresholds_dict
1078
+
1079
+ def get_entropy_threshold(self, histogram, num_quantized_bins):
1080
+ """Given a dataset, find the optimal threshold for quantizing it.
1081
+ The reference distribution is `q`, and the candidate distribution is `p`.
1082
+ `q` is a truncated version of the original distribution.
1083
+ Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf
1084
+ """
1085
+ hist = histogram[0]
1086
+ hist_edges = histogram[1]
1087
+ num_bins = hist.size
1088
+ zero_bin_index = num_bins // 2
1089
+ num_half_quantized_bin = num_quantized_bins // 2
1090
+
1091
+ dtype = histogram[1].dtype
1092
+ kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1)
1093
+ thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
1094
+
1095
+ # <------------ num bins ---------------->
1096
+ # <--- quantized bins ---->
1097
+ # |======|===========|===========|=======|
1098
+ # zero bin index
1099
+ # ^ ^
1100
+ # | |
1101
+ # start index end index (start of iteration)
1102
+ # ^ ^
1103
+ # | |
1104
+ # start index end index ...
1105
+ # ^ ^
1106
+ # | |
1107
+ # start index end index (end of iteration)
1108
+
1109
+ for i in range(num_half_quantized_bin, zero_bin_index + 1, 1):
1110
+ start_index = zero_bin_index - i
1111
+ end_index = min(zero_bin_index + i + 1, num_bins)
1112
+
1113
+ thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
1114
+
1115
+ sliced_distribution = copy.deepcopy(hist[start_index:end_index])
1116
+
1117
+ # reference distribution p
1118
+ p = sliced_distribution.copy() # a copy of np array
1119
+ left_outliers_count = sum(hist[:start_index])
1120
+ right_outliers_count = sum(hist[end_index:])
1121
+ p[0] += left_outliers_count
1122
+ p[-1] += right_outliers_count
1123
+
1124
+ # nonzeros[i] incidates whether p[i] is non-zero
1125
+ nonzeros = (p != 0).astype(np.int64)
1126
+
1127
+ # quantize p.size bins into quantized bins (default 128 bins)
1128
+ quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64)
1129
+ num_merged_bins = sliced_distribution.size // num_quantized_bins
1130
+
1131
+ # merge bins into quantized bins
1132
+ for index in range(num_quantized_bins):
1133
+ start = index * num_merged_bins
1134
+ end = start + num_merged_bins
1135
+ quantized_bins[index] = sum(sliced_distribution[start:end])
1136
+ quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
1137
+
1138
+ # in order to compare p and q, we need to make length of q equals to length of p
1139
+ # expand quantized bins into p.size bins
1140
+ q = np.zeros(p.size, dtype=np.int64)
1141
+ for index in range(num_quantized_bins):
1142
+ start = index * num_merged_bins
1143
+ end = start + num_merged_bins
1144
+
1145
+ norm = sum(nonzeros[start:end])
1146
+ if norm != 0:
1147
+ q[start:end] = quantized_bins[index] / norm
1148
+
1149
+ p = smooth_distribution(p)
1150
+ q = smooth_distribution(q)
1151
+ if p is None or q is None:
1152
+ div = np.array(np.inf, dtype=dtype)
1153
+ else:
1154
+ div = np.array(entropy(p, q), dtype=dtype)
1155
+ kl_divergence[i - num_half_quantized_bin] = div
1156
+
1157
+ min_kl_divergence_idx = np.argmin(kl_divergence)
1158
+ optimal_threshold = thresholds[min_kl_divergence_idx]
1159
+ min_value = histogram[2]
1160
+ max_value = histogram[3]
1161
+ if optimal_threshold[0] < min_value:
1162
+ optimal_threshold = (min_value, optimal_threshold[1])
1163
+ if optimal_threshold[1] > max_value:
1164
+ optimal_threshold = (optimal_threshold[0], max_value)
1165
+ assert hasattr(optimal_threshold[0], "dtype")
1166
+ assert hasattr(optimal_threshold[1], "dtype")
1167
+ return optimal_threshold
1168
+
1169
+
1170
+ def create_calibrator(
1171
+ model: Union[str, Path],
1172
+ op_types_to_calibrate: Optional[Sequence[str]] = None,
1173
+ augmented_model_path="augmented_model.onnx",
1174
+ calibrate_method=CalibrationMethod.MinMax,
1175
+ use_external_data_format=False,
1176
+ extra_options={}, # noqa: B006
1177
+ ):
1178
+ calibrator = None
1179
+ if calibrate_method == CalibrationMethod.MinMax:
1180
+ # default settings for min-max algorithm
1181
+ symmetric = extra_options.get("symmetric", False)
1182
+ moving_average = extra_options.get("moving_average", False)
1183
+ averaging_constant = extra_options.get("averaging_constant", 0.01)
1184
+ max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None)
1185
+ per_channel = extra_options.get("per_channel", False)
1186
+ calibrator = MinMaxCalibrater(
1187
+ model,
1188
+ op_types_to_calibrate,
1189
+ augmented_model_path,
1190
+ use_external_data_format=use_external_data_format,
1191
+ symmetric=symmetric,
1192
+ moving_average=moving_average,
1193
+ averaging_constant=averaging_constant,
1194
+ max_intermediate_outputs=max_intermediate_outputs,
1195
+ per_channel=per_channel,
1196
+ )
1197
+ elif calibrate_method == CalibrationMethod.Entropy:
1198
+ # default settings for entropy algorithm
1199
+ num_bins = extra_options.get("num_bins", 128)
1200
+ num_quantized_bins = extra_options.get("num_quantized_bins", 128)
1201
+ symmetric = extra_options.get("symmetric", False)
1202
+ calibrator = EntropyCalibrater(
1203
+ model,
1204
+ op_types_to_calibrate,
1205
+ augmented_model_path,
1206
+ use_external_data_format=use_external_data_format,
1207
+ symmetric=symmetric,
1208
+ num_bins=num_bins,
1209
+ num_quantized_bins=num_quantized_bins,
1210
+ )
1211
+ elif calibrate_method == CalibrationMethod.Percentile:
1212
+ # default settings for percentile algorithm
1213
+ num_bins = extra_options.get("num_bins", 2048)
1214
+ percentile = extra_options.get("percentile", 99.999)
1215
+ symmetric = extra_options.get("symmetric", True)
1216
+ calibrator = PercentileCalibrater(
1217
+ model,
1218
+ op_types_to_calibrate,
1219
+ augmented_model_path,
1220
+ use_external_data_format=use_external_data_format,
1221
+ symmetric=symmetric,
1222
+ num_bins=num_bins,
1223
+ percentile=percentile,
1224
+ )
1225
+
1226
+ elif calibrate_method == CalibrationMethod.Distribution:
1227
+ # default settings for percentile algorithm
1228
+ num_bins = extra_options.get("num_bins", 2048)
1229
+ scenario = extra_options.get("scenario", "same")
1230
+
1231
+ calibrator = DistributionCalibrater(
1232
+ model,
1233
+ op_types_to_calibrate,
1234
+ augmented_model_path,
1235
+ use_external_data_format=use_external_data_format,
1236
+ num_bins=num_bins,
1237
+ scenario=scenario,
1238
+ )
1239
+
1240
+ if calibrator:
1241
+ calibrator.augment_graph()
1242
+ calibrator.create_inference_session()
1243
+ return calibrator
1244
+
1245
+ raise ValueError(f"Unsupported calibration method {calibrate_method}")