// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "onnxruntime_pybind.h" // must use this for the include of #include #include #include #include "core/common/logging/logging.h" #include "core/common/logging/sinks/clog_sink.h" #include "core/common/logging/sinks/cerr_sink.h" #include "core/session/environment.h" #include "core/framework/ort_value.h" #include "core/session/inference_session.h" #include PYBIND11_MAKE_OPAQUE(std::vector); namespace onnxruntime { namespace python { extern const char* PYTHON_ORTVALUE_OBJECT_NAME; extern const char* PYTHON_ORTVALUE_NATIVE_OBJECT_ATTR; bool IsNumericNumpyArray(const pybind11::object& py_object); bool IsNumpyArray(pybind11::object& obj); int GetNumpyArrayType(const pybind11::object& obj); bool IsNumericDType(const pybind11::dtype& dtype); TensorShape GetShape(const pybind11::array& arr); int OnnxRuntimeTensorToNumpyType(const DataTypeImpl* tensor_type); MLDataType NumpyTypeToOnnxRuntimeTensorType(int numpy_type); MLDataType OnnxTypeToOnnxRuntimeTensorType(int onnx_element_type); using MemCpyFunc = std::function; using DataTransferAlternative = std::variant; // helpers to get allocator and IDataTransfer from Environment for plugin EP AllocatorPtr GetSharedAllocator(const OrtDevice& device); MemCpyFunc CreateDataTransferMemCpy(const OrtDevice& src_device, const OrtDevice& dst_device); void CpuToCpuMemCpy(void*, const void*, size_t); void CopyDataToTensor(const pybind11::array& py_array, int npy_type, Tensor& tensor, const MemCpyFunc& mem_cpy_to_device = CpuToCpuMemCpy); pybind11::object AddTensorAsPyObj(const OrtValue& val, const DataTransferManager* data_transfer_manager, const std::unordered_map* mem_cpy_to_host_functions); pybind11::object GetPyObjectFromSparseTensor(size_t pos, const OrtValue& ort_value, const DataTransferManager* data_transfer_manager); pybind11::object AddNonTensorAsPyObj(const OrtValue& val, const DataTransferManager* data_transfer_manager, const std::unordered_map* mem_cpy_to_host_functions); OrtMemoryInfo GetMemoryInfoPerDeviceType(const OrtDevice& ort_device); int32_t GetTensorProtoType(const OrtValue& ort_value); #ifdef USE_CUDA void CpuToCudaMemCpy(void* dst, const void* src, size_t num_bytes); void CudaToCpuMemCpy(void* dst, const void* src, size_t num_bytes); const std::unordered_map* GetCudaToHostMemCpyFunction(const OrtDevice&); bool IsCudaDeviceIdValid(const onnxruntime::logging::Logger& logger, int id); AllocatorPtr GetCudaAllocator(OrtDevice::DeviceId id); std::unique_ptr GetGPUDataTransfer(); #endif #ifdef USE_DML AllocatorPtr GetDmlAllocator(OrtDevice::DeviceId id); void CpuToDmlMemCpy(void* dst, const void* src, size_t num_bytes); void DmlToCpuMemCpy(void* dst, const void* src, size_t num_bytes); const std::unordered_map* GetDmlToHostMemCpyFunction(const OrtDevice&); #endif #ifdef USE_MIGRAPHX void CpuToMIGraphXMemCpy(void* dst, const void* src, size_t num_bytes); void MIGraphXToCpuMemCpy(void* dst, const void* src, size_t num_bytes); const std::unordered_map* GetMIGraphXToHostMemCpyFunction(const OrtDevice&); AllocatorPtr GetMIGraphXAllocator(OrtDevice::DeviceId id); #endif #ifdef USE_CANN void CpuToCannMemCpy(void* dst, const void* src, size_t num_bytes); void CannToCpuMemCpy(void* dst, const void* src, size_t num_bytes); const std::unordered_map* GetCannToHostMemCpyFunction(); bool IsCannDeviceIdValid(const onnxruntime::logging::Logger& logger, int id); AllocatorPtr GetCannAllocator(OrtDevice::DeviceId id); #endif void CreateGenericMLValue(const onnxruntime::InputDefList* input_def_list, const AllocatorPtr& alloc, const std::string& name_input, const pybind11::object& value, OrtValue* p_mlvalue, bool accept_only_numpy_array = false, bool use_numpy_data_memory = true, const MemCpyFunc& mem_cpy_to_device = CpuToCpuMemCpy); /// @param zero_copy_non_owning When false (default), CPU tensors that do not own /// their buffer are copied to a new numpy array to prevent dangling pointers /// (e.g. when a model output aliases a numpy input array). Set to true ONLY /// when the caller explicitly manages the backing memory lifetime — currently /// this is limited to OrtValue.numpy(), where the user holds the OrtValue /// Python object and is responsible for keeping it alive. pybind11::object GetPyObjFromTensor(const OrtValue& rtensor, const DataTransferManager* data_transfer_manager = nullptr, const std::unordered_map* mem_cpy_to_host_functions = nullptr, bool zero_copy_non_owning = false); // Update the tensor data in an OrtValue in-place from another OrtValue. // Both OrtValues must contain tensors of the same data type and size. // This function supports various device-to-device transfers. void UpdateOrtValueInplace(OrtValue& dst, const OrtValue& src); // The below two functions are used to convert OrtValue to numpy arrays /// /// This function operates on string tensors. Strings are always /// copied to python and converted to UTF-16/UCS-4/32 depending on the platform. /// This is accomplished using py::cast() /// /// It is an error to pass a non-tensor or a non-string tensor to this function. /// /// Tensor that contains strings /// py::array object pybind11::array StringTensorToNumpyArray(const Tensor& tensor); /// /// Creates a numpy array with shape over OrtValue memory. Numpy array /// does not own the memory, but it holds a copy or OrtValue in a py::capsule. /// OrtValue is destroyed when the numpy array is garbage collected. /// This is used when the OrtValue memory is on CPU. /// /// OrtValue with data /// numpy array pybind11::array PrimitiveTensorToNumpyOverOrtValue(const OrtValue& ort_value); /// /// Creates a numpy array with shape with a copy of OrtValue data. /// This function is used when the OrtValue memory is not on CPU. /// /// Source memory that is not on CPU. /// a variant encapsulating alternatives for copying data /// pybind11::array PrimitiveTensorToNumpyFromDevice(const OrtValue& ort_value, const DataTransferAlternative& data_transfer); template struct DecRefFn { void operator()(T* pyobject) const { Py_XDECREF(pyobject); } }; template using UniqueDecRefPtr = std::unique_ptr>; } // namespace python } // namespace onnxruntime