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,1108 @@
1
+ # -------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License.
4
+ # --------------------------------------------------------------------------
5
+ from __future__ import annotations
6
+
7
+ import collections
8
+ import collections.abc
9
+ import os
10
+ import typing
11
+ import warnings
12
+ from typing import Any, Sequence
13
+
14
+ from onnxruntime.capi import _pybind_state as C
15
+
16
+ if typing.TYPE_CHECKING:
17
+ import onnxruntime
18
+
19
+
20
+ def get_ort_device_type(device_type: str, device_index) -> C.OrtDevice:
21
+ if device_type == "cuda":
22
+ return C.OrtDevice.cuda()
23
+ elif device_type == "cann":
24
+ return C.OrtDevice.cann()
25
+ elif device_type == "cpu":
26
+ return C.OrtDevice.cpu()
27
+ elif device_type == "dml":
28
+ return C.OrtDevice.dml()
29
+ elif device_type == "ort":
30
+ return C.get_ort_device(device_index).device_type()
31
+ else:
32
+ raise Exception("Unsupported device type: " + device_type)
33
+
34
+
35
+ class AdapterFormat:
36
+ """
37
+ This class is used to create adapter files from python structures
38
+ """
39
+
40
+ def __init__(self, adapter=None) -> None:
41
+ if adapter is None:
42
+ self._adapter = C.AdapterFormat()
43
+ else:
44
+ self._adapter = adapter
45
+
46
+ @staticmethod
47
+ def read_adapter(file_path: os.PathLike) -> AdapterFormat:
48
+ return AdapterFormat(C.AdapterFormat.read_adapter(file_path))
49
+
50
+ def export_adapter(self, file_path: os.PathLike):
51
+ """
52
+ This function writes a file at the specified location
53
+ in onnxrunitme adapter format containing Lora parameters.
54
+
55
+ :param file_path: absolute path for the adapter
56
+ """
57
+ self._adapter.export_adapter(file_path)
58
+
59
+ def get_format_version(self):
60
+ return self._adapter.format_version
61
+
62
+ def set_adapter_version(self, adapter_version: int):
63
+ self._adapter.adapter_version = adapter_version
64
+
65
+ def get_adapter_version(self):
66
+ return self._adapter.adapter_version
67
+
68
+ def set_model_version(self, model_version: int):
69
+ self._adapter.model_version = model_version
70
+
71
+ def get_model_version(self):
72
+ return self._adapter.model_version
73
+
74
+ def set_parameters(self, params: dict[str, OrtValue]):
75
+ self._adapter.parameters = {k: v._ortvalue for k, v in params.items()}
76
+
77
+ def get_parameters(self) -> dict[str, OrtValue]:
78
+ return {k: OrtValue(v) for k, v in self._adapter.parameters.items()}
79
+
80
+
81
+ def check_and_normalize_provider_args(
82
+ providers: Sequence[str | tuple[str, dict[Any, Any]]] | None,
83
+ provider_options: Sequence[dict[Any, Any]] | None,
84
+ available_provider_names: Sequence[str],
85
+ ):
86
+ """
87
+ Validates the 'providers' and 'provider_options' arguments and returns a
88
+ normalized version.
89
+
90
+ :param providers: Optional sequence of providers in order of decreasing
91
+ precedence. Values can either be provider names or tuples of
92
+ (provider name, options dict).
93
+ :param provider_options: Optional sequence of options dicts corresponding
94
+ to the providers listed in 'providers'.
95
+ :param available_provider_names: The available provider names.
96
+
97
+ :return: Tuple of (normalized 'providers' sequence, normalized
98
+ 'provider_options' sequence).
99
+
100
+ 'providers' can contain either names or names and options. When any options
101
+ are given in 'providers', 'provider_options' should not be used.
102
+
103
+ The normalized result is a tuple of:
104
+ 1. Sequence of provider names in the same order as 'providers'.
105
+ 2. Sequence of corresponding provider options dicts with string keys and
106
+ values. Unspecified provider options yield empty dicts.
107
+ """
108
+ if providers is None:
109
+ return [], []
110
+
111
+ provider_name_to_options = collections.OrderedDict()
112
+
113
+ def set_provider_options(name, options):
114
+ if name not in available_provider_names:
115
+ warnings.warn(
116
+ "Specified provider '{}' is not in available provider names."
117
+ "Available providers: '{}'".format(name, ", ".join(available_provider_names))
118
+ )
119
+
120
+ if name in provider_name_to_options:
121
+ warnings.warn(f"Duplicate provider '{name}' encountered, ignoring.")
122
+ return
123
+
124
+ normalized_options = {str(key): str(value) for key, value in options.items()}
125
+ provider_name_to_options[name] = normalized_options
126
+
127
+ if not isinstance(providers, collections.abc.Sequence):
128
+ raise ValueError("'providers' should be a sequence.")
129
+
130
+ if provider_options is not None:
131
+ if not isinstance(provider_options, collections.abc.Sequence):
132
+ raise ValueError("'provider_options' should be a sequence.")
133
+
134
+ if len(providers) != len(provider_options):
135
+ raise ValueError("'providers' and 'provider_options' should be the same length if both are given.")
136
+
137
+ if not all([isinstance(provider, str) for provider in providers]):
138
+ raise ValueError("Only string values for 'providers' are supported if 'provider_options' is given.")
139
+
140
+ if not all([isinstance(options_for_provider, dict) for options_for_provider in provider_options]):
141
+ raise ValueError("'provider_options' values must be dicts.")
142
+
143
+ for name, options in zip(providers, provider_options):
144
+ set_provider_options(name, options)
145
+
146
+ else:
147
+ for provider in providers:
148
+ if isinstance(provider, str):
149
+ set_provider_options(provider, dict())
150
+ elif (
151
+ isinstance(provider, tuple)
152
+ and len(provider) == 2
153
+ and isinstance(provider[0], str)
154
+ and isinstance(provider[1], dict)
155
+ ):
156
+ set_provider_options(provider[0], provider[1])
157
+ else:
158
+ raise ValueError("'providers' values must be either strings or (string, dict) tuples.")
159
+
160
+ return list(provider_name_to_options.keys()), list(provider_name_to_options.values())
161
+
162
+
163
+ class Session:
164
+ """
165
+ This is the main class used to run a model.
166
+ """
167
+
168
+ def __init__(self):
169
+ # self._sess is managed by the derived class and relies on bindings from C.InferenceSession
170
+ self._sess = None
171
+ self._enable_fallback = True
172
+
173
+ def get_session_options(self):
174
+ "Return the session options. See :class:`onnxruntime.SessionOptions`."
175
+ return self._sess_options
176
+
177
+ def get_inputs(self):
178
+ "Return the inputs metadata as a list of :class:`onnxruntime.NodeArg`."
179
+ return self._inputs_meta
180
+
181
+ def get_outputs(self):
182
+ "Return the outputs metadata as a list of :class:`onnxruntime.NodeArg`."
183
+ return self._outputs_meta
184
+
185
+ def get_overridable_initializers(self):
186
+ "Return the inputs (including initializers) metadata as a list of :class:`onnxruntime.NodeArg`."
187
+ return self._overridable_initializers
188
+
189
+ def get_modelmeta(self):
190
+ "Return the metadata. See :class:`onnxruntime.ModelMetadata`."
191
+ return self._model_meta
192
+
193
+ def get_providers(self):
194
+ "Return list of registered execution providers."
195
+ return self._providers
196
+
197
+ def get_provider_options(self):
198
+ "Return registered execution providers' configurations."
199
+ return self._provider_options
200
+
201
+ def set_providers(self, providers=None, provider_options=None):
202
+ """
203
+ Register the input list of execution providers. The underlying session is re-created.
204
+
205
+ :param providers: Optional sequence of providers in order of decreasing
206
+ precedence. Values can either be provider names or tuples of
207
+ (provider name, options dict). If not provided, then all available
208
+ providers are used with the default precedence.
209
+ :param provider_options: Optional sequence of options dicts corresponding
210
+ to the providers listed in 'providers'.
211
+
212
+ 'providers' can contain either names or names and options. When any options
213
+ are given in 'providers', 'provider_options' should not be used.
214
+
215
+ The list of providers is ordered by precedence. For example
216
+ `['CUDAExecutionProvider', 'CPUExecutionProvider']`
217
+ means execute a node using CUDAExecutionProvider if capable,
218
+ otherwise execute using CPUExecutionProvider.
219
+ """
220
+ # recreate the underlying C.InferenceSession
221
+ self._reset_session(providers, provider_options)
222
+
223
+ def disable_fallback(self):
224
+ """
225
+ Disable session.run() fallback mechanism.
226
+ """
227
+ self._enable_fallback = False
228
+
229
+ def enable_fallback(self):
230
+ """
231
+ Enable session.Run() fallback mechanism. If session.Run() fails due to an internal Execution Provider failure,
232
+ reset the Execution Providers enabled for this session.
233
+ If GPU is enabled, fall back to CUDAExecutionProvider.
234
+ otherwise fall back to CPUExecutionProvider.
235
+ """
236
+ self._enable_fallback = True
237
+
238
+ def _validate_input(self, feed_input_names):
239
+ missing_input_names = []
240
+ for input in self._inputs_meta:
241
+ if input.name not in feed_input_names and not input.type.startswith("optional"):
242
+ missing_input_names.append(input.name)
243
+ if missing_input_names:
244
+ raise ValueError(
245
+ f"Required inputs ({missing_input_names}) are missing from input feed ({feed_input_names})."
246
+ )
247
+
248
+ def run(self, output_names, input_feed, run_options=None):
249
+ """
250
+ Compute the predictions.
251
+
252
+ :param output_names: name of the outputs
253
+ :param input_feed: dictionary ``{ input_name: input_value }``
254
+ :param run_options: See :class:`onnxruntime.RunOptions`.
255
+ :return: list of results, every result is either a numpy array,
256
+ a sparse tensor, a list or a dictionary.
257
+
258
+ ::
259
+
260
+ sess.run([output_name], {input_name: x})
261
+ """
262
+ self._validate_input(list(input_feed.keys()))
263
+ if not output_names:
264
+ output_names = [output.name for output in self._outputs_meta]
265
+ try:
266
+ return self._sess.run(output_names, input_feed, run_options)
267
+ except C.EPFail as err:
268
+ if self._enable_fallback:
269
+ print(f"EP Error: {err!s} using {self._providers}")
270
+ print(f"Falling back to {self._fallback_providers} and retrying.")
271
+ self.set_providers(self._fallback_providers)
272
+ # Fallback only once.
273
+ self.disable_fallback()
274
+ return self._sess.run(output_names, input_feed, run_options)
275
+ raise
276
+
277
+ def run_async(self, output_names, input_feed, callback, user_data, run_options=None):
278
+ """
279
+ Compute the predictions asynchronously in a separate cxx thread from ort intra-op threadpool.
280
+
281
+ :param output_names: name of the outputs
282
+ :param input_feed: dictionary ``{ input_name: input_value }``
283
+ :param callback: python function that accept array of results, and a status string on error.
284
+ The callback will be invoked by a cxx thread from ort intra-op threadpool.
285
+ :param run_options: See :class:`onnxruntime.RunOptions`.
286
+
287
+ ::
288
+ class MyData:
289
+ def __init__(self):
290
+ # ...
291
+ def save_results(self, results):
292
+ # ...
293
+
294
+ def callback(results: np.ndarray, user_data: MyData, err: str) -> None:
295
+ if err:
296
+ print (err)
297
+ else:
298
+ # save results to user_data
299
+
300
+ sess.run_async([output_name], {input_name: x}, callback)
301
+ """
302
+ self._validate_input(list(input_feed.keys()))
303
+ if not output_names:
304
+ output_names = [output.name for output in self._outputs_meta]
305
+ return self._sess.run_async(output_names, input_feed, callback, user_data, run_options)
306
+
307
+ def run_with_ort_values(self, output_names, input_dict_ort_values, run_options=None):
308
+ """
309
+ Compute the predictions.
310
+
311
+ :param output_names: name of the outputs
312
+ :param input_dict_ort_values: dictionary ``{ input_name: input_ort_value }``
313
+ See ``OrtValue`` class how to create `OrtValue`
314
+ from numpy array or `SparseTensor`
315
+ :param run_options: See :class:`onnxruntime.RunOptions`.
316
+ :return: an array of `OrtValue`
317
+
318
+ ::
319
+
320
+ sess.run([output_name], {input_name: x})
321
+ """
322
+
323
+ def invoke(sess, output_names, input_dict_ort_values, run_options):
324
+ input_dict = {}
325
+ for n, v in input_dict_ort_values.items():
326
+ input_dict[n] = v._get_c_value()
327
+ result = sess.run_with_ort_values(input_dict, output_names, run_options)
328
+ if not isinstance(result, C.OrtValueVector):
329
+ raise TypeError("run_with_ort_values() must return a instance of type 'OrtValueVector'.")
330
+ ort_values = [OrtValue(v) for v in result]
331
+ return ort_values
332
+
333
+ self._validate_input(list(input_dict_ort_values.keys()))
334
+ if not output_names:
335
+ output_names = [output.name for output in self._outputs_meta]
336
+ try:
337
+ return invoke(self._sess, output_names, input_dict_ort_values, run_options)
338
+ except C.EPFail as err:
339
+ if self._enable_fallback:
340
+ print(f"EP Error: {err!s} using {self._providers}")
341
+ print(f"Falling back to {self._fallback_providers} and retrying.")
342
+ self.set_providers(self._fallback_providers)
343
+ # Fallback only once.
344
+ self.disable_fallback()
345
+ return invoke(self._sess, output_names, input_dict_ort_values, run_options)
346
+ raise
347
+
348
+ def end_profiling(self):
349
+ """
350
+ End profiling and return results in a file.
351
+
352
+ The results are stored in a filename if the option
353
+ :meth:`onnxruntime.SessionOptions.enable_profiling`.
354
+ """
355
+ return self._sess.end_profiling()
356
+
357
+ def get_profiling_start_time_ns(self):
358
+ """
359
+ Return the nanoseconds of profiling's start time
360
+ Comparable to time.monotonic_ns() after Python 3.3
361
+ On some platforms, this timer may not be as precise as nanoseconds
362
+ For instance, on Windows and MacOS, the precision will be ~100ns
363
+ """
364
+ return self._sess.get_profiling_start_time_ns
365
+
366
+ def io_binding(self):
367
+ "Return an onnxruntime.IOBinding object`."
368
+ return IOBinding(self)
369
+
370
+ def run_with_iobinding(self, iobinding, run_options=None):
371
+ """
372
+ Compute the predictions.
373
+
374
+ :param iobinding: the iobinding object that has graph inputs/outputs bind.
375
+ :param run_options: See :class:`onnxruntime.RunOptions`.
376
+ """
377
+ self._sess.run_with_iobinding(iobinding._iobinding, run_options)
378
+
379
+ def get_tuning_results(self):
380
+ return self._sess.get_tuning_results()
381
+
382
+ def set_tuning_results(self, results, *, error_on_invalid=False):
383
+ return self._sess.set_tuning_results(results, error_on_invalid)
384
+
385
+ def run_with_ortvaluevector(self, run_options, feed_names, feeds, fetch_names, fetches, fetch_devices):
386
+ """
387
+ Compute the predictions similar to other run_*() methods but with minimal C++/Python conversion overhead.
388
+
389
+ :param run_options: See :class:`onnxruntime.RunOptions`.
390
+ :param feed_names: list of input names.
391
+ :param feeds: list of input OrtValue.
392
+ :param fetch_names: list of output names.
393
+ :param fetches: list of output OrtValue.
394
+ :param fetch_devices: list of output devices.
395
+ """
396
+ self._sess.run_with_ortvaluevector(run_options, feed_names, feeds, fetch_names, fetches, fetch_devices)
397
+
398
+
399
+ class InferenceSession(Session):
400
+ """
401
+ This is the main class used to run a model.
402
+ """
403
+
404
+ def __init__(
405
+ self,
406
+ path_or_bytes: str | bytes | os.PathLike,
407
+ sess_options: onnxruntime.SessionOptions | None = None,
408
+ providers: Sequence[str | tuple[str, dict[Any, Any]]] | None = None,
409
+ provider_options: Sequence[dict[Any, Any]] | None = None,
410
+ **kwargs,
411
+ ) -> None:
412
+ """
413
+ :param path_or_bytes: Filename or serialized ONNX or ORT format model in a byte string.
414
+ :param sess_options: Session options.
415
+ :param providers: Optional sequence of providers in order of decreasing
416
+ precedence. Values can either be provider names or tuples of
417
+ (provider name, options dict). If not provided, then all available
418
+ providers are used with the default precedence.
419
+ :param provider_options: Optional sequence of options dicts corresponding
420
+ to the providers listed in 'providers'.
421
+
422
+ The model type will be inferred unless explicitly set in the SessionOptions.
423
+ To explicitly set:
424
+
425
+ ::
426
+
427
+ so = onnxruntime.SessionOptions()
428
+ # so.add_session_config_entry('session.load_model_format', 'ONNX') or
429
+ so.add_session_config_entry('session.load_model_format', 'ORT')
430
+
431
+ A file extension of '.ort' will be inferred as an ORT format model.
432
+ All other filenames are assumed to be ONNX format models.
433
+
434
+ 'providers' can contain either names or names and options. When any options
435
+ are given in 'providers', 'provider_options' should not be used.
436
+
437
+ The list of providers is ordered by precedence. For example
438
+ `['CUDAExecutionProvider', 'CPUExecutionProvider']`
439
+ means execute a node using `CUDAExecutionProvider`
440
+ if capable, otherwise execute using `CPUExecutionProvider`.
441
+ """
442
+ super().__init__()
443
+
444
+ if isinstance(path_or_bytes, (str, os.PathLike)):
445
+ self._model_path = os.fspath(path_or_bytes)
446
+ self._model_bytes = None
447
+ elif isinstance(path_or_bytes, bytes):
448
+ self._model_path = None
449
+ self._model_bytes = path_or_bytes # TODO: This is bad as we're holding the memory indefinitely
450
+ else:
451
+ raise TypeError(f"Unable to load from type '{type(path_or_bytes)}'")
452
+
453
+ self._sess_options = sess_options
454
+ self._sess_options_initial = sess_options
455
+ self._enable_fallback = True
456
+ if "read_config_from_model" in kwargs:
457
+ self._read_config_from_model = int(kwargs["read_config_from_model"]) == 1
458
+ else:
459
+ self._read_config_from_model = os.environ.get("ORT_LOAD_CONFIG_FROM_MODEL") == "1"
460
+
461
+ # internal parameters that we don't expect to be used in general so aren't documented
462
+ disabled_optimizers = kwargs.get("disabled_optimizers")
463
+
464
+ try:
465
+ self._create_inference_session(providers, provider_options, disabled_optimizers)
466
+ except (ValueError, RuntimeError) as e:
467
+ if self._enable_fallback:
468
+ try:
469
+ print("*************** EP Error ***************")
470
+ print(f"EP Error {e} when using {providers}")
471
+ print(f"Falling back to {self._fallback_providers} and retrying.")
472
+ print("****************************************")
473
+ self._create_inference_session(self._fallback_providers, None)
474
+ # Fallback only once.
475
+ self.disable_fallback()
476
+ return
477
+ except Exception as fallback_error:
478
+ raise fallback_error from e
479
+ # Fallback is disabled. Raise the original error.
480
+ raise e
481
+
482
+ def _create_inference_session(self, providers, provider_options, disabled_optimizers=None):
483
+ available_providers = C.get_available_providers()
484
+
485
+ # Tensorrt can fall back to CUDA if it's explicitly assigned. All others fall back to CPU.
486
+ if "TensorrtExecutionProvider" in available_providers:
487
+ if (
488
+ providers
489
+ and any(
490
+ provider == "CUDAExecutionProvider"
491
+ or (isinstance(provider, tuple) and provider[0] == "CUDAExecutionProvider")
492
+ for provider in providers
493
+ )
494
+ and any(
495
+ provider == "TensorrtExecutionProvider"
496
+ or (isinstance(provider, tuple) and provider[0] == "TensorrtExecutionProvider")
497
+ for provider in providers
498
+ )
499
+ ):
500
+ self._fallback_providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
501
+ else:
502
+ self._fallback_providers = ["CPUExecutionProvider"]
503
+ # MIGraphX can fall back to ROCM if it's explicitly assigned. All others fall back to CPU.
504
+ elif "MIGraphXExecutionProvider" in available_providers:
505
+ if providers and any(
506
+ provider == "ROCMExecutionProvider"
507
+ or (isinstance(provider, tuple) and provider[0] == "ROCMExecutionProvider")
508
+ for provider in providers
509
+ ):
510
+ self._fallback_providers = ["ROCMExecutionProvider", "CPUExecutionProvider"]
511
+ else:
512
+ self._fallback_providers = ["CPUExecutionProvider"]
513
+ else:
514
+ self._fallback_providers = ["CPUExecutionProvider"]
515
+
516
+ # validate providers and provider_options before other initialization
517
+ providers, provider_options = check_and_normalize_provider_args(
518
+ providers, provider_options, available_providers
519
+ )
520
+
521
+ session_options = self._sess_options if self._sess_options else C.get_default_session_options()
522
+
523
+ self._register_ep_custom_ops(session_options, providers, provider_options, available_providers)
524
+
525
+ if self._model_path:
526
+ sess = C.InferenceSession(session_options, self._model_path, True, self._read_config_from_model)
527
+ else:
528
+ sess = C.InferenceSession(session_options, self._model_bytes, False, self._read_config_from_model)
529
+
530
+ if disabled_optimizers is None:
531
+ disabled_optimizers = set()
532
+ elif not isinstance(disabled_optimizers, set):
533
+ # convert to set. assumes iterable
534
+ disabled_optimizers = set(disabled_optimizers)
535
+
536
+ # initialize the C++ InferenceSession
537
+ sess.initialize_session(providers, provider_options, disabled_optimizers)
538
+
539
+ self._sess = sess
540
+ self._sess_options = self._sess.session_options
541
+ self._inputs_meta = self._sess.inputs_meta
542
+ self._outputs_meta = self._sess.outputs_meta
543
+ self._overridable_initializers = self._sess.overridable_initializers
544
+ self._model_meta = self._sess.model_meta
545
+ self._providers = self._sess.get_providers()
546
+ self._provider_options = self._sess.get_provider_options()
547
+ self._profiling_start_time_ns = self._sess.get_profiling_start_time_ns
548
+
549
+ def _reset_session(self, providers, provider_options):
550
+ "release underlying session object."
551
+ # meta data references session internal structures
552
+ # so they must be set to None to decrement _sess reference count.
553
+ self._sess_options = None
554
+ self._inputs_meta = None
555
+ self._outputs_meta = None
556
+ self._overridable_initializers = None
557
+ self._model_meta = None
558
+ self._providers = None
559
+ self._provider_options = None
560
+ self._profiling_start_time_ns = None
561
+
562
+ # create a new C.InferenceSession
563
+ self._sess = None
564
+ self._sess_options = self._sess_options_initial
565
+ self._create_inference_session(providers, provider_options)
566
+
567
+ def _register_ep_custom_ops(self, session_options, providers, provider_options, available_providers):
568
+ for i in range(len(providers)):
569
+ if providers[i] in available_providers and providers[i] == "TensorrtExecutionProvider":
570
+ C.register_tensorrt_plugins_as_custom_ops(session_options, provider_options[i])
571
+ elif (
572
+ isinstance(providers[i], tuple)
573
+ and providers[i][0] in available_providers
574
+ and providers[i][0] == "TensorrtExecutionProvider"
575
+ ):
576
+ C.register_tensorrt_plugins_as_custom_ops(session_options, providers[i][1])
577
+
578
+
579
+ class IOBinding:
580
+ """
581
+ This class provides API to bind input/output to a specified device, e.g. GPU.
582
+ """
583
+
584
+ def __init__(self, session: Session):
585
+ self._iobinding = C.SessionIOBinding(session._sess)
586
+ self._numpy_obj_references = {}
587
+
588
+ def bind_cpu_input(self, name, arr_on_cpu):
589
+ """
590
+ bind an input to array on CPU
591
+ :param name: input name
592
+ :param arr_on_cpu: input values as a python array on CPU
593
+ """
594
+ # Hold a reference to the numpy object as the bound OrtValue is backed
595
+ # directly by the data buffer of the numpy object and so the numpy object
596
+ # must be around until this IOBinding instance is around
597
+ self._numpy_obj_references[name] = arr_on_cpu
598
+ self._iobinding.bind_input(name, arr_on_cpu)
599
+
600
+ def bind_input(self, name, device_type, device_id, element_type, shape, buffer_ptr):
601
+ """
602
+ :param name: input name
603
+ :param device_type: e.g. cpu, cuda, cann
604
+ :param device_id: device id, e.g. 0
605
+ :param element_type: input element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
606
+ :param shape: input shape
607
+ :param buffer_ptr: memory pointer to input data
608
+ """
609
+ self._iobinding.bind_input(
610
+ name,
611
+ C.OrtDevice(
612
+ get_ort_device_type(device_type, device_id),
613
+ C.OrtDevice.default_memory(),
614
+ device_id,
615
+ ),
616
+ element_type,
617
+ shape,
618
+ buffer_ptr,
619
+ )
620
+
621
+ def bind_ortvalue_input(self, name, ortvalue):
622
+ """
623
+ :param name: input name
624
+ :param ortvalue: OrtValue instance to bind
625
+ """
626
+ self._iobinding.bind_ortvalue_input(name, ortvalue._ortvalue)
627
+
628
+ def synchronize_inputs(self):
629
+ self._iobinding.synchronize_inputs()
630
+
631
+ def bind_output(
632
+ self,
633
+ name,
634
+ device_type="cpu",
635
+ device_id=0,
636
+ element_type=None,
637
+ shape=None,
638
+ buffer_ptr=None,
639
+ ):
640
+ """
641
+ :param name: output name
642
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
643
+ :param device_id: device id, e.g. 0
644
+ :param element_type: output element type. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16)
645
+ :param shape: output shape
646
+ :param buffer_ptr: memory pointer to output data
647
+ """
648
+
649
+ # Follow the `if` path when the user has not provided any pre-allocated buffer but still
650
+ # would like to bind an output to a specific device (e.g. cuda).
651
+ # Pre-allocating an output buffer may not be an option for the user as :
652
+ # (1) They may not want to use a custom allocator specific to the device they want to bind the output to,
653
+ # in which case ORT will allocate the memory for the user
654
+ # (2) The output has a dynamic shape and hence the size of the buffer may not be fixed across runs
655
+ if buffer_ptr is None:
656
+ self._iobinding.bind_output(
657
+ name,
658
+ C.OrtDevice(
659
+ get_ort_device_type(device_type, device_id),
660
+ C.OrtDevice.default_memory(),
661
+ device_id,
662
+ ),
663
+ )
664
+ else:
665
+ if element_type is None or shape is None:
666
+ raise ValueError("`element_type` and `shape` are to be provided if pre-allocated memory is provided")
667
+ self._iobinding.bind_output(
668
+ name,
669
+ C.OrtDevice(
670
+ get_ort_device_type(device_type, device_id),
671
+ C.OrtDevice.default_memory(),
672
+ device_id,
673
+ ),
674
+ element_type,
675
+ shape,
676
+ buffer_ptr,
677
+ )
678
+
679
+ def bind_ortvalue_output(self, name, ortvalue):
680
+ """
681
+ :param name: output name
682
+ :param ortvalue: OrtValue instance to bind
683
+ """
684
+ self._iobinding.bind_ortvalue_output(name, ortvalue._ortvalue)
685
+
686
+ def synchronize_outputs(self):
687
+ self._iobinding.synchronize_outputs()
688
+
689
+ def get_outputs(self):
690
+ """
691
+ Returns the output OrtValues from the Run() that preceded the call.
692
+ The data buffer of the obtained OrtValues may not reside on CPU memory
693
+ """
694
+ outputs = self._iobinding.get_outputs()
695
+ if not isinstance(outputs, C.OrtValueVector):
696
+ raise TypeError("get_outputs() must return an instance of type 'OrtValueVector'.")
697
+ return [OrtValue(ortvalue) for ortvalue in outputs]
698
+
699
+ def get_outputs_as_ortvaluevector(self):
700
+ return self._iobinding.get_outputs()
701
+
702
+ def copy_outputs_to_cpu(self):
703
+ """Copy output contents to CPU."""
704
+ return self._iobinding.copy_outputs_to_cpu()
705
+
706
+ def clear_binding_inputs(self):
707
+ self._iobinding.clear_binding_inputs()
708
+
709
+ def clear_binding_outputs(self):
710
+ self._iobinding.clear_binding_outputs()
711
+
712
+
713
+ class OrtValue:
714
+ """
715
+ A data structure that supports all ONNX data formats (tensors and non-tensors) that allows users
716
+ to place the data backing these on a device, for example, on a CUDA supported device.
717
+ This class provides APIs to construct and deal with OrtValues.
718
+ """
719
+
720
+ def __init__(self, ortvalue, numpy_obj=None):
721
+ if isinstance(ortvalue, C.OrtValue):
722
+ self._ortvalue = ortvalue
723
+ # Hold a ref count to the numpy object if the OrtValue is backed directly
724
+ # by its data buffer so that it isn't destroyed when the OrtValue is in use
725
+ self._numpy_obj = numpy_obj
726
+ else:
727
+ # An end user won't hit this error
728
+ raise ValueError(
729
+ "`Provided ortvalue` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtValue`"
730
+ )
731
+
732
+ def _get_c_value(self):
733
+ return self._ortvalue
734
+
735
+ @staticmethod
736
+ def ortvalue_from_numpy(numpy_obj, device_type="cpu", device_id=0):
737
+ """
738
+ Factory method to construct an OrtValue (which holds a Tensor) from a given Numpy object
739
+ A copy of the data in the Numpy object is held by the OrtValue only if the device is NOT cpu
740
+
741
+ :param numpy_obj: The Numpy object to construct the OrtValue from
742
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
743
+ :param device_id: device id, e.g. 0
744
+ """
745
+ # Hold a reference to the numpy object (if device_type is 'cpu') as the OrtValue
746
+ # is backed directly by the data buffer of the numpy object and so the numpy object
747
+ # must be around until this OrtValue instance is around
748
+ return OrtValue(
749
+ C.OrtValue.ortvalue_from_numpy(
750
+ numpy_obj,
751
+ C.OrtDevice(
752
+ get_ort_device_type(device_type, device_id),
753
+ C.OrtDevice.default_memory(),
754
+ device_id,
755
+ ),
756
+ ),
757
+ numpy_obj if device_type.lower() == "cpu" else None,
758
+ )
759
+
760
+ @staticmethod
761
+ def ortvalue_from_numpy_with_onnx_type(data, onnx_element_type: int):
762
+ """
763
+ This method creates an instance of OrtValue on top of the numpy array.
764
+ No data copy is made and the lifespan of the resulting OrtValue should never
765
+ exceed the lifespan of bytes object. The API attempts to reinterpret
766
+ the data type which is expected to be the same size. This is useful
767
+ when we want to use an ONNX data type that is not supported by numpy.
768
+
769
+ :param data: numpy.ndarray.
770
+ :param onnx_elemenet_type: a valid onnx TensorProto::DataType enum value
771
+ """
772
+ return OrtValue(C.OrtValue.ortvalue_from_numpy_with_onnx_type(data, onnx_element_type), data)
773
+
774
+ @staticmethod
775
+ def ortvalue_from_shape_and_type(shape, element_type, device_type: str = "cpu", device_id: int = 0):
776
+ """
777
+ Factory method to construct an OrtValue (which holds a Tensor) from given shape and element_type
778
+
779
+ :param shape: List of integers indicating the shape of the OrtValue
780
+ :param element_type: The data type of the elements. It can be either numpy type (like numpy.float32) or an integer for onnx type (like onnx.TensorProto.BFLOAT16).
781
+ :param device_type: e.g. cpu, cuda, cann, cpu by default
782
+ :param device_id: device id, e.g. 0
783
+ """
784
+ # Integer for onnx element type (see https://onnx.ai/onnx/api/mapping.html).
785
+ # This is helpful for some data type (like TensorProto.BFLOAT16) that is not available in numpy.
786
+ if isinstance(element_type, int):
787
+ return OrtValue(
788
+ C.OrtValue.ortvalue_from_shape_and_onnx_type(
789
+ shape,
790
+ element_type,
791
+ C.OrtDevice(
792
+ get_ort_device_type(device_type, device_id),
793
+ C.OrtDevice.default_memory(),
794
+ device_id,
795
+ ),
796
+ )
797
+ )
798
+
799
+ return OrtValue(
800
+ C.OrtValue.ortvalue_from_shape_and_type(
801
+ shape,
802
+ element_type,
803
+ C.OrtDevice(
804
+ get_ort_device_type(device_type, device_id),
805
+ C.OrtDevice.default_memory(),
806
+ device_id,
807
+ ),
808
+ )
809
+ )
810
+
811
+ @staticmethod
812
+ def ort_value_from_sparse_tensor(sparse_tensor):
813
+ """
814
+ The function will construct an OrtValue instance from a valid SparseTensor
815
+ The new instance of OrtValue will assume the ownership of sparse_tensor
816
+ """
817
+ return OrtValue(C.OrtValue.ort_value_from_sparse_tensor(sparse_tensor._get_c_tensor()))
818
+
819
+ def as_sparse_tensor(self):
820
+ """
821
+ The function will return SparseTensor contained in this OrtValue
822
+ """
823
+ return SparseTensor(self._ortvalue.as_sparse_tensor())
824
+
825
+ def data_ptr(self):
826
+ """
827
+ Returns the address of the first element in the OrtValue's data buffer
828
+ """
829
+ return self._ortvalue.data_ptr()
830
+
831
+ def device_name(self):
832
+ """
833
+ Returns the name of the device where the OrtValue's data buffer resides e.g. cpu, cuda, cann
834
+ """
835
+ return self._ortvalue.device_name().lower()
836
+
837
+ def shape(self):
838
+ """
839
+ Returns the shape of the data in the OrtValue
840
+ """
841
+ return self._ortvalue.shape()
842
+
843
+ def data_type(self):
844
+ """
845
+ Returns the data type of the data in the OrtValue
846
+ """
847
+ return self._ortvalue.data_type()
848
+
849
+ def element_type(self):
850
+ """
851
+ Returns the proto type of the data in the OrtValue
852
+ if the OrtValue is a tensor.
853
+ """
854
+ return self._ortvalue.element_type()
855
+
856
+ def has_value(self):
857
+ """
858
+ Returns True if the OrtValue corresponding to an
859
+ optional type contains data, else returns False
860
+ """
861
+ return self._ortvalue.has_value()
862
+
863
+ def is_tensor(self):
864
+ """
865
+ Returns True if the OrtValue contains a Tensor, else returns False
866
+ """
867
+ return self._ortvalue.is_tensor()
868
+
869
+ def is_sparse_tensor(self):
870
+ """
871
+ Returns True if the OrtValue contains a SparseTensor, else returns False
872
+ """
873
+ return self._ortvalue.is_sparse_tensor()
874
+
875
+ def is_tensor_sequence(self):
876
+ """
877
+ Returns True if the OrtValue contains a Tensor Sequence, else returns False
878
+ """
879
+ return self._ortvalue.is_tensor_sequence()
880
+
881
+ def numpy(self):
882
+ """
883
+ Returns a Numpy object from the OrtValue.
884
+ Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
885
+ Use accessors to gain a reference to non-Tensor objects such as SparseTensor
886
+ """
887
+ return self._ortvalue.numpy()
888
+
889
+ def update_inplace(self, np_arr):
890
+ """
891
+ Update the OrtValue in place with a new Numpy array. The numpy contents
892
+ are copied over to the device memory backing the OrtValue. It can be used
893
+ to update the input valuess for an InferenceSession with CUDA graph
894
+ enabled or other scenarios where the OrtValue needs to be updated while
895
+ the memory address can not be changed.
896
+ """
897
+ self._ortvalue.update_inplace(np_arr)
898
+
899
+
900
+ class OrtDevice:
901
+ """
902
+ A data structure that exposes the underlying C++ OrtDevice
903
+ """
904
+
905
+ def __init__(self, c_ort_device):
906
+ """
907
+ Internal constructor
908
+ """
909
+ if isinstance(c_ort_device, C.OrtDevice):
910
+ self._ort_device = c_ort_device
911
+ else:
912
+ raise ValueError(
913
+ "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.OrtDevice`"
914
+ )
915
+
916
+ def _get_c_device(self):
917
+ """
918
+ Internal accessor to underlying object
919
+ """
920
+ return self._ort_device
921
+
922
+ @staticmethod
923
+ def make(ort_device_name, device_id):
924
+ return OrtDevice(
925
+ C.OrtDevice(
926
+ get_ort_device_type(ort_device_name, device_id),
927
+ C.OrtDevice.default_memory(),
928
+ device_id,
929
+ )
930
+ )
931
+
932
+ def device_id(self):
933
+ return self._ort_device.device_id()
934
+
935
+ def device_type(self):
936
+ return self._ort_device.device_type()
937
+
938
+
939
+ class SparseTensor:
940
+ """
941
+ A data structure that project the C++ SparseTensor object
942
+ The class provides API to work with the object.
943
+ Depending on the format, the class will hold more than one buffer
944
+ depending on the format
945
+ """
946
+
947
+ def __init__(self, sparse_tensor):
948
+ """
949
+ Internal constructor
950
+ """
951
+ if isinstance(sparse_tensor, C.SparseTensor):
952
+ self._tensor = sparse_tensor
953
+ else:
954
+ # An end user won't hit this error
955
+ raise ValueError(
956
+ "`Provided object` needs to be of type `onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`"
957
+ )
958
+
959
+ def _get_c_tensor(self):
960
+ return self._tensor
961
+
962
+ @staticmethod
963
+ def sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device):
964
+ """
965
+ Factory method to construct a SparseTensor in COO format from given arguments
966
+
967
+ :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the sparse tensor
968
+ must be on cpu memory
969
+ :param values: a homogeneous, contiguous 1-D numpy array that contains non-zero elements of the tensor
970
+ of a type.
971
+ :param coo_indices: contiguous numpy array(int64) that contains COO indices for the tensor. coo_indices may
972
+ have a 1-D shape when it contains a linear index of non-zero values and its length must be equal to
973
+ that of the values. It can also be of 2-D shape, in which has it contains pairs of coordinates for
974
+ each of the nnz values and its length must be exactly twice of the values length.
975
+ :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
976
+ suppored for non-numeric data types.
977
+
978
+ For primitive types, the method will map values and coo_indices arrays into native memory and will use
979
+ them as backing storage. It will increment the reference count for numpy arrays and it will decrement it
980
+ on GC. The buffers may reside in any storage either CPU or GPU.
981
+ For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
982
+ on other devices and their memory can not be mapped.
983
+ """
984
+ return SparseTensor(
985
+ C.SparseTensor.sparse_coo_from_numpy(dense_shape, values, coo_indices, ort_device._get_c_device())
986
+ )
987
+
988
+ @staticmethod
989
+ def sparse_csr_from_numpy(dense_shape, values, inner_indices, outer_indices, ort_device):
990
+ """
991
+ Factory method to construct a SparseTensor in CSR format from given arguments
992
+
993
+ :param dense_shape: 1-D numpy array(int64) or a python list that contains a dense_shape of the
994
+ sparse tensor (rows, cols) must be on cpu memory
995
+ :param values: a contiguous, homogeneous 1-D numpy array that contains non-zero elements of the tensor
996
+ of a type.
997
+ :param inner_indices: contiguous 1-D numpy array(int64) that contains CSR inner indices for the tensor.
998
+ Its length must be equal to that of the values.
999
+ :param outer_indices: contiguous 1-D numpy array(int64) that contains CSR outer indices for the tensor.
1000
+ Its length must be equal to the number of rows + 1.
1001
+ :param ort_device: - describes the backing memory owned by the supplied nummpy arrays. Only CPU memory is
1002
+ suppored for non-numeric data types.
1003
+
1004
+ For primitive types, the method will map values and indices arrays into native memory and will use them as
1005
+ backing storage. It will increment the reference count and it will decrement then count when it is GCed.
1006
+ The buffers may reside in any storage either CPU or GPU.
1007
+ For strings and objects, it will create a copy of the arrays in CPU memory as ORT does not support those
1008
+ on other devices and their memory can not be mapped.
1009
+ """
1010
+ return SparseTensor(
1011
+ C.SparseTensor.sparse_csr_from_numpy(
1012
+ dense_shape,
1013
+ values,
1014
+ inner_indices,
1015
+ outer_indices,
1016
+ ort_device._get_c_device(),
1017
+ )
1018
+ )
1019
+
1020
+ def values(self):
1021
+ """
1022
+ The method returns a numpy array that is backed by the native memory
1023
+ if the data type is numeric. Otherwise, the returned numpy array that contains
1024
+ copies of the strings.
1025
+ """
1026
+ return self._tensor.values()
1027
+
1028
+ def as_coo_view(self):
1029
+ """
1030
+ The method will return coo representation of the sparse tensor which will enable
1031
+ querying COO indices. If the instance did not contain COO format, it would throw.
1032
+ You can query coo indices as:
1033
+
1034
+ ::
1035
+
1036
+ coo_indices = sparse_tensor.as_coo_view().indices()
1037
+
1038
+ which will return a numpy array that is backed by the native memory.
1039
+ """
1040
+ return self._tensor.get_coo_data()
1041
+
1042
+ def as_csrc_view(self):
1043
+ """
1044
+ The method will return CSR(C) representation of the sparse tensor which will enable
1045
+ querying CRS(C) indices. If the instance dit not contain CSR(C) format, it would throw.
1046
+ You can query indices as:
1047
+
1048
+ ::
1049
+
1050
+ inner_ndices = sparse_tensor.as_csrc_view().inner()
1051
+ outer_ndices = sparse_tensor.as_csrc_view().outer()
1052
+
1053
+ returning numpy arrays backed by the native memory.
1054
+ """
1055
+ return self._tensor.get_csrc_data()
1056
+
1057
+ def as_blocksparse_view(self):
1058
+ """
1059
+ The method will return coo representation of the sparse tensor which will enable
1060
+ querying BlockSparse indices. If the instance did not contain BlockSparse format, it would throw.
1061
+ You can query coo indices as:
1062
+
1063
+ ::
1064
+
1065
+ block_sparse_indices = sparse_tensor.as_blocksparse_view().indices()
1066
+
1067
+ which will return a numpy array that is backed by the native memory
1068
+ """
1069
+ return self._tensor.get_blocksparse_data()
1070
+
1071
+ def to_cuda(self, ort_device):
1072
+ """
1073
+ Returns a copy of this instance on the specified cuda device
1074
+
1075
+ :param ort_device: with name 'cuda' and valid gpu device id
1076
+
1077
+ The method will throw if:
1078
+
1079
+ - this instance contains strings
1080
+ - this instance is already on GPU. Cross GPU copy is not supported
1081
+ - CUDA is not present in this build
1082
+ - if the specified device is not valid
1083
+ """
1084
+ return SparseTensor(self._tensor.to_cuda(ort_device._get_c_device()))
1085
+
1086
+ def format(self):
1087
+ """
1088
+ Returns a OrtSparseFormat enumeration
1089
+ """
1090
+ return self._tensor.format
1091
+
1092
+ def dense_shape(self):
1093
+ """
1094
+ Returns a numpy array(int64) containing a dense shape of a sparse tensor
1095
+ """
1096
+ return self._tensor.dense_shape()
1097
+
1098
+ def data_type(self):
1099
+ """
1100
+ Returns a string data type of the data in the OrtValue
1101
+ """
1102
+ return self._tensor.data_type()
1103
+
1104
+ def device_name(self):
1105
+ """
1106
+ Returns the name of the device where the SparseTensor data buffers reside e.g. cpu, cuda
1107
+ """
1108
+ return self._tensor.device_name().lower()