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

197 lines
7 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.Text;
2018-11-23 04:56:43 +00:00
using System.Runtime.InteropServices;
2018-11-20 00:48:22 +00:00
namespace Microsoft.ML.OnnxRuntime
{
/// <summary>
/// Holds the options for creating an InferenceSession
/// </summary>
public class SessionOptions:IDisposable
2018-11-20 00:48:22 +00:00
{
public IntPtr _nativePtr;
protected static readonly Lazy<SessionOptions> _default = new Lazy<SessionOptions>(MakeSessionOptionWithCpuProvider);
Refactor CI pipelines - add GPU NuGet pipelines and ESRP code signing steps (#1247) * Simplify linux gpu pipeline * Refactor win-gpu-ci-pipeline.yml * Set cuda environment variables for testing and version * Remove variables from starter script * minor fix * Add GPU Nuget pipeline * Set DisableContribOps environment variable for Linux package tests * Add ESRP tasks * Add ESRP signing templates * Test out hardcode value of ERSP * Test out hardcode value of ERSP * Test out hardcode value of ERSP * Test out hardcode value of ERSP * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test out variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * test variable expansion * update cpu pipeline to conditionally esrp sign * Set C# GPU tests to run only if env var is set * Refactor for easy parameter passing * refactored esrp templates * remove variables from template * Add packaging variables back to pipelines * update C# for cuda 10 * Merge vars ana parameters for gpu pipeline * remove vars from mklml pipeline * display envvars on terminal * Clean up C# cuda tests, and upgrade to Cuda10 * Introduce CUDNN_PATH pipeline varaible * YAML variable are always uppercased (not true with classic) * Update C# GPU test to be more meaningful * remove macos from gpu tests * remove debugging info for DisableContribOps option * Remove DisableContrib ops parameters -- use variables only * Fix typo from = to - * remove debug steps * fix typo * remove unused variable TESTONGPU from some templates * clean up CUDA env setup scripts * Remove CUDNN_PATH from setup_env_cuda.bat
2019-06-21 02:41:30 +00:00
private static string[] cudaDelayLoadedLibs = { "cublas64_100.dll", "cudnn64_7.dll" };
2018-11-20 00:48:22 +00:00
/// <summary>
/// Constructs an empty SessionOptions
/// </summary>
2018-11-20 00:48:22 +00:00
public SessionOptions()
{
NativeMethods.OrtCreateSessionOptions(out _nativePtr);
2018-11-20 00:48:22 +00:00
}
/// <summary>
/// Sets the graph optimization level for the session. Default is set to 1.
/// </summary>
/// <param name="optimization_level">optimization level for the session</param>
/// Available options are : 0, 1, 2
/// 0 -> Disable all optimizations
/// 1 -> Enable basic optimizations
/// 2 -> Enable all optimizations
public void SetSessionGraphOptimizationLevel(uint optimization_level)
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtSetSessionGraphOptimizationLevel(_nativePtr, optimization_level));
}
/// <summary>
/// Enable Sequential Execution. By default, it is enabled.
/// </summary>
/// </param>
public void EnableSequentialExecution()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtEnableSequentialExecution(_nativePtr));
}
/// <summary>
/// Disable Sequential Execution and enable Parallel Execution.
/// </summary>
/// </param>
public void DisableSequentialExecution()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisableSequentialExecution(_nativePtr));
}
/// <summary>
/// Enable Mem Pattern. By default, it is enabled
/// </summary>
/// </param>
public void EnableMemPattern()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtEnableMemPattern(_nativePtr));
}
/// <summary>
/// Disable Mem Pattern.
/// </summary>
/// </param>
public void DisableMemPattern()
{
NativeApiStatus.VerifySuccess(NativeMethods.OrtDisableMemPattern(_nativePtr));
}
/// <summary>
/// Default instance
/// </summary>
2018-11-23 04:56:43 +00:00
public static SessionOptions Default
2018-11-20 00:48:22 +00:00
{
get
{
2018-11-23 04:56:43 +00:00
return _default.Value;
2018-11-20 00:48:22 +00:00
}
}
private static SessionOptions MakeSessionOptionWithCpuProvider()
2018-11-20 00:48:22 +00:00
{
CheckLibcVersionGreaterThanMinimum();
2018-11-23 04:56:43 +00:00
SessionOptions options = new SessionOptions();
NativeMethods.OrtSessionOptionsAppendExecutionProvider_CPU(options._nativePtr, 1);
2018-11-23 04:56:43 +00:00
return options;
2018-11-20 00:48:22 +00:00
}
/// <summary>
/// A helper method to constuct a SessionOptions object for CUDA execution
/// </summary>
/// <returns>A SessionsOptions() object configured for execution on deviceId=0</returns>
public static SessionOptions MakeSessionOptionWithCudaProvider()
{
return MakeSessionOptionWithCudaProvider(0);
}
/// <summary>
/// A helper method to constuct a SessionOptions object for CUDA execution
/// </summary>
/// <param name="deviceId"></param>
/// <returns>A SessionsOptions() object configured for execution on deviceId</returns>
public static SessionOptions MakeSessionOptionWithCudaProvider(int deviceId=0)
{
CheckLibcVersionGreaterThanMinimum();
CheckCudaExecutionProviderDLLs();
SessionOptions options = new SessionOptions();
NativeMethods.OrtSessionOptionsAppendExecutionProvider_CUDA(options._nativePtr, deviceId);
NativeMethods.OrtSessionOptionsAppendExecutionProvider_CPU(options._nativePtr, 1);
return options;
}
2018-11-23 04:56:43 +00:00
// 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);
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;
}
[DllImport("libc", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gnu_get_libc_version();
private static void CheckLibcVersionGreaterThanMinimum()
{
// require libc version 2.23 or higher
var minVersion = new Version(2, 23);
var curVersion = new Version(0, 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
try
{
curVersion = Version.Parse(Marshal.PtrToStringAnsi(gnu_get_libc_version()));
if (curVersion >= minVersion)
return;
}
catch (Exception)
{
// trap any obscure exception
}
throw new OnnxRuntimeException(ErrorCode.RuntimeException,
$"libc.so version={curVersion} does not meet the minimun of 2.23 required by OnnxRuntime. " +
"Linux distribution should be similar to Ubuntu 16.04 or higher");
}
}
#region destructors disposers
~SessionOptions()
{
Dispose(false);
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// cleanup managed resources
}
NativeMethods.OrtReleaseSessionOptions(_nativePtr);
}
#endregion
2018-11-20 00:48:22 +00:00
}
}