onnxruntime/csharp/src/Microsoft.ML.OnnxRuntime/SessionOptions.shared.cs

936 lines
38 KiB
C#
Raw Normal View History

2018-11-20 00:48:22 +00:00
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
2018-11-23 04:56:43 +00:00
2018-11-20 00:48:22 +00:00
namespace Microsoft.ML.OnnxRuntime
{
/// <summary>
/// Graph optimization level to use with SessionOptions
/// [https://github.com/microsoft/onnxruntime/blob/main/docs/ONNX_Runtime_Graph_Optimizations.md]
/// </summary>
public enum GraphOptimizationLevel
{
ORT_DISABLE_ALL = 0,
ORT_ENABLE_BASIC = 1,
ORT_ENABLE_EXTENDED = 2,
ORT_ENABLE_ALL = 99
}
/// <summary>
/// Controls whether you want to execute operators in the graph sequentially or in parallel.
/// Usually when the model has many branches, setting this option to ExecutionMode.ORT_PARALLEL
/// will give you better performance.
/// See [ONNX_Runtime_Perf_Tuning.md] for more details.
/// </summary>
public enum ExecutionMode
{
ORT_SEQUENTIAL = 0,
ORT_PARALLEL = 1,
}
/// <summary>
/// Holds the options for creating an InferenceSession
/// It forces the instantiation of the OrtEnv singleton.
/// </summary>
public class SessionOptions : SafeHandle
2018-11-20 00:48:22 +00:00
{
// Delay-loaded CUDA or cuDNN DLLs. Currently, delayload is disabled. See cmake/CMakeLists.txt for more information.
private static string[] cudaDelayLoadedLibs = { };
private static string[] trtDelayLoadedLibs = { };
2018-11-20 00:48:22 +00:00
#region Constructor and Factory methods
/// <summary>
/// Constructs an empty SessionOptions
/// </summary>
2018-11-20 00:48:22 +00:00
public SessionOptions()
: base(IntPtr.Zero, true)
2018-11-20 00:48:22 +00:00
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionOptions(out handle));
// Instantiate the OrtEnv singleton if not already done.
OrtEnv.Instance();
2018-11-20 00:48:22 +00:00
}
/// <summary>
/// A helper method to construct a SessionOptions object for CUDA execution.
/// Use only if CUDA is installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId"></param>
/// <returns>A SessionsOptions() object configured for execution on deviceId</returns>
public static SessionOptions MakeSessionOptionWithCudaProvider(int deviceId = 0)
{
CheckCudaExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_CUDA(deviceId);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
/// A helper method to construct a SessionOptions object for CUDA execution provider.
/// Use only if CUDA is installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="cudaProviderOptions">CUDA EP provider options</param>
/// <returns>A SessionsOptions() object configured for execution on provider options</returns>
public static SessionOptions MakeSessionOptionWithCudaProvider(OrtCUDAProviderOptions cudaProviderOptions)
{
CheckCudaExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_CUDA(cudaProviderOptions);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
/// A helper method to construct a SessionOptions object for TensorRT execution.
/// Use only if CUDA/TensorRT are installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId"></param>
/// <returns>A SessionsOptions() object configured for execution on deviceId</returns>
public static SessionOptions MakeSessionOptionWithTensorrtProvider(int deviceId = 0)
{
CheckTensorrtExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_Tensorrt(deviceId);
options.AppendExecutionProvider_CUDA(deviceId);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
/// A helper method to construct a SessionOptions object for TensorRT execution provider.
/// Use only if CUDA/TensorRT are installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="trtProviderOptions">TensorRT EP provider options</param>
/// <returns>A SessionsOptions() object configured for execution on provider options</returns>
public static SessionOptions MakeSessionOptionWithTensorrtProvider(OrtTensorRTProviderOptions trtProviderOptions)
{
CheckTensorrtExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
// Make sure that CUDA EP uses the same device id as TensorRT EP.
options.AppendExecutionProvider_Tensorrt(trtProviderOptions);
options.AppendExecutionProvider_CUDA(trtProviderOptions.GetDeviceId());
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
[TVM EP] Rename Standalone TVM (STVM) Execution Provider to TVM EP (#10260) * update java API for STVM EP. Issue is from PR#10019 * use_stvm -> use_tvm * rename stvm worktree * STVMAllocator -> TVMAllocator * StvmExecutionProviderInfo -> TvmExecutionProviderInfo * stvm -> tvm for cpu_targets. resolve onnxruntime::tvm and origin tvm namespaces conflict * STVMRunner -> TVMRunner * StvmExecutionProvider -> TvmExecutionProvider * tvm::env_vars * StvmProviderFactory -> TvmProviderFactory * rename factory funcs * StvmCPUDataTransfer -> TvmCPUDataTransfer * small clean * STVMFuncState -> TVMFuncState * USE_TVM -> NUPHAR_USE_TVM * USE_STVM -> USE_TVM * python API: providers.stvm -> providers.tvm. clean TVM_EP.md * clean build scripts #1 * clean build scripts, java frontend and others #2 * once more clean #3 * fix build of nuphar tvm test * final transfer stvm namespace to onnxruntime::tvm * rename stvm->tvm * NUPHAR_USE_TVM -> USE_NUPHAR_TVM * small fixes for correct CI tests * clean after rebase. Last renaming stvm to tvm, separate TVM and Nuphar in cmake and build files * update CUDA support for TVM EP * roll back CudaNN home check * ERROR for not positive input shape dimension instead of WARNING * update documentation for CUDA * small corrections after review * update GPU description * update GPU description * misprints were fixed * cleaned up error msgs Co-authored-by: Valery Chernov <valery.chernov@deelvin.com> Co-authored-by: KJlaccHoeUM9l <wotpricol@mail.ru> Co-authored-by: Thierry Moreau <tmoreau@octoml.ai>
2022-02-15 09:21:02 +00:00
/// A helper method to construct a SessionOptions object for TVM execution.
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="settings">settings string, comprises of comma separated key:value pairs. default is empty</param>
[TVM EP] Rename Standalone TVM (STVM) Execution Provider to TVM EP (#10260) * update java API for STVM EP. Issue is from PR#10019 * use_stvm -> use_tvm * rename stvm worktree * STVMAllocator -> TVMAllocator * StvmExecutionProviderInfo -> TvmExecutionProviderInfo * stvm -> tvm for cpu_targets. resolve onnxruntime::tvm and origin tvm namespaces conflict * STVMRunner -> TVMRunner * StvmExecutionProvider -> TvmExecutionProvider * tvm::env_vars * StvmProviderFactory -> TvmProviderFactory * rename factory funcs * StvmCPUDataTransfer -> TvmCPUDataTransfer * small clean * STVMFuncState -> TVMFuncState * USE_TVM -> NUPHAR_USE_TVM * USE_STVM -> USE_TVM * python API: providers.stvm -> providers.tvm. clean TVM_EP.md * clean build scripts #1 * clean build scripts, java frontend and others #2 * once more clean #3 * fix build of nuphar tvm test * final transfer stvm namespace to onnxruntime::tvm * rename stvm->tvm * NUPHAR_USE_TVM -> USE_NUPHAR_TVM * small fixes for correct CI tests * clean after rebase. Last renaming stvm to tvm, separate TVM and Nuphar in cmake and build files * update CUDA support for TVM EP * roll back CudaNN home check * ERROR for not positive input shape dimension instead of WARNING * update documentation for CUDA * small corrections after review * update GPU description * update GPU description * misprints were fixed * cleaned up error msgs Co-authored-by: Valery Chernov <valery.chernov@deelvin.com> Co-authored-by: KJlaccHoeUM9l <wotpricol@mail.ru> Co-authored-by: Thierry Moreau <tmoreau@octoml.ai>
2022-02-15 09:21:02 +00:00
/// <returns>A SessionsOptions() object configured for execution with TVM</returns>
public static SessionOptions MakeSessionOptionWithTvmProvider(String settings = "")
{
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_Tvm(settings);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
/// A helper method to construct a SessionOptions object for ROCM execution.
/// Use only if ROCM is installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">Device Id</param>
/// <returns>A SessionsOptions() object configured for execution on deviceId</returns>
public static SessionOptions MakeSessionOptionWithRocmProvider(int deviceId = 0)
{
CheckRocmExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_ROCm(deviceId);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
/// <summary>
/// A helper method to construct a SessionOptions object for ROCm execution provider.
/// Use only if ROCm is installed and you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="rocmProviderOptions">ROCm EP provider options</param>
/// <returns>A SessionsOptions() object configured for execution on provider options</returns>
public static SessionOptions MakeSessionOptionWithRocmProvider(OrtROCMProviderOptions rocmProviderOptions)
{
CheckRocmExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
try
{
options.AppendExecutionProvider_ROCm(rocmProviderOptions);
return options;
}
catch (Exception)
{
options.Dispose();
throw;
}
}
#endregion
#region ExecutionProviderAppends
/// <summary>
/// Appends CPU EP to a list of available execution providers for the session.
/// </summary>
/// <param name="useArena">1 - use arena, 0 - do not use arena</param>
public void AppendExecutionProvider_CPU(int useArena = 1)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_CPU(handle, useArena));
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="useArena">1 - use allocation arena, 0 - otherwise</param>
public void AppendExecutionProvider_Dnnl(int useArena = 1)
{
#if __MOBILE__
throw new NotSupportedException("The DNNL Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_Dnnl(handle, useArena));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">integer device ID</param>
public void AppendExecutionProvider_CUDA(int deviceId = 0)
{
#if __MOBILE__
throw new NotSupportedException("The CUDA Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_CUDA(handle, deviceId));
#endif
}
/// <summary>
/// Append a CUDA EP instance (based on specified configuration) to the SessionOptions instance.
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="cudaProviderOptions">CUDA EP provider options</param>
public void AppendExecutionProvider_CUDA(OrtCUDAProviderOptions cudaProviderOptions)
{
#if __MOBILE__
throw new NotSupportedException("The CUDA Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.SessionOptionsAppendExecutionProvider_CUDA_V2(handle, cudaProviderOptions.Handle));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">device identification</param>
public void AppendExecutionProvider_DML(int deviceId = 0)
{
#if __MOBILE__
throw new NotSupportedException("The DML Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_DML(handle, deviceId));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">device identification, default empty string</param>
OpenVINO EP v2.0 (#3585) * Added FP16 transformations * Revert "Added CMAKE_BUILD_TYPE to make building dynamic" This reverts commit d3e17af1af655cfdc4d2fec33f52055caa525e85. * Added FP16 transformations for FP16 builds * Backend logic cleanup Cleans the backend(intel_graph.*) code in the following ways:- 1. Minimize global usage: Since all the IR graphs need to be re-generated on every Infer, it is bad practice to rely on globals for their saving and usage as there would be multiple readers and writers to the same global variable leading to incorrect usages or contentions. This change replaces globals with locals where possible. This change also fixes an existing bug with due to incorrect global usage. 2. Remove all unused functions. 3. Remove all unused headers and prepocessor directives. * removed commented out code * Disabled default optimization for Intel EP Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Fix missed plugins.xml for python bindings * Fixed the build after latest master changes Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Disabled unsupported ops for accelerators Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Added some more disabled ops Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Added environment variable to enable debugging Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Added more debug statements Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Fixed unsupported ops list for GPU and VPU Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Fixed unsqueeze unit tests Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Added error message to the status Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Overwrite Model proto with shape info from data Overwrites the shape info of Model proto with the shape from actual input data. Needed for inferring models with Dynamic shapes. * Removed print statement and disabled where op Signed-off-by: suryasidd <surya.siddharth.pemmaraju@intel.com> * Disabled Reshape with Empty initializer * Added more debug statements for 1P * Don't allow 1D inputs with symbol for dimension * Disabled some 3rd phase ops * Disabled split and added zero dimension check for OutputDefs * Cleanup zero dimensionality check * Added different data type check for inputs and initializers * Added conditions for Mod, Cast and Pad * Removed unused variable * Disabled scan and added conditions for squeeze * Added changes for fixing all C++ unit tests * Implements Backend Manager class for caching Backend Manager provides a layer of indirection between EP interface and OV backend that provides caching services for models with symbolic dims in input shapes. * clean up commented blocks * clang-formatting * Read I/O type info from ModleProto Read the tensor element type information from ModelProto object, as FusedNode is no longer available. * code cleanup * clang-formatting * Added print statement for jenkins * Disabled some python tests * Changed the path of convert fp32 to fp16 hpp * Added conditions for BatchNorm in GetCapability * Fixed failed tests * Revert "Added conditions for BatchNorm in GetCapability" This reverts commit c3c28c3b00d27892c42546b35dacdd807a48ee90. * Added Intel to onnxruntime backends * pick up vars set by OV package setupvars.sh * Added conditions for Identity * remove a few cout prints * Added conditions for GPU_FP32 unit tests * Revert "pick up vars set by OV package setupvars.sh" This reverts commit 8199e029c03eae21a1a7ef6bfdc93d00e5d0198b. * Commented out fatal message for protobuf * Might need to be removed * Add interface class for current backend * moved common logic to base class * simplified cpu backend * Removed unused headers * use vectors to save i/o tensors for windows compatibility * move utils fxns to backend_utils namespace * rename ov_backend to ibackend * Factory pattern for backend creation * rename CPU backend to Basic backend * renamed to vad-M and added to factory list * Added conditions for VPU * Added print statements * Changed the logic for checking for symbolic shapes * Modified logic for zero dimension check * Removed VPU single dimension condition * Removed comments * Modified logic in DimensionCheck method * Remove legacy OpenVINO EP Remove all the legacy code for OpenVINO EP. UEP code will take its place going forward. This change does NOT remove OVEP files in the following areas asa they will be reused by UEP:- 1. Documentation: All .md files 2. Docker releated files 3. Python bindings 4. Java bindings 5. C# bindings 6. ORT Server 7. CI pipeline setup files * Rename Intel EP to OpenVINO EP * Added unique names to the subgraphs * Removed subgraphs with only constant inputs * Modified subgraph partitioning algorithm to remove const input subgraphs * Apply suggestion to onnxruntime/core/providers/openvino/openvino_execution_provider.cc * Tracking output names to fix the output order bug * Changed output names to a unordered map * Modified logic to check for symbolic input shapes * Fixed a bug in Reshape check * Added empty model path to Model constructor * Made necessary changes to cmake to build from the binary package * Changed INTEL_CVSDK_DIR to INTEL_OPENVINO_DIR * Enable dyn device selection with C++ API * Added Round operator to unsupported list * Modified subgraph partition logic for MYRIAD * Removed supported ops from the list * Enable dyn dev selection in Py API's * Add documentation for dynamic device selection * Use MYRIAD || HDDL instead of VPU * Removed temporary cast of Int64 to FP32 * Disabled unit Tests for CPU_FP32 and GPU_FP32 * Removed default "CPU" from unit tests to allow overriding * Removed ops Concat, Squeeze, Unsqueeze from unsupported list * Get the device id from info * Removed overwriting device_id and precision * Enabled ConvTranspose and EyeLike * Reordered unsupported ops in alphabetical order * Fixed syntax error * Fixed syntax error * Code clean-up: Handle exceptions, logs and formatting Code formatted according to ORT coding guidelines. * remove debug print from pybind code * updated docs with ops and models * formatting prints * Added default values for c and j for openvino * Overriding the values set for c and j to be 1 * BACKEND_OPENVINO should be empty if openvino is not in build * Overriding c value with default for perftest * fix VAD-M device string bug * Add IE error details to exceptions * Use IE specific device names in EP * Add VAD-F (FPGA) device support * Removed unecessary libraries from whl package * Code changes for Windows compatibility * Add VAD-F option to python API * [revert before merge] cmake changes for RC * Enable Windows build in CMake * Unset macro OPTIONAL for windows builds inference_engine.hpp's include chain defines a macro 'OPTIONAL' which conflicts with onnx project's headers when using MSVC. So would need to explictly unset it for MSVC. * Use a single copy of plugin/IE::Core Defined as a static member in Backend manager * Remove restriction of single subgraphs for myriad * Passed subgraph name to Backend to enhance log statements * Disabled zero dimension conditions * Disabled concat to remove zero dims * Enabled building ngraph as part of ORT * Removed serializing and added versioning * Fix CPU_FP32 unit tests * Removed unecessary condition * add ngraph.so.0.0 to .whl * Check for zero dimensions only for inputs and outputs * Restrict loading only 10 subgraphs on myriad * Build ngraph.dll within UEP. Doesn't link yet * Rename Linux included libngraph.so to libovep_ngraph.so Renames locally built libngraph.so containing ONNX importer to libovep_ngraph.so in order to avoid linkage conflicts with libngraph.so supplied by OpenVINO binary installer. Applies only for Linux builds. * use output_name cmake properties for lib name * fix .so name format in lib_name.patch * CMake code cleanup * Rename WIN32 included ngraph.dll to ovep_ngraph.dll To avoid conflict with ngraph.dll distributed by openvino. * Added myriad config for networks without 4 dimensions * Loading the 10 max clusters for inference on myriad * Refactor code and add Batching support Encapsulate subgraph settings into context structs. Add batching support for completely supported models. * Disabled some broken tests * use input_indexes to avoid batch-checking initializers * Avoid static initialization order error on WOS * Added candy to broken tests * InternalCI changes for 2020.2 * Updated DLDT instructions * Unsaved changed in install_openvino.sh * Changes after manual check * Remove custom ngraph onnx_import build for WOS ONNX Importer on WOS does not have protobuf issue. * Remove FP32ToFP16 ngraph pass This conversion is performed implicitly within IE. * Surround debug logic by #ifndef NDEBUG * remove invalid TODO comments * removed references to ngrpah-ep * clang-formatting * remove commented code * comment edits * updating copyright year to that of first OpenVINO-EP release * remove redundant log msg * Modified operator and topology support * Update build instructions * doc formatting * Fixed clip unit tests * Revert "Remove FP32ToFP16 ngraph pass" This reverts commit ec962ca5f315a5658ad980e740196f19de2639c1. * Applying FP16 transformation only for GPU FP16 * Fixed GPU FP32 python tests * automatically use full protobuf * disable onnxrt server for now * Disabled upsample * update dockerfile instructions * Removed MO paths and added ngraph path * Remove OVEP from ORT Server docs Will put it back in after validation * Updated path to Ngraph lib * Disabled Resize and some other python tests * Removed unnecesary header files * Use commit SHA to fetch ngraph repo * Avoid un-needed file changes due to version update * Fixed clip tests * Fixed Pow, max and min onnx tests * build.md doc typo * Update cmake patch command for ngraph src * remove dead cmake code for onnxruntime_USE_OPENVINO_BINARY * use spaces instead of tab * remove commented code * Add info about protobuf version * edit debug env var and enable for WIN32 * specify only version tag of 2020.2 for dockerbuilds * remove unnecessary file changes * Pass empty string as default argument to C# tests * Use ${OPENVINO_VERSION} to name openvino install directory in CI builds * Enabled unnecessarily disabled tests * Fixed ngraph protobuf patch * Fixed error in protobuf patch * Revert "Use ${OPENVINO_VERSION} to name openvino install directory in CI builds" This reverts commit 89e72adb8bf3b9712f5c81c5e13fe68c6c0df002. * Remove unsetting OPTIONAL macro This is no longer used in recent ONNX update onnx/onnx@da13be2, so this unset workaround is no longer necessary. * Use a null string default argument for C# API * Set OpenVINO version yml files and pass to CI Docker builds Git Tag info for DLDT as well as install directory are set using this value. This reverts commit 9fa9c20348ed72ae360a95c98e9b074d2f9fafc5. * Documentation: recommendation and instructions for disabling ORT graph optimizations * more doc updates * Reduced the number of models according to CI time constraints Co-authored-by: ynimmaga <yamini.nimmagadda@intel.com> Co-authored-by: suryasidd <surya.siddharth.pemmaraju@intel.com> Co-authored-by: Mikhail Treskin <mikhail.treskin@intel.com> Co-authored-by: mbencer <mateusz.bencer@intel.com> Co-authored-by: Aravind <aravindx.gunda@intel.com> Co-authored-by: suryasidd <48925384+suryasidd@users.noreply.github.com>
2020-04-24 11:06:02 +00:00
public void AppendExecutionProvider_OpenVINO(string deviceId = "")
{
#if __MOBILE__
throw new NotSupportedException("The OpenVINO Execution Provider is not supported in this build");
#else
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(deviceId);
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_OpenVINO(handle, utf8));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">device identification</param>
public void AppendExecutionProvider_Tensorrt(int deviceId = 0)
{
#if __MOBILE__
throw new NotSupportedException("The TensorRT Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_Tensorrt(handle, deviceId));
#endif
}
/// <summary>
/// Append a TensorRT EP instance (based on specified configuration) to the SessionOptions instance.
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="trtProviderOptions">TensorRT EP provider options</param>
public void AppendExecutionProvider_Tensorrt(OrtTensorRTProviderOptions trtProviderOptions)
{
#if __MOBILE__
throw new NotSupportedException("The TensorRT Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.SessionOptionsAppendExecutionProvider_TensorRT_V2(handle, trtProviderOptions.Handle));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">Device Id</param>
public void AppendExecutionProvider_ROCm(int deviceId = 0)
{
#if __MOBILE__
throw new NotSupportedException("The ROCM Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(
NativeMethods.OrtSessionOptionsAppendExecutionProvider_ROCM(handle, deviceId));
#endif
}
/// <summary>
/// Append a ROCm EP instance (based on specified configuration) to the SessionOptions instance.
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="rocmProviderOptions">ROCm EP provider options</param>
public void AppendExecutionProvider_ROCm(OrtROCMProviderOptions rocmProviderOptions)
{
#if __MOBILE__
throw new NotSupportedException("The ROCm Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.SessionOptionsAppendExecutionProvider_ROCM(handle, rocmProviderOptions.Handle));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="deviceId">device identification</param>
public void AppendExecutionProvider_MIGraphX(int deviceId = 0)
{
#if __MOBILE__
throw new NotSupportedException($"The MIGraphX Execution Provider is not supported in this build");
#else
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_MIGraphX(handle, deviceId));
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="nnapiFlags">NNAPI specific flag mask</param>
public void AppendExecutionProvider_Nnapi(NnapiFlags nnapiFlags = NnapiFlags.NNAPI_FLAG_USE_NONE)
{
#if __ANDROID__
NativeApiStatus.VerifySuccess(
NativeMethods.OrtSessionOptionsAppendExecutionProvider_Nnapi(handle, (uint)nnapiFlags));
#else
throw new NotSupportedException("The NNAPI Execution Provider is not supported in this build");
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
/// <param name="coremlFlags">CoreML specific flags</param>
public void AppendExecutionProvider_CoreML(CoreMLFlags coremlFlags = CoreMLFlags.COREML_FLAG_USE_NONE)
{
#if __IOS__
NativeApiStatus.VerifySuccess(
NativeMethods.OrtSessionOptionsAppendExecutionProvider_CoreML(handle, (uint)coremlFlags));
#else
#if __ENABLE_COREML__
// only attempt if this is OSX
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
NativeApiStatus.VerifySuccess(
NativeMethods.OrtSessionOptionsAppendExecutionProvider_CoreML(handle, (uint)coremlFlags));
}
else
#endif
{
throw new NotSupportedException("The CoreML Execution Provider is not supported in this build");
}
#endif
}
/// <summary>
/// Use only if you have the onnxruntime package specific to this Execution Provider.
/// </summary>
[TVM EP] Rename Standalone TVM (STVM) Execution Provider to TVM EP (#10260) * update java API for STVM EP. Issue is from PR#10019 * use_stvm -> use_tvm * rename stvm worktree * STVMAllocator -> TVMAllocator * StvmExecutionProviderInfo -> TvmExecutionProviderInfo * stvm -> tvm for cpu_targets. resolve onnxruntime::tvm and origin tvm namespaces conflict * STVMRunner -> TVMRunner * StvmExecutionProvider -> TvmExecutionProvider * tvm::env_vars * StvmProviderFactory -> TvmProviderFactory * rename factory funcs * StvmCPUDataTransfer -> TvmCPUDataTransfer * small clean * STVMFuncState -> TVMFuncState * USE_TVM -> NUPHAR_USE_TVM * USE_STVM -> USE_TVM * python API: providers.stvm -> providers.tvm. clean TVM_EP.md * clean build scripts #1 * clean build scripts, java frontend and others #2 * once more clean #3 * fix build of nuphar tvm test * final transfer stvm namespace to onnxruntime::tvm * rename stvm->tvm * NUPHAR_USE_TVM -> USE_NUPHAR_TVM * small fixes for correct CI tests * clean after rebase. Last renaming stvm to tvm, separate TVM and Nuphar in cmake and build files * update CUDA support for TVM EP * roll back CudaNN home check * ERROR for not positive input shape dimension instead of WARNING * update documentation for CUDA * small corrections after review * update GPU description * update GPU description * misprints were fixed * cleaned up error msgs Co-authored-by: Valery Chernov <valery.chernov@deelvin.com> Co-authored-by: KJlaccHoeUM9l <wotpricol@mail.ru> Co-authored-by: Thierry Moreau <tmoreau@octoml.ai>
2022-02-15 09:21:02 +00:00
/// <param name="settings">string with TVM specific settings</param>
public void AppendExecutionProvider_Tvm(string settings = "")
{
#if __MOBILE__
[TVM EP] Rename Standalone TVM (STVM) Execution Provider to TVM EP (#10260) * update java API for STVM EP. Issue is from PR#10019 * use_stvm -> use_tvm * rename stvm worktree * STVMAllocator -> TVMAllocator * StvmExecutionProviderInfo -> TvmExecutionProviderInfo * stvm -> tvm for cpu_targets. resolve onnxruntime::tvm and origin tvm namespaces conflict * STVMRunner -> TVMRunner * StvmExecutionProvider -> TvmExecutionProvider * tvm::env_vars * StvmProviderFactory -> TvmProviderFactory * rename factory funcs * StvmCPUDataTransfer -> TvmCPUDataTransfer * small clean * STVMFuncState -> TVMFuncState * USE_TVM -> NUPHAR_USE_TVM * USE_STVM -> USE_TVM * python API: providers.stvm -> providers.tvm. clean TVM_EP.md * clean build scripts #1 * clean build scripts, java frontend and others #2 * once more clean #3 * fix build of nuphar tvm test * final transfer stvm namespace to onnxruntime::tvm * rename stvm->tvm * NUPHAR_USE_TVM -> USE_NUPHAR_TVM * small fixes for correct CI tests * clean after rebase. Last renaming stvm to tvm, separate TVM and Nuphar in cmake and build files * update CUDA support for TVM EP * roll back CudaNN home check * ERROR for not positive input shape dimension instead of WARNING * update documentation for CUDA * small corrections after review * update GPU description * update GPU description * misprints were fixed * cleaned up error msgs Co-authored-by: Valery Chernov <valery.chernov@deelvin.com> Co-authored-by: KJlaccHoeUM9l <wotpricol@mail.ru> Co-authored-by: Thierry Moreau <tmoreau@octoml.ai>
2022-02-15 09:21:02 +00:00
throw new NotSupportedException("The TVM Execution Provider is not supported in this build");
#else
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(settings);
NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionOptionsAppendExecutionProvider_Tvm(handle, utf8));
#endif
}
private class ExecutionProviderAppender
{
private byte[] _utf8ProviderName;
internal ExecutionProviderAppender(byte[] providerName)
{
_utf8ProviderName = providerName;
}
public IntPtr Appender(IntPtr handle, IntPtr[] optKeys, IntPtr[] optValues, UIntPtr optCount)
{
return NativeMethods.SessionOptionsAppendExecutionProvider(
handle, _utf8ProviderName, optKeys, optValues, optCount);
}
}
2020-10-31 02:19:50 +00:00
/// <summary>
/// Append QNN, SNPE or XNNPACK execution provider
/// </summary>
/// <param name="providerName">Execution provider to add. 'QNN', 'SNPE' or 'XNNPACK' are currently supported.</param>
/// <param name="providerOptions">Optional key/value pairs to specify execution provider options.</param>
public void AppendExecutionProvider(string providerName, Dictionary<string, string> providerOptions = null)
{
if (providerName != "SNPE" && providerName != "XNNPACK" && providerName != "QNN" && providerName != "AZURE")
{
throw new NotSupportedException(
"Only QNN, SNPE, XNNPACK and AZURE execution providers can be enabled by this method.");
}
if (providerOptions == null)
{
providerOptions = new Dictionary<string, string>();
}
var utf8ProviderName = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(providerName);
var appender = new ExecutionProviderAppender(utf8ProviderName);
ProviderOptionsUpdater.Update(providerOptions, handle, appender.Appender);
}
#endregion //ExecutionProviderAppends
#region Public Methods
2020-10-31 02:19:50 +00:00
/// <summary>
/// Loads a DLL named 'libraryPath' and looks for this entry point:
/// OrtStatus* RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api);
2020-10-31 02:19:50 +00:00
/// It then passes in the provided session options to this function along with the api base.
///
/// Prior to v1.15 this leaked the library handle and RegisterCustomOpLibraryV2
/// was added to resolve that.
///
/// From v1.15 on ONNX Runtime will manage the lifetime of the handle.
2020-10-31 02:19:50 +00:00
/// </summary>
/// <param name="libraryPath">path to the custom op library</param>
public void RegisterCustomOpLibrary(string libraryPath)
{
NativeApiStatus.VerifySuccess(
NativeMethods.OrtRegisterCustomOpsLibrary_V2(
handle, NativeOnnxValueHelper.GetPlatformSerializedString(libraryPath))
);
2020-10-31 02:19:50 +00:00
}
/// <summary>
/// Loads a DLL named 'libraryPath' and looks for this entry point:
/// OrtStatus* RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api);
/// It then passes in the provided session options to this function along with the api base.
/// The handle to the loaded library is returned in 'libraryHandle'.
2020-10-31 02:19:50 +00:00
/// It can be unloaded by the caller after all sessions using the passed in
/// session options are destroyed, or if an error occurs and it is non null.
/// Hint: .NET Core 3.1 has a 'NativeLibrary' class that can be used to free the library handle
/// </summary>
/// <param name="libraryPath">Custom op library path</param>
/// <param name="libraryHandle">out parameter, library handle</param>
2020-10-31 02:19:50 +00:00
public void RegisterCustomOpLibraryV2(string libraryPath, out IntPtr libraryHandle)
{
// NOTE: This is confusing due to the history.
// SessionOptions.RegisterCustomOpLibrary initially called NativeMethods.OrtRegisterCustomOpsLibrary
// and leaked the handle.
// SessionOptions.RegisterCustomOpLibraryV2 was added to resolve that by returning the handle.
// Later, NativeMethods.OrtRegisterCustomOpsLibrary_V2 was added with ORT owning the handle.
//
// End result of that is
// SessionOptions.RegisterCustomOpLibrary calls NativeMethods.OrtRegisterCustomOpsLibrary_V2
// SessionOptions.RegisterCustomOpLibraryV2 calls NativeMethods.OrtRegisterCustomOpsLibrary
var utf8Path = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(libraryPath);
NativeApiStatus.VerifySuccess(NativeMethods.OrtRegisterCustomOpsLibrary(handle, utf8Path,
out libraryHandle));
}
/// <summary>
/// Register the custom operators from the Microsoft.ML.OnnxRuntime.Extensions NuGet package.
/// A reference to Microsoft.ML.OnnxRuntime.Extensions must be manually added to your project.
/// </summary>
/// <exception cref="OnnxRuntimeException">Throws if the extensions library is not found.</exception>
public void RegisterOrtExtensions()
{
try
{
#if NETSTANDARD2_0
var ortApiBasePtr = NativeMethods.OrtGetApiBase();
var ortApiBase = (OrtApiBase)Marshal.PtrToStructure(ortApiBasePtr, typeof(OrtApiBase));
#else
var ortApiBase = NativeMethods.OrtGetApiBase();
#endif
NativeApiStatus.VerifySuccess(
OrtExtensionsNativeMethods.RegisterCustomOps(this.handle, ref ortApiBase)
);
}
catch (DllNotFoundException)
{
throw new OnnxRuntimeException(
ErrorCode.NoSuchFile,
"The ONNX Runtime extensions library was not found. The Microsoft.ML.OnnxRuntime.Extensions " +
"NuGet package must be referenced by the project to use 'OrtExtensions.RegisterCustomOps.");
}
}
/// <summary>
/// Add a pre-allocated initializer to a session. If a model contains an initializer with a name
/// that is same as the name passed to this API call, ORT will use this initializer instance
/// instead of deserializing one from the model file. This is useful when you want to share
/// the same initializer across sessions.
/// </summary>
/// <param name="name">name of the initializer</param>
/// <param name="ortValue">OrtValue containing the initializer. Lifetime of 'val' and the underlying initializer buffer must be
/// managed by the user (created using the CreateTensorWithDataAsOrtValue API) and it must outlive the session object</param>
2020-10-31 02:19:50 +00:00
public void AddInitializer(string name, OrtValue ortValue)
{
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(name);
NativeApiStatus.VerifySuccess(NativeMethods.OrtAddInitializer(handle, utf8, ortValue.Handle));
}
2020-10-31 02:19:50 +00:00
/// <summary>
/// Set a single session configuration entry as a pair of strings
/// If a configuration with same key exists, this will overwrite the configuration with the given configValue
/// </summary>
/// <param name="configKey">config key name</param>
/// <param name="configValue">config key value</param>
public void AddSessionConfigEntry(string configKey, string configValue)
{
var utf8Key = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(configKey);
var utf8Value = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(configValue);
NativeApiStatus.VerifySuccess(NativeMethods.OrtAddSessionConfigEntry(handle, utf8Key, utf8Value));
2020-10-31 02:19:50 +00:00
}
/// <summary>
/// Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable
/// optimizations that can take advantage of fixed values (such as memory planning, etc)
/// </summary>
/// <param name="dimDenotation">denotation name</param>
/// <param name="dimValue">denotation value</param>
2020-10-31 02:19:50 +00:00
public void AddFreeDimensionOverride(string dimDenotation, long dimValue)
{
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(dimDenotation);
NativeApiStatus.VerifySuccess(NativeMethods.OrtAddFreeDimensionOverride(handle, utf8, dimValue));
}
2020-10-31 02:19:50 +00:00
/// <summary>
/// Override symbolic dimensions (by specific name strings) with actual values if known at session initialization time to enable
2020-10-31 02:19:50 +00:00
/// optimizations that can take advantage of fixed values (such as memory planning, etc)
/// </summary>
/// <param name="dimName">dimension name</param>
/// <param name="dimValue">dimension value</param>
2020-10-31 02:19:50 +00:00
public void AddFreeDimensionOverrideByName(string dimName, long dimValue)
{
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(dimName);
NativeApiStatus.VerifySuccess(NativeMethods.OrtAddFreeDimensionOverrideByName(handle, utf8, dimValue));
2020-10-31 02:19:50 +00:00
}
#endregion
2020-10-31 02:19:50 +00:00
internal IntPtr Handle
{
get
{
return handle;
}
}
#region Public Properties
/// <summary>
/// Overrides SafeHandle.IsInvalid
/// </summary>
/// <value>returns true if handle is equal to Zero</value>
public override bool IsInvalid { get { return handle == IntPtr.Zero; } }
/// <summary>
/// Enables the use of the memory allocation patterns in the first Run() call for subsequent runs. Default = true.
/// </summary>
/// <value>returns enableMemoryPattern flag value</value>
public bool EnableMemoryPattern
{
get
{
return _enableMemoryPattern;
}
set
{
if (!_enableMemoryPattern && value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtEnableMemPattern(handle));
_enableMemoryPattern = true;
}
else if (_enableMemoryPattern && !value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisableMemPattern(handle));
_enableMemoryPattern = false;
}
}
}
private bool _enableMemoryPattern = true;
/// <summary>
/// Path prefix to use for output of profiling data
/// </summary>
public string ProfileOutputPathPrefix
{
get; set;
} = "onnxruntime_profile_"; // this is the same default in C++ implementation
/// <summary>
/// Enables profiling of InferenceSession.Run() calls. Default is false
/// </summary>
/// <value>returns _enableProfiling flag value</value>
public bool EnableProfiling
{
get
{
return _enableProfiling;
}
set
{
if (!_enableProfiling && value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtEnableProfiling(handle, NativeOnnxValueHelper.GetPlatformSerializedString(ProfileOutputPathPrefix)));
_enableProfiling = true;
}
else if (_enableProfiling && !value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisableProfiling(handle));
_enableProfiling = false;
}
}
}
private bool _enableProfiling = false;
/// <summary>
/// Set filepath to save optimized model after graph level transformations. Default is empty, which implies saving is disabled.
/// </summary>
/// <value>returns _optimizedModelFilePath flag value</value>
public string OptimizedModelFilePath
{
get
{
return _optimizedModelFilePath;
}
set
{
if (value != _optimizedModelFilePath)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetOptimizedModelFilePath(handle, NativeOnnxValueHelper.GetPlatformSerializedString(value)));
_optimizedModelFilePath = value;
}
}
}
private string _optimizedModelFilePath = "";
/// <summary>
/// Enables Arena allocator for the CPU memory allocations. Default is true.
/// </summary>
/// <value>returns _enableCpuMemArena flag value</value>
public bool EnableCpuMemArena
2018-11-20 00:48:22 +00:00
{
get
{
return _enableCpuMemArena;
}
set
{
if (!_enableCpuMemArena && value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtEnableCpuMemArena(handle));
_enableCpuMemArena = true;
}
else if (_enableCpuMemArena && !value)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisableCpuMemArena(handle));
_enableCpuMemArena = false;
}
2018-11-20 00:48:22 +00:00
}
}
private bool _enableCpuMemArena = true;
/// <summary>
/// Disables the per session threads. Default is true.
/// This makes all sessions in the process use a global TP.
/// </summary>
public void DisablePerSessionThreads()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisablePerSessionThreads(handle));
}
/// <summary>
/// Log Id to be used for the session. Default is empty string.
/// </summary>
/// <value>returns _logId value</value>
public string LogId
2018-11-20 00:48:22 +00:00
{
get
{
return _logId;
}
set
{
var utf8 = NativeOnnxValueHelper.StringToZeroTerminatedUtf8(value);
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionLogId(handle, utf8));
_logId = value;
}
2018-11-20 00:48:22 +00:00
}
private string _logId = string.Empty;
/// <summary>
/// Log Severity Level for the session logs. Default = ORT_LOGGING_LEVEL_WARNING
/// </summary>
/// <value>returns _logSeverityLevel value</value>
public OrtLoggingLevel LogSeverityLevel
{
get
{
return _logSeverityLevel;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionLogSeverityLevel(handle, value));
_logSeverityLevel = value;
}
}
private OrtLoggingLevel _logSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
2018-11-20 00:48:22 +00:00
/// <summary>
/// Log Verbosity Level for the session logs. Default = 0. Valid values are >=0.
/// This takes into effect only when the LogSeverityLevel is set to ORT_LOGGING_LEVEL_VERBOSE.
/// </summary>
/// <value>returns _logVerbosityLevel value</value>
public int LogVerbosityLevel
{
get
{
return _logVerbosityLevel;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionLogVerbosityLevel(handle, value));
_logVerbosityLevel = value;
}
}
private int _logVerbosityLevel = 0;
/// <summary>
// Sets the number of threads used to parallelize the execution within nodes
// A value of 0 means ORT will pick a default
/// </summary>
/// <value>returns _intraOpNumThreads value</value>
public int IntraOpNumThreads
{
get
{
return _intraOpNumThreads;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetIntraOpNumThreads(handle, value));
_intraOpNumThreads = value;
}
}
private int _intraOpNumThreads = 0; // set to what is set in C++ SessionOptions by default;
/// <summary>
// Sets the number of threads used to parallelize the execution of the graph (across nodes)
// If sequential execution is enabled this value is ignored
// A value of 0 means ORT will pick a default
/// </summary>
/// <value>returns _interOpNumThreads value</value>
public int InterOpNumThreads
{
get
{
return _interOpNumThreads;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetInterOpNumThreads(handle, value));
_interOpNumThreads = value;
}
}
private int _interOpNumThreads = 0; // set to what is set in C++ SessionOptions by default;
/// <summary>
/// Sets the graph optimization level for the session. Default is set to ORT_ENABLE_ALL.
/// </summary>
/// <value>returns _graphOptimizationLevel value</value>
public GraphOptimizationLevel GraphOptimizationLevel
{
get
{
return _graphOptimizationLevel;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionGraphOptimizationLevel(handle, value));
_graphOptimizationLevel = value;
}
}
private GraphOptimizationLevel _graphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL;
/// <summary>
/// Sets the execution mode for the session. Default is set to ORT_SEQUENTIAL.
/// See [ONNX_Runtime_Perf_Tuning.md] for more details.
/// </summary>
/// <value>returns _executionMode value</value>
public ExecutionMode ExecutionMode
{
get
{
return _executionMode;
}
set
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionExecutionMode(handle, value));
_executionMode = value;
}
}
private ExecutionMode _executionMode = ExecutionMode.ORT_SEQUENTIAL;
#endregion
#region Private Methods
#if !__MOBILE__
// Declared, but called only if OS = Windows.
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
static extern uint GetSystemDirectory([Out] StringBuilder lpBuffer, uint uSize);
#else
private static IntPtr LoadLibrary(string dllToLoad)
{
throw new NotSupportedException();
}
static uint GetSystemDirectory([Out] StringBuilder lpBuffer, uint uSize)
{
throw new NotSupportedException();
}
#endif
private static bool CheckCudaExecutionProviderDLLs()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
foreach (var dll in cudaDelayLoadedLibs)
{
IntPtr handle = LoadLibrary(dll);
if (handle != IntPtr.Zero)
continue;
var sysdir = new StringBuilder(String.Empty, 2048);
GetSystemDirectory(sysdir, (uint)sysdir.Capacity);
throw new OnnxRuntimeException(
ErrorCode.NoSuchFile,
$"kernel32.LoadLibrary():'{dll}' not found. CUDA is required for GPU execution. " +
$". Verify it is available in the system directory={sysdir}. Else copy it to the output folder."
);
}
}
return true;
}
private static bool CheckTensorrtExecutionProviderDLLs()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
foreach (var dll in trtDelayLoadedLibs)
{
IntPtr handle = LoadLibrary(dll);
if (handle != IntPtr.Zero)
continue;
var sysdir = new StringBuilder(String.Empty, 2048);
GetSystemDirectory(sysdir, (uint)sysdir.Capacity);
throw new OnnxRuntimeException(
ErrorCode.NoSuchFile,
$"kernel32.LoadLibrary():'{dll}' not found. TensorRT/CUDA are required for GPU execution. " +
$". Verify it is available in the system directory={sysdir}. Else copy it to the output folder."
);
}
}
return true;
}
private static bool CheckRocmExecutionProviderDLLs()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
throw new NotSupportedException("ROCm Execution Provider is not currently supported on Windows.");
}
return true;
}
#endregion
#region SafeHandle
/// <summary>
/// Overrides SafeHandle.ReleaseHandle() to properly dispose of
/// the native instance of SessionOptions
/// </summary>
/// <returns>always returns true</returns>
protected override bool ReleaseHandle()
{
NativeMethods.OrtReleaseSessionOptions(handle);
handle = IntPtr.Zero;
return true;
}
#endregion
2018-11-20 00:48:22 +00:00
}
}