// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-FileCopyrightText: Copyright 2024 Arm Limited and/or its affiliates // Licensed under the MIT License. #pragma once #include #include #include #include #include "core/common/status.h" #include "core/session/model_compilation_options.h" #include "python/onnxruntime_pybind_state_common.h" namespace onnxruntime { class Environment; namespace python { #if !defined(ORT_MINIMAL_BUILD) class PyEpContextData { public: PyEpContextData(const void* data, size_t size) : data_(data), size_(size) {} size_t Size() const noexcept { return size_; } pybind11::bytes Read(size_t offset, std::optional length) const; void Invalidate() noexcept; private: const void* data_ = nullptr; size_t size_ = 0; bool valid_ = true; }; class PyEpContextDataBuffer { public: PyEpContextDataBuffer(OrtAllocator* allocator, size_t max_data_size); ~PyEpContextDataBuffer(); ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(PyEpContextDataBuffer); size_t Size() const noexcept { return size_; } size_t MaxSize() const noexcept { return max_data_size_; } bool IsAllocated() const noexcept { return allocated_; } void Allocate(size_t size); void Write(size_t offset, const pybind11::buffer& data); void Detach(void*& buffer, size_t& size); void Invalidate() noexcept; private: void ThrowIfInvalid() const; OrtAllocator* allocator_ = nullptr; const size_t max_data_size_; void* buffer_ = nullptr; size_t size_ = 0; bool allocated_ = false; bool valid_ = true; }; using PyEpContextDataWriteFunc = std::function&)>; using PyEpContextDataReadFunc = std::function&)>; struct PyEpContextDataReadRegistration { PyEpContextDataReadFunc read_func; size_t max_data_size; }; OrtStatus* ORT_API_CALL PyEpContextDataReadFuncWrapper(void* state, const char* name, OrtAllocator* allocator, void** buffer, size_t* data_size); #endif // !defined(ORT_MINIMAL_BUILD) // Type of the function provided by Python code that is called by ORT to write out the compiled model. using PyOutStreamWriteFunc = std::function; // Type of the function provided by Python code that is called by ORT to handle every initializer. using PyGetInitializerLocationFunc = std::function( const std::string& initializer_name, const OrtValue& initializer_value, const OrtExternalInitializerInfo* external_info)>; /// /// Class exposed to Python that enables compiling ONNX models. /// Internally wraps a onnxruntime::ModelCompilationOptions that stores and validates settings. /// class PyModelCompiler { #if defined(ORT_MINIMAL_BUILD) public: bool not_defined_in_this_build{}; // Prevent empty class warning. #else private: // private tag to pass to constructor to ensure that constructor cannot be directly called externally struct PrivateConstructorTag {}; public: /// /// Static class function that creates a unique_ptr with the given settings. /// /// Output parameter for the result /// The Environment instance /// The SessionOptions from which to initialize compilation options. /// An r-value string that could be the input model's path or bytes /// True if 'input_model_path_or_bytes' is a path, and false if its bytes. /// True to embed compiled binary data into EPContext nodes. /// The file into which to store initializers for non-compiled /// nodes. /// Ignored if 'external_initializers_file_path' is empty. /// Initializers with a size greater than this threshold are dumped into the external file. /// Flags from OrtCompileApiFlags /// Optimization level for graph transformations on the model. /// Defaults to ORT_DISABLE_ALL to allow EP to get the original loaded model. /// User's function to handle saving of initializers. /// A Status indicating error or success. static onnxruntime::Status Create(/*out*/ std::unique_ptr& out, onnxruntime::Environment& env, const PySessionOptions& sess_options, std::string&& input_model_path_or_bytes, bool input_model_is_path, bool embed_compiled_data_into_model = false, const std::string& external_initializers_file_path = {}, size_t external_initializers_size_threshold = 1024, uint32_t flags = 0, GraphOptimizationLevel graph_opt_level = GraphOptimizationLevel::ORT_DISABLE_ALL, const PyGetInitializerLocationFunc& py_get_initializer_location_func = nullptr); // Note: Creation should be done via Create(). This constructor is public so that it can be called from // std::make_shared(). PyModelCompiler(onnxruntime::Environment& env, const OrtSessionOptions& sess_options, std::shared_ptr py_ep_selection_registration, std::shared_ptr py_ep_context_data_read_registration, const PyGetInitializerLocationFunc& py_get_initializer_location_func, PrivateConstructorTag); /// /// Compiles the input model and saves the result to an output file. /// If the 'output_model_path' is not specified, /// it is generated based on the input model's path by replacing '.onnx' with '_ctx.onnx'. /// /// The path into which to save the compiled model. /// A Status indicating error or success. onnxruntime::Status CompileToFile(const std::string& output_model_path = {}); /// /// Compiles the input model and stores the result into a buffer. /// /// A reference to the output buffer into which to store the /// serialized ONNX model bytes. /// A Status indicating error or success. onnxruntime::Status CompileToBytes(std::string& output_buffer); /// /// Compiles the input model and writes the result into the provided output stream (write functor). /// /// Write functor that encapsulates the stream's state. /// A Status indicating error or success. onnxruntime::Status CompileToOutStream(PyOutStreamWriteFunc& write_func); void SetEpContextDataWriteFunc(PyEpContextDataWriteFunc write_func); void ClearEpContextDataWriteFunc(); private: onnxruntime::Status BeginCompilation(); void EndCompilation() noexcept; onnxruntime::Environment& env_; std::shared_ptr py_ep_selection_registration_; std::shared_ptr py_ep_context_data_read_registration_; std::string input_model_bytes_; PyGetInitializerLocationFunc py_get_initializer_location_func_; PyEpContextDataWriteFunc py_ep_context_data_write_func_; onnxruntime::ModelCompilationOptions model_compile_options_; std::mutex compilation_mutex_; bool compilation_in_progress_{false}; #endif // defined(ORT_MINIMAL_BUILD) }; } // namespace python } // namespace onnxruntime