// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.ML.OnnxRuntime { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; /// /// Flags representing options to enable when compiling a model. /// Matches OrtCompileApiFlags in the ORT C API. /// [Flags] public enum OrtCompileApiFlags : uint { NONE = 0, ERROR_IF_NO_NODES_COMPILED = 1 << 0, ERROR_IF_OUTPUT_FILE_EXISTS = 1 << 1, } /// /// This class is used to set options for model compilation, and to produce a compiled model using those options. /// See https://onnxruntime.ai/docs/api/c/ for further details of various options. /// public class OrtModelCompilationOptions : IDisposable { /// /// Create a new OrtModelCompilationOptions object from SessionOptions. /// /// By default, the GraphOptimizationLevel is set to ORT_DISABLE_ALL. Use SetGraphOptimizationLevel() /// to enable graph optimizations. /// SessionOptions instance to read settings from. public OrtModelCompilationOptions(SessionOptions sessionOptions) { _epContextDataReadRegistration = sessionOptions.InvokeWithEpContextDataReadRegistration(sessionOptionsHandle => { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtCreateModelCompilationOptionsFromSessionOptions( OrtEnv.Instance().Handle, sessionOptionsHandle, out _handle)); }); } /// /// Compile the model using the options set in this object. /// public void CompileModel() { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount == 0) { ApplyPendingEpContextDataWriteRegistration(); } ++_activeCompileCount; } try { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtCompileModel(OrtEnv.Instance().Handle, _handle)); } finally { lock (_epContextDataWriteRegistrationLock) { if (--_activeCompileCount == 0) { ApplyPendingEpContextDataWriteRegistration(); } } GC.KeepAlive(this); } } /// /// Set the input model to compile. /// /// Path to ONNX model to compile. public void SetInputModelPath(string path) { var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(path); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelPath(_handle, platformPath)); } /// /// Set the input model to compile to be a byte array. /// The input bytes are NOT copied and must remain valid while in use by ORT. /// /// Input model bytes. public void SetInputModelFromBuffer(byte[] buffer) { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelFromBuffer( _handle, buffer, (UIntPtr)buffer.Length)); } /// /// Set the path to write the compiled ONNX model to. /// /// Path to write compiled model to. public void SetOutputModelPath(string path) { var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(path); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelPath(_handle, platformPath)); } /// /// Set the path to a file to write initializers as external data to, /// and the threshold that determines when to write an initializer to the external data file. /// /// Path to file to write external data to. /// Size at which an initializer will be written to external data. public void SetOutputModelExternalInitializersFile(string filePath, ulong threshold) { var platformPath = NativeOnnxValueHelper.GetPlatformSerializedString(filePath); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelExternalInitializersFile( _handle, platformPath, new UIntPtr(threshold))); } // TODO: In order to use this to create an InferenceSession without copying bytes we need more infrastructure. // - Need something that wraps the allocator, pointer and size and is SafeHandle based. // - When it is disposed we need to use the allocator to release the native buffer. // - Need the 4 InferenceSession ctors that take byte[] for the model to be duplicated to handle this new // wrapper type. // Due to that making this API internal so we can test it. We can make it public when the other infrastructure // is in place as it will change the signature of the API. internal void SetOutputModelBuffer(OrtAllocator allocator, ref IntPtr outputModelBufferPtr, ref UIntPtr outputModelBufferSizePtr) { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelBuffer( _handle, allocator.Pointer, ref outputModelBufferPtr, ref outputModelBufferSizePtr)); } /// /// Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute /// of EPContext nodes. /// /// Enable if true. Default is false. public void SetEpContextEmbedMode(bool embed) { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextEmbedMode(_handle, embed)); } /// /// Sets flags from OrtCompileApiFlags that represent one or more boolean options to enable. /// /// bitwise OR of flags in OrtCompileApiFlags to enable. public void SetFlags(OrtCompileApiFlags flags) { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetFlags(_handle, (uint)flags)); } /// /// Sets information related to EP context binary file. The Ep uses this information to decide the /// location and context binary file name when compiling with both the input and output models /// stored in buffers. /// /// Path to the model directory. /// The name of the model. public void SetEpContextBinaryInformation(string outputDirectory, string modelName) { var platformOutputDirectory = NativeOnnxValueHelper.GetPlatformSerializedString(outputDirectory); var platformModelName = NativeOnnxValueHelper.GetPlatformSerializedString(modelName); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextBinaryInformation( _handle, platformOutputDirectory, platformModelName)); } /// /// Sets the graph optimization level. Defaults to ORT_DISABLE_ALL if not specified. /// /// The graph optimization level to set. public void SetGraphOptimizationLevel(GraphOptimizationLevel graphOptimizationLevel) { NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetGraphOptimizationLevel( _handle, graphOptimizationLevel)); } /// /// Delegate that receives one complete external EPContext payload during model compilation. /// The data view is valid only for the duration of the delegate invocation. /// /// Logical UTF-8 name stored in the EPContext node. /// Non-owning view of the payload. /// ORT may invoke this delegate concurrently. The application must synchronize shared state. public delegate void WriteEpContextDataDelegate(string name, OrtEpContextData data); /// /// Registers a delegate that receives external EPContext data when embed mode is disabled. /// /// Delegate invoked by ORT to receive external EPContext data. public void SetEpContextDataWriteDelegate(WriteEpContextDataDelegate writeDelegate) { if (writeDelegate == null) { throw new ArgumentNullException(nameof(writeDelegate)); } var newRegistration = new EpContextDataWriteRegistration(writeDelegate); try { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount > 0) { var previousRegistration = _epContextDataWriteRegistration; _epContextDataWriteRegistration = newRegistration; RetireEpContextDataWriteRegistration(previousRegistration); _epContextDataWriteRegistrationUpdatePending = true; } else { ApplyPendingEpContextDataWriteRegistration(); var previousRegistration = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc( _handle, newRegistration.FunctionPointer, newRegistration.State)); _epContextDataWriteRegistration = newRegistration; RetireEpContextDataWriteRegistration(previousRegistration); } } } catch { newRegistration.Dispose(); throw; } } /// /// Clears a previously registered EPContext data write delegate. /// public void ClearEpContextDataWriteDelegate() { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount > 0) { var previousRegistration = _epContextDataWriteRegistration; _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(previousRegistration); _epContextDataWriteRegistrationUpdatePending = true; } else { ApplyPendingEpContextDataWriteRegistration(); var previousRegistration = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc( _handle, IntPtr.Zero, IntPtr.Zero)); _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(previousRegistration); } } } private void ApplyPendingEpContextDataWriteRegistration() { if (!_epContextDataWriteRegistrationUpdatePending) { return; } var registration = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc( _handle, registration?.FunctionPointer ?? IntPtr.Zero, registration?.State ?? IntPtr.Zero)); _epContextDataWriteRegistrationUpdatePending = false; foreach (var retiredRegistration in _retiredEpContextDataWriteRegistrations) { retiredRegistration.Dispose(); } _retiredEpContextDataWriteRegistrations.Clear(); } private void RetireEpContextDataWriteRegistration(EpContextDataWriteRegistration registration) { if (registration == null) { return; } // Native compilation snapshots the callback after entering CompileModel, so any registration // replaced during an active call may still be used by that call. if (_activeCompileCount > 0) { _retiredEpContextDataWriteRegistrations.Add(registration); } else { registration.Dispose(); } } /// /// Delegate to write/save a buffer containing ONNX model bytes to a custom destination. The delegate /// may be called repeatedly until the entire output model has been written out. Each call to the delegate /// is expected to consume the entire buffer. /// /// The buffer to write out. /// public delegate void WriteBufferToDestinationDelegate(ReadOnlySpan buffer); /// /// Sets a delegate that is called by ORT to write out the output model's serialized ONNX bytes. /// The provided delegate may be called repeatedly until the entire output model has been written out. /// Each call to the delegate is expected to consume/handle the entire input buffer. /// /// The delegate called by ORT to write out the model. public void SetOutputModelWriteDelegate(WriteBufferToDestinationDelegate writeBufferDelegate) { _writeBufferToDestinationDelegateState?.Dispose(); _writeBufferToDestinationDelegateState = new DelegateResources( new WriteBufferToDestinationConnector(writeBufferDelegate), new NativeMethods.DOrtWriteBufferToDestinationDelegate( WriteBufferToDestinationConnector.WriteBufferToDestinationDelegateWrapper)); IntPtr funcPtr = _writeBufferToDestinationDelegateState.GetFunctionPointerForDelegate(); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelWriteFunc( _handle, funcPtr, _writeBufferToDestinationDelegateState.GetConnectorHandleAsPointer())); } /// /// Delegate called by ORT for every initializer when generating the compiled model. /// The delegate allows the user to determine whether the initializer should be stored within the compiled /// model or externally in a file. If the delegate chooses to store an initializer externally, the delegate /// implementation is responsible for writing the initializer data to a file. /// /// The initializer's name. /// The readonly OrtValue instance containing the data, type, and /// shape of the initializer. /// May be null. If the initializer is originally stored externally, /// this contains the file path, file offset, and data size. Otherwise, this is null. /// A new OrtExternalInitializerInfo indicating the new location of the initializer. /// Returns null if the initializer should be stored within the generated compiled model. /// The return value may be null. /// public delegate OrtExternalInitializerInfo GetInitializerLocationDelegate( string initializerName, IReadOnlyOrtValue initializerValue, IReadOnlyExternalInitializerInfo originalInitializerLocation); /// /// Sets a delegate that is called by ORT for every initializer when generating the compiled model. /// The delegate allows the user to determine whether the initializer should be stored within the compiled /// model or externally in a file. If the delegate chooses to store an initializer externally, the delegate /// implementation is responsible for writing the initializer data to a file. /// /// The delegate called by ORT for every initializer. public void SetOutputModelGetInitializerLocationDelegate( GetInitializerLocationDelegate getInitializerLocationDelegate) { _getInitializerLocationDelegateState?.Dispose(); _getInitializerLocationDelegateState = new DelegateResources( new GetInitializerLocationConnector(getInitializerLocationDelegate), new NativeMethods.DOrtGetInitializerLocationDelegate( GetInitializerLocationConnector.GetInitializerLocationDelegateWrapper)); IntPtr funcPtr = _getInitializerLocationDelegateState.GetFunctionPointerForDelegate(); NativeApiStatus.VerifySuccess( NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelGetInitializerLocationFunc( _handle, funcPtr, _getInitializerLocationDelegateState.GetConnectorHandleAsPointer())); } #region Delegate helpers private sealed class EpContextDataWriteConnector { internal EpContextDataWriteConnector(WriteEpContextDataDelegate writeDelegate) { _writeDelegate = writeDelegate; } internal static IntPtr WriteEpContextDataDelegateWrapper( IntPtr state, IntPtr name, IntPtr buffer, UIntPtr bufferSize) { try { var connector = (EpContextDataWriteConnector)GCHandle.FromIntPtr(state).Target; string dataName = NativeOnnxValueHelper.StringFromNativeUtf8(name); var data = new OrtEpContextData(buffer, bufferSize); try { connector._writeDelegate(dataName, data); } finally { data.Invalidate(); } return IntPtr.Zero; } catch (Exception ex) { string error = $"The C# EPContext data write delegate threw an exception: {ex.Message}"; return NativeMethods.OrtCreateStatus( (uint)ErrorCode.Fail, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error)); } } private readonly WriteEpContextDataDelegate _writeDelegate; } private sealed class EpContextDataWriteRegistration : IDisposable { internal EpContextDataWriteRegistration(WriteEpContextDataDelegate writeDelegate) { _connector = new EpContextDataWriteConnector(writeDelegate); _nativeDelegate = new CompileApi.NativeMethods.DOrtWriteNamedBufferDelegate( EpContextDataWriteConnector.WriteEpContextDataDelegateWrapper); _connectorHandle = GCHandle.Alloc(_connector); try { FunctionPointer = Marshal.GetFunctionPointerForDelegate(_nativeDelegate); State = GCHandle.ToIntPtr(_connectorHandle); } catch { _connectorHandle.Free(); throw; } } internal IntPtr FunctionPointer { get; } internal IntPtr State { get; } internal void Release() { if (System.Threading.Interlocked.Decrement(ref _referenceCount) == 0) { if (_connectorHandle.IsAllocated) { _connectorHandle.Free(); } _connector = null; _nativeDelegate = null; } } public void Dispose() { if (System.Threading.Interlocked.Exchange(ref _ownerReleased, 1) == 0) { Release(); } GC.SuppressFinalize(this); } ~EpContextDataWriteRegistration() { if (System.Threading.Interlocked.Exchange(ref _ownerReleased, 1) == 0) { Release(); } } private EpContextDataWriteConnector _connector; private CompileApi.NativeMethods.DOrtWriteNamedBufferDelegate _nativeDelegate; private GCHandle _connectorHandle; private int _referenceCount = 1; private int _ownerReleased; } /// /// Class to bridge the C# and native worlds for the "write buffer to destination" delegate /// private class WriteBufferToDestinationConnector { private readonly WriteBufferToDestinationDelegate _userDelegate; internal WriteBufferToDestinationConnector(WriteBufferToDestinationDelegate writeBufferDelegate) { _userDelegate = writeBufferDelegate; } public static IntPtr WriteBufferToDestinationDelegateWrapper(IntPtr /* void* */ state, IntPtr /* const void* */ buffer, UIntPtr /* size_t */ bufferNumBytes) { try { WriteBufferToDestinationConnector connector = (WriteBufferToDestinationConnector) GCHandle.FromIntPtr(state).Target; ReadOnlySpan bufferSpan; unsafe { // NOTE: A Span can only view 2GB of data. This is fine because ORT does not write out // chunks that large. However, if we ever need to, the solution is to just write a loop here // that repeatedly calls the delegate with smaller chunks of data. bufferSpan = new ReadOnlySpan(buffer.ToPointer(), checked((int)bufferNumBytes)); } connector._userDelegate(bufferSpan); } catch (Exception ex) { var error = $"The C# WriteBufferToDestination delegate threw an exception: {ex.Message}"; IntPtr status = NativeMethods.OrtCreateStatus((uint)ErrorCode.Fail, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error)); return status; } return IntPtr.Zero; } } /// /// Class to bridge the C# and native worlds for the "get initializer location" delegate /// private class GetInitializerLocationConnector { private readonly GetInitializerLocationDelegate _userDelegate; internal GetInitializerLocationConnector(GetInitializerLocationDelegate getInitializerLocationDelegate) { _userDelegate = getInitializerLocationDelegate; } public static IntPtr GetInitializerLocationDelegateWrapper( IntPtr /* void* */ state, IntPtr /* const char* */ initializerName, IntPtr /* const OrtValue* */ initializerValue, IntPtr /* const OrtExternalInitializerInfo* */ originalInitializerLocation, out IntPtr /* OrtExternalInitializerInfo** */ newInitializerLocationOutput) { newInitializerLocationOutput = IntPtr.Zero; try { GetInitializerLocationConnector connector = (GetInitializerLocationConnector)GCHandle. FromIntPtr(state).Target; string utf8InitializerName = NativeOnnxValueHelper.StringFromNativeUtf8(initializerName); IReadOnlyOrtValue readOnlyInitializerValue = new OrtValue(initializerValue, owned: false); IReadOnlyExternalInitializerInfo readOnlyOriginalInitializerLocation = null; if (originalInitializerLocation != IntPtr.Zero) { readOnlyOriginalInitializerLocation = new OrtExternalInitializerInfo( originalInitializerLocation, ownsHandle: false); } // Call user's delegate, which may return the new location of the initializer. OrtExternalInitializerInfo newInitializerLocation = connector._userDelegate( utf8InitializerName, readOnlyInitializerValue, readOnlyOriginalInitializerLocation); if (newInitializerLocation != null) { // Delegate returned info about a new location for the initializer. // Can't guarantee that the new external info returned by user's delegate is not referenced // by other C# code. ORT expects to own the new external info, so create a copy here and // give it to ORT. string newFilePath = newInitializerLocation.GetFilePath(); byte[] newFilePathBytes = NativeOnnxValueHelper.GetPlatformSerializedString(newFilePath); IntPtr status = NativeMethods.OrtCreateExternalInitializerInfo( newFilePathBytes, newInitializerLocation.GetFileOffset(), (UIntPtr)newInitializerLocation.GetByteSize(), out newInitializerLocationOutput); if (status != IntPtr.Zero) { return status; } } else { // User's delegate did not return a new location for the initializer. ORT will store initializer // within the generated compiled model. newInitializerLocationOutput = IntPtr.Zero; } } catch (Exception ex) { var error = $"The C# GetInitializerLocation delegate threw an exception: {ex.Message}"; IntPtr status = NativeMethods.OrtCreateStatus((uint)ErrorCode.Fail, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(error)); return status; } return IntPtr.Zero; } } /// /// Disposable class that stores resources for a delegate provided by the user. /// /// The type of the connector class /// (e.g., WriteBufferToDestinationConnector) /// The type of the native delegate. private class DelegateResources : IDisposable where Connector : class where Delegate : class { public DelegateResources(Connector connector, Delegate @delegate) { _connector = connector; _delegate = @delegate; _connectorHandle = GCHandle.Alloc(_connector); _delegateHandle = GCHandle.Alloc(_delegate); } internal IntPtr GetFunctionPointerForDelegate() { return Marshal.GetFunctionPointerForDelegate(_delegate); } internal IntPtr GetConnectorHandleAsPointer() { return GCHandle.ToIntPtr(_connectorHandle); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { // Dispose other children disposables. We have none. } if (_connectorHandle.IsAllocated) { _connectorHandle.Free(); _connector = null; } if (_delegateHandle.IsAllocated) { _delegateHandle.Free(); _delegate = null; } _disposed = true; } ~DelegateResources() { Dispose(false); } private Connector _connector = null; private Delegate _delegate = null; private GCHandle _connectorHandle = default; private GCHandle _delegateHandle = default; private bool _disposed = false; } #endregion #region IDispose implementation /// /// IDispose implementation. /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// IDispose implementation /// /// True if Dispose() has been called by the user-side code. False if /// called by the runtime from inside the finalizer. protected virtual void Dispose(bool disposing) { if (_disposed) { return; } Debug.Assert(_handle != IntPtr.Zero); NativeMethods.CompileApi.OrtReleaseModelCompilationOptions(_handle); _handle = IntPtr.Zero; if (_epContextDataReadRegistration != null) { _epContextDataReadRegistration.Release(); _epContextDataReadRegistration = null; } lock (_epContextDataWriteRegistrationLock) { var writeRegistration = _epContextDataWriteRegistration; _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(writeRegistration); foreach (var retiredRegistration in _retiredEpContextDataWriteRegistrations) { retiredRegistration.Dispose(); } _retiredEpContextDataWriteRegistrations.Clear(); } if (disposing) { _writeBufferToDestinationDelegateState?.Dispose(); _getInitializerLocationDelegateState?.Dispose(); } _disposed = true; } /// /// Finalizer that releases the native handle if not already released by Dispose(). /// ~OrtModelCompilationOptions() { Dispose(false); } #endregion /// /// Handle to the native OrtModelCompilationOptions object. /// private IntPtr _handle; /// /// True if this OrtModelCompilationOptions instance has already been disposed. /// private bool _disposed = false; private SessionOptions.EpContextDataReadRegistration _epContextDataReadRegistration = null; /// /// Stores delegate state for the "write buffer to destination" delegate. /// private DelegateResources _writeBufferToDestinationDelegateState = null; private readonly object _epContextDataWriteRegistrationLock = new object(); private EpContextDataWriteRegistration _epContextDataWriteRegistration = null; private int _activeCompileCount; private bool _epContextDataWriteRegistrationUpdatePending; private readonly List _retiredEpContextDataWriteRegistrations = new List(); /// /// Stores delegate state for the "get initializer location" delegate. /// private DelegateResources _getInitializerLocationDelegateState = null; } }