From 4ab6256e9fac14bfc74282a971086cd50f64d8dd Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 15 Jan 2025 12:20:15 -0500 Subject: [PATCH 1/9] pass test Signed-off-by: Chen Tong --- CMakeLists.txt | 58 ++++++++++++------- MLIR.cmake | 54 ++++++++++------- src/CMakeLists.txt | 10 ++++ src/Runtime/CMakeLists.txt | 14 +++++ src/Runtime/ExecutionSession.cpp | 47 +++++++++++++++ src/Runtime/ExecutionSession.hpp | 9 ++- src/Runtime/OMTensor.inc | 16 +++++ src/Runtime/python/CMakeLists.txt | 45 +++++++++++--- src/Runtime/python/PyExecutionSessionBase.cpp | 14 +++++ src/Runtime/python/PyRuntime.py | 22 ++++--- 10 files changed, 228 insertions(+), 61 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 42609866cf..b3350cfe5b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,6 +11,8 @@ option(ONNX_MLIR_ENABLE_STABLEHLO "Enable StableHLO support." ON) option(ONNX_MLIR_ENABLE_WERROR "Enable warnings as errors." OFF) option(ONNX_MLIR_SUPPRESS_THIRD_PARTY_WARNINGS "Suppress warning in third_party code." ON) option(ONNX_MLIR_ENABLE_JAVA "Set to ON for building the Java runtime, tools, and tests" ON) +option(ONNX_MLIR_ENABLE_PYRUNTIME_LIT "Set to ON for building Python driver of running the compiled model without llvm-project." OFF) +#unset(ONNX_MLIR_ENABLE_PYRUNTIME_LIT CACHE) set(CMAKE_CXX_STANDARD 17) @@ -73,8 +75,10 @@ set(ONNX_MLIR_INCLUDE_PATH ${CMAKE_INCLUDE_OUTPUT_DIRECTORY}) set(ONNX_MLIR_VENDOR ${PACKAGE_VENDOR} CACHE STRING "Vendor-specific text for showing with version information.") -include(CTest) -include(ExternalProject) +if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + include(CTest) + include(ExternalProject) +endif() include(MLIR.cmake) # MLIR.cmake calls find_package(MLIR) which sets LLVM_MINIMUM_PYTHON_VERSION @@ -159,23 +163,29 @@ endif() set(CMAKE_MESSAGE_LOG_LEVEL NOTICE) # Add third party subdirectories and define options appropriate to run their cmakes. -set(pybind11_FIND_QUIETLY ON) -add_subdirectory(third_party/onnx) -add_subdirectory(third_party/pybind11) -add_subdirectory(third_party/rapidcheck) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + add_subdirectory(third_party/onnx) + add_subdirectory(third_party/pybind11) +else() + set(pybind11_FIND_QUIETLY ON) + add_subdirectory(third_party/onnx) + add_subdirectory(third_party/pybind11) -if (ONNX_MLIR_ENABLE_STABLEHLO) - add_subdirectory(third_party/stablehlo EXCLUDE_FROM_ALL) -endif() + add_subdirectory(third_party/rapidcheck) -if (NOT TARGET benchmark) - set(BENCHMARK_USE_BUNDLED_GTEST OFF) - set(BENCHMARK_ENABLE_GTEST_TESTS OFF) - set(BENCHMARK_ENABLE_TESTING OFF) - set(BENCHMARK_ENABLE_WERROR OFF) - # Since LLVM requires C++11 (or higher) it is safe to assume that std::regex is available. - set(HAVE_STD_REGEX ON CACHE BOOL "OK" FORCE) - add_subdirectory(third_party/benchmark) + if (ONNX_MLIR_ENABLE_STABLEHLO) + add_subdirectory(third_party/stablehlo EXCLUDE_FROM_ALL) + endif() + + if (NOT TARGET benchmark) + set(BENCHMARK_USE_BUNDLED_GTEST OFF) + set(BENCHMARK_ENABLE_GTEST_TESTS OFF) + set(BENCHMARK_ENABLE_TESTING OFF) + set(BENCHMARK_ENABLE_WERROR OFF) + # Since LLVM requires C++11 (or higher) it is safe to assume that std::regex is available. + set(HAVE_STD_REGEX ON CACHE BOOL "OK" FORCE) + add_subdirectory(third_party/benchmark) + endif() endif() # All libraries and executables coming from llvm or ONNX-MLIR have had their @@ -207,8 +217,12 @@ if (ONNX_MLIR_ENABLE_STABLEHLO) add_compile_definitions(ONNX_MLIR_ENABLE_STABLEHLO) endif() -add_subdirectory(utils) -add_subdirectory(include) -add_subdirectory(src) -add_subdirectory(docs) -add_subdirectory(test) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + add_subdirectory(src) +else() + add_subdirectory(utils) + add_subdirectory(include) + add_subdirectory(src) + add_subdirectory(docs) + add_subdirectory(test) +endif() diff --git a/MLIR.cmake b/MLIR.cmake index 1a66f6e41e..43ad3244e3 100644 --- a/MLIR.cmake +++ b/MLIR.cmake @@ -1,33 +1,39 @@ # SPDX-License-Identifier: Apache-2.0 -# Must unset LLVM_DIR in cache. Otherwise, when MLIR_DIR changes LLVM_DIR -# won't change accordingly. -unset(LLVM_DIR CACHE) -if (NOT DEFINED MLIR_DIR) - message(FATAL_ERROR "MLIR_DIR is not configured but it is required. " - "Set the cmake option MLIR_DIR, e.g.,\n" - " cmake -DMLIR_DIR=/path/to/llvm-project/build/lib/cmake/mlir ..\n" - ) -endif() +message(STATUS "ONNX_MLIR_ENABLE_PYRUNTIME_LIT: ${ONNX_MLIR_ENABLE_PYRUNTIE_LIT}") +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + function(llvm_update_compile_flags name) + endfunction() +else() + # Must unset LLVM_DIR in cache. Otherwise, when MLIR_DIR changes LLVM_DIR + # won't change accordingly. + unset(LLVM_DIR CACHE) + if (NOT DEFINED MLIR_DIR) + message(FATAL_ERROR "MLIR_DIR is not configured but it is required. " + "Set the cmake option MLIR_DIR, e.g.,\n" + " cmake -DMLIR_DIR=/path/to/llvm-project/build/lib/cmake/mlir ..\n" + ) + endif() -find_package(MLIR REQUIRED CONFIG) + find_package(MLIR REQUIRED CONFIG) -message(STATUS "Using MLIRConfig.cmake in: ${MLIR_DIR}") -message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") + message(STATUS "Using MLIRConfig.cmake in: ${MLIR_DIR}") + message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") -list(APPEND CMAKE_MODULE_PATH "${MLIR_CMAKE_DIR}") -list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") + list(APPEND CMAKE_MODULE_PATH "${MLIR_CMAKE_DIR}") + list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") -include(TableGen) -include(AddLLVM) -include(AddMLIR) + include(TableGen) + include(AddLLVM) + include(AddMLIR) -include(HandleLLVMOptions) + include(HandleLLVMOptions) -include_directories(${LLVM_INCLUDE_DIRS}) -include_directories(${MLIR_INCLUDE_DIRS}) + include_directories(${LLVM_INCLUDE_DIRS}) + include_directories(${MLIR_INCLUDE_DIRS}) -add_definitions(${LLVM_DEFINITIONS}) + add_definitions(${LLVM_DEFINITIONS}) +endif() set(BUILD_SHARED_LIBS ${LLVM_ENABLE_SHARED_LIBS} CACHE BOOL "" FORCE) message(STATUS "BUILD_SHARED_LIBS : " ${BUILD_SHARED_LIBS}) @@ -55,6 +61,7 @@ if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND NOT LLVM_INSTALL_PREFIX) endif() message(STATUS "CMAKE_INSTALL_PREFIX : " ${CMAKE_INSTALL_PREFIX}) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) # The tablegen functions below are modeled based on the corresponding functions # in mlir: https://github.com/llvm/llvm-project/blob/main/mlir/cmake/modules/AddMLIR.cmake function(add_onnx_mlir_dialect_doc dialect dialect_tablegen_file) @@ -126,6 +133,7 @@ function(add_onnx_mlir_interface interface) mlir_tablegen(${interface}.cpp.inc -gen-op-interface-defs) add_public_tablegen_target(OM${interface}IncGen) endfunction() +endif() # add_onnx_mlir_library(name sources... # This function (generally) has the same semantic as add_library. In @@ -158,7 +166,9 @@ function(add_onnx_mlir_library name) ) if (NOT ARG_EXCLUDE_FROM_OM_LIBS) - set_property(GLOBAL APPEND PROPERTY ONNX_MLIR_LIBS ${name}) + if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + set_property(GLOBAL APPEND PROPERTY ONNX_MLIR_LIBS ${name}) + endif() endif() add_library(${name} ${ARG_UNPARSED_ARGUMENTS}) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2c0b45b2d8..031d3a8655 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,5 +1,15 @@ # SPDX-License-Identifier: Apache-2.0 +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + add_subdirectory(Runtime) + # Accelerators introduces a target AcceleratorsInc. Define a dummy one here + add_custom_target(AcceleratorsInc + COMMAND echo "This is the dummy definition for AcceleratorsInc" + ) + add_compile_definitions(ENABLE_PYRUNTIME_LIT) + return() +endif() + add_subdirectory(Accelerators) add_subdirectory(Interface) add_subdirectory(Dialect) diff --git a/src/Runtime/CMakeLists.txt b/src/Runtime/CMakeLists.txt index c32b09c793..f3c8bfb69a 100644 --- a/src/Runtime/CMakeLists.txt +++ b/src/Runtime/CMakeLists.txt @@ -1,8 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 +if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) add_subdirectory(jni) add_subdirectory(omp) +endif() add_subdirectory(python) # TODO: should add for each accelerator its subdirectory that implements InitAccel##name @@ -65,6 +67,17 @@ set_target_properties(OMTensorUtils POSITION_INDEPENDENT_CODE TRUE ) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +add_compile_definitions(ENABLE_PYRUNTIME_LIT) +add_onnx_mlir_library(OMExecutionSession + ExecutionSession.cpp + + EXCLUDE_FROM_OM_LIBS + + LINK_LIBS PUBLIC + OMTensorUtils + ) +else() add_onnx_mlir_library(OMExecutionSession ExecutionSession.cpp @@ -74,6 +87,7 @@ add_onnx_mlir_library(OMExecutionSession OMTensorUtils LLVMSupport ) +endif() set_target_properties(OMExecutionSession PROPERTIES POSITION_INDEPENDENT_CODE TRUE diff --git a/src/Runtime/ExecutionSession.cpp b/src/Runtime/ExecutionSession.cpp index b00446edd7..3941c04327 100644 --- a/src/Runtime/ExecutionSession.cpp +++ b/src/Runtime/ExecutionSession.cpp @@ -16,14 +16,19 @@ #include #include + #include #include #include #include +#ifndef ENABLE_PYRUNTIME_LIT #include "llvm/ADT/SmallString.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" +#else +#include +#endif #include "ExecutionSession.hpp" #include "OMTensorListHelper.hpp" @@ -44,16 +49,24 @@ void ExecutionSession::Init( // If there is no tag, use the model filename without extension as a tag. if (tag == "") { + // ToFix: equivalent implementation of llvm utilities. + // The would not be an urgent issue, because tag is usually "NONE" +#ifndef ENABLE_PYRUNTIME_LIT std::string fname = llvm::sys::path::filename(sharedLibPath).str(); llvm::SmallString<256> fnameWithoutExt(fname); llvm::sys::path::replace_extension(fnameWithoutExt, ""); tag = fnameWithoutExt.str().lower(); +#endif } // tag = "NONE" to use functions without tag. std::string lowDashTag; + // ToFix: equivalent implementation of llv::StringRef +#ifndef ENABLE_PYRUNTIME_LIT + // Assume tag is always NONE if (!llvm::StringRef(tag).equals_insensitive("NONE")) lowDashTag = "_" + tag; +#endif #if defined(_WIN32) // Use functions without tags on Windows since we cannot define at compile @@ -63,31 +76,55 @@ void ExecutionSession::Init( #endif // Init symbols used by execution session. +#ifndef ENABLE_PYRUNTIME_LIT _sharedLibraryHandle = llvm::sys::DynamicLibrary::getLibrary(sharedLibPath.c_str()); if (!_sharedLibraryHandle.isValid()) throw std::runtime_error(reportLibraryOpeningError(sharedLibPath)); +#else + // Copy code from llvm/lib/Support/DynamicLibrary.cpp, especially the flags + // ToFix: copy the lock related code too. + _sharedLibraryHandle = dlopen(sharedLibPath.c_str(), RTLD_LAZY | RTLD_GLOBAL); + if (!_sharedLibraryHandle) + throw std::runtime_error(reportLibraryOpeningError(sharedLibPath)); +#endif std::string queryEntryPointsNameWithTag = _queryEntryPointsName + lowDashTag; +#ifndef ENABLE_PYRUNTIME_LIT _queryEntryPointsFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( queryEntryPointsNameWithTag.c_str())); +#else + _queryEntryPointsFunc = reinterpret_cast( + dlsym(_sharedLibraryHandle, queryEntryPointsNameWithTag.c_str())); +#endif + if (!_queryEntryPointsFunc) throw std::runtime_error( reportSymbolLoadingError(queryEntryPointsNameWithTag)); std::string inputSignatureNameWithTag = _inputSignatureName + lowDashTag; +#ifndef ENABLE_PYRUNTIME_LIT _inputSignatureFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( inputSignatureNameWithTag.c_str())); +#else + _inputSignatureFunc = reinterpret_cast( + dlsym(_sharedLibraryHandle, inputSignatureNameWithTag.c_str())); +#endif if (!_inputSignatureFunc) throw std::runtime_error( reportSymbolLoadingError(inputSignatureNameWithTag)); std::string outputSignatureNameWithTag = _outputSignatureName + lowDashTag; +#ifndef ENABLE_PYRUNTIME_LIT _outputSignatureFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( outputSignatureNameWithTag.c_str())); +#else + _outputSignatureFunc = reinterpret_cast( + dlsym(_sharedLibraryHandle, outputSignatureNameWithTag.c_str())); +#endif if (!_outputSignatureFunc) throw std::runtime_error( reportSymbolLoadingError(outputSignatureNameWithTag)); @@ -114,8 +151,13 @@ void ExecutionSession::Init( } ExecutionSession::~ExecutionSession() { +#ifndef ENABLE_PYRUNTIME_LIT if (_sharedLibraryHandle.isValid()) llvm::sys::DynamicLibrary::closeLibrary(_sharedLibraryHandle); +#else + if (!_sharedLibraryHandle) + dlclose(_sharedLibraryHandle); +#endif } // ============================================================================= @@ -132,8 +174,13 @@ const std::string *ExecutionSession::queryEntryPoints( void ExecutionSession::setEntryPoint(const std::string &entryPointName) { if (!isInitialized) throw std::runtime_error(reportInitError()); +#ifndef ENABLE_PYRUNTIME_LIT _entryPointFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol(entryPointName.c_str())); +#else + _entryPointFunc = reinterpret_cast( + dlsym(_sharedLibraryHandle, entryPointName.c_str())); +#endif if (!_entryPointFunc) throw std::runtime_error(reportSymbolLoadingError(entryPointName)); _entryPointName = entryPointName; diff --git a/src/Runtime/ExecutionSession.hpp b/src/Runtime/ExecutionSession.hpp index 856a1005cc..a4b58c42ad 100644 --- a/src/Runtime/ExecutionSession.hpp +++ b/src/Runtime/ExecutionSession.hpp @@ -21,7 +21,12 @@ #include #include "OnnxMlirRuntime.h" +#ifndef ENABLE_PYRUNTIME_LIT #include "llvm/Support/DynamicLibrary.h" +typedef llvm::sys::DynamicLibrary DynamicLibraryHandleType; +#else +typedef void* DynamicLibraryHandleType; +#endif namespace onnx_mlir { @@ -62,7 +67,7 @@ class ExecutionSession { // defaultEntryPoint is false or there are multiple entry points in the model. void setEntryPoint(const std::string &entryPointName); - llvm::sys::DynamicLibrary &getSharedLibraryHandle() { + DynamicLibraryHandleType &getSharedLibraryHandle() { return _sharedLibraryHandle; }; @@ -100,7 +105,7 @@ class ExecutionSession { bool isInitialized = false; // Handler to the shared library file being loaded. - llvm::sys::DynamicLibrary _sharedLibraryHandle; + DynamicLibraryHandleType _sharedLibraryHandle; // Tag used to compile the model. By default, it is the model filename without // extension. diff --git a/src/Runtime/OMTensor.inc b/src/Runtime/OMTensor.inc index 49e24befc3..c2d4b3860a 100644 --- a/src/Runtime/OMTensor.inc +++ b/src/Runtime/OMTensor.inc @@ -44,7 +44,9 @@ #include "src/Runtime/OMTensorHelper.hpp" #endif +#ifndef ENABLE_PYRUNTIME_LIT #include "src/Support/SmallFPConversion.h" +#endif #if defined(__APPLE__) // __errno_location() is called from krnl::emitErrNo() to set errno in @@ -52,6 +54,20 @@ int *__attribute__((__weak__)) __errno_location(void) { return &errno; } #endif +#ifdef ENABLE_PYRUNTIME_LIT +// The implementation depends on src/Utility and llvm. Will be solved in +// another PR. Here are just dummy definitions for compilation +float om_f16_to_f32(uint16_t a) { + return (float) 0; +} + +uint16_t om_f32_to_f16(uint16_t a) { + return (uint16_t) 0; +} +#endif + + + // On some platforms LLVM generates f16 conversion code that calls some // of these C runtime functions. // TODO: Figure out if we could get these with llvm/compiler-rt in a diff --git a/src/Runtime/python/CMakeLists.txt b/src/Runtime/python/CMakeLists.txt index 16a93e9eea..43374c6b0b 100644 --- a/src/Runtime/python/CMakeLists.txt +++ b/src/Runtime/python/CMakeLists.txt @@ -11,17 +11,32 @@ file(GENERATE ) # TODO: Remove pybind11::python_link_helper after cmake version bumped to 3.16+ -add_onnx_mlir_library(OMPyExecutionSessionBase - PyExecutionSessionBase.cpp +if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + add_onnx_mlir_library(OMPyExecutionSessionBase + PyExecutionSessionBase.cpp - EXCLUDE_FROM_OM_LIBS + EXCLUDE_FROM_OM_LIBS - LINK_LIBS PUBLIC - OMExecutionSession - OMMlirUtilities - pybind11::embed - pybind11::python_link_helper + LINK_LIBS PUBLIC + OMExecutionSession + OMMlirUtilities + pybind11::embed + pybind11::python_link_helper + ) +else() + add_compile_definitions(ENABLE_PYRUNTIME_LIT) + add_onnx_mlir_library(OMPyExecutionSessionBase + PyExecutionSessionBase.cpp + + EXCLUDE_FROM_OM_LIBS + + LINK_LIBS PUBLIC + OMExecutionSession + pybind11::embed + pybind11::python_link_helper ) +endif() + if(MSVC) target_link_libraries(OMPyExecutionSessionBase PRIVATE pybind11::windows_extras @@ -92,6 +107,19 @@ install(TARGETS PyRuntimeC DESTINATION lib ) +# Target to prepare onnxmlir package +add_custom_target(OMCreatePyRuntimePackage + COMMAND cp -r ${CMAKE_CURRENT_SOURCE_DIR}/onnxmlir ${CMAKE_CURRENT_BINARY_DIR} + COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/onnxmlirdocker.py ${CMAKE_CURRENT_BINARY_DIR}/onnxmlir/src/onnxmlir + COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/PyRuntime.py ${CMAKE_CURRENT_BINARY_DIR}/onnxmlir/src/onnxmlir + COMMAND cp ${ONNX_MLIR_BIN_ROOT}/${CMAKE_BUILD_TYPE}/lib/PyRuntimeC.*.so ${CMAKE_CURRENT_BINARY_DIR}/onnxmlir/src/onnxmlir/ + DEPENDS PyRuntimeC + ) + +if(ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + return() +endif() + pybind11_add_module(PyCompileAndRuntimeC PyOMCompileExecutionSession.cpp) add_dependencies(PyCompileAndRuntimeC onnx_proto) target_compile_options(PyCompileAndRuntimeC @@ -118,3 +146,4 @@ llvm_update_compile_flags(PyCompileAndRuntimeC) install(TARGETS PyCompileAndRuntimeC DESTINATION lib ) + diff --git a/src/Runtime/python/PyExecutionSessionBase.cpp b/src/Runtime/python/PyExecutionSessionBase.cpp index b98fb0de23..dc25eb5d99 100644 --- a/src/Runtime/python/PyExecutionSessionBase.cpp +++ b/src/Runtime/python/PyExecutionSessionBase.cpp @@ -13,7 +13,13 @@ // //===----------------------------------------------------------------------===// +#ifndef ENABLE_PYRUNTIME_LIT #include "src/Support/SmallFP.hpp" +#else +// ToFix: how to handle float_16 +#endif + +// SuppressWarnings.h only defines macros, not functions. #include "src/Support/SuppressWarnings.h" SUPPRESS_WARNINGS_PUSH @@ -30,6 +36,11 @@ namespace detail { // Ref: https://github.com/pybind/pybind11/issues/1776 // // This implementation is copied from https://github.com/PaddlePaddle/Paddle + +#ifndef ENABLE_PYRUNTIME_LIT +// ToFix: support for float_16 +// Now onnx_mlir::float_16 is not defined without SmallFP.h + template <> struct npy_format_descriptor { static py::dtype dtype() { @@ -48,6 +59,7 @@ struct npy_format_descriptor { } static constexpr auto name = _("float16"); }; +#endif } // namespace detail } // namespace pybind11 @@ -171,8 +183,10 @@ std::vector PyExecutionSessionBase::pyRun( // string type missing else if (py::isinstance>(inputPyArray)) dtype = ONNX_TYPE_BOOL; +#ifndef ENABLE_PYRUNTIME_LIT else if (py::isinstance>(inputPyArray)) dtype = ONNX_TYPE_FLOAT16; +#endif else if (py::isinstance>(inputPyArray)) dtype = ONNX_TYPE_DOUBLE; else if (py::isinstance>(inputPyArray)) diff --git a/src/Runtime/python/PyRuntime.py b/src/Runtime/python/PyRuntime.py index a57b019fce..a24da63bab 100644 --- a/src/Runtime/python/PyRuntime.py +++ b/src/Runtime/python/PyRuntime.py @@ -9,13 +9,21 @@ ################################################################################ import numpy as np -try: - from PyRuntimeC import OMExecutionSession as OMExecutionSession_ -except ImportError: - raise ImportError( - "Looks like you did not build the PyRuntimeC target, build it by running `make PyRuntimeC`." - "You may need to set ONNX_MLIR_HOME to `onnx-mlir/build/Debug` since `make PyRuntimeC` outputs to `build/Debug` by default" - ) +if __package__ == "onnxmlir": + try: + from .PyRuntimeC import OMExecutionSession as OMExecutionSession_ + except ImportError: + raise ImportError( + "Failure to load the prebuild PyRuntimeC.*.so." + ) +else: + try: + from PyRuntimeC import OMExecutionSession as OMExecutionSession_ + except ImportError: + raise ImportError( + "Looks like you did not build the PyRuntimeC target, build it by running `make PyRuntimeC`." + "You may need to set ONNX_MLIR_HOME to `onnx-mlir/build/Debug` since `make PyRuntimeC` outputs to `build/Debug` by default" + ) class OMExecutionSession(OMExecutionSession_): From 49034b5f40e9ed8f62edf73dfd81050e0a3a64f3 Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 15 Jan 2025 12:28:43 -0500 Subject: [PATCH 2/9] package Signed-off-by: Chen Tong --- src/Runtime/python/onnxmlir/LICENSE | 201 ++++++++++++++++++ src/Runtime/python/onnxmlir/README.md | 68 ++++++ src/Runtime/python/onnxmlir/VERSION_NUMBER | 1 + src/Runtime/python/onnxmlir/pyproject.toml | 26 +++ .../python/onnxmlir/src/onnxmlir/__init__.py | 1 + src/Runtime/python/onnxmlir/tests/test_1.py | 10 + src/Runtime/python/onnxmlir/tests/test_2.py | 11 + src/Runtime/python/onnxmlir/tests/test_3.py | 12 ++ .../python/onnxmlir/tests/test_add.onnx | Bin 0 -> 129 bytes .../python/onnxmlir/tests/test_standalone.py | 16 ++ src/Runtime/python/onnxmlirdocker.py | 139 ++++++++++++ 11 files changed, 485 insertions(+) create mode 100644 src/Runtime/python/onnxmlir/LICENSE create mode 100644 src/Runtime/python/onnxmlir/README.md create mode 100644 src/Runtime/python/onnxmlir/VERSION_NUMBER create mode 100644 src/Runtime/python/onnxmlir/pyproject.toml create mode 100644 src/Runtime/python/onnxmlir/src/onnxmlir/__init__.py create mode 100644 src/Runtime/python/onnxmlir/tests/test_1.py create mode 100644 src/Runtime/python/onnxmlir/tests/test_2.py create mode 100644 src/Runtime/python/onnxmlir/tests/test_3.py create mode 100644 src/Runtime/python/onnxmlir/tests/test_add.onnx create mode 100644 src/Runtime/python/onnxmlir/tests/test_standalone.py create mode 100644 src/Runtime/python/onnxmlirdocker.py diff --git a/src/Runtime/python/onnxmlir/LICENSE b/src/Runtime/python/onnxmlir/LICENSE new file mode 100644 index 0000000000..20e4bd8566 --- /dev/null +++ b/src/Runtime/python/onnxmlir/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/Runtime/python/onnxmlir/README.md b/src/Runtime/python/onnxmlir/README.md new file mode 100644 index 0000000000..af1f8b18c0 --- /dev/null +++ b/src/Runtime/python/onnxmlir/README.md @@ -0,0 +1,68 @@ +This package provides a python interface to use onnx-mlir compiler to run inference of an onnx model similar to onnxruntime interface. The basic parameters of the interface are supported with options ignored. + +## Description +Let's start with [an onnxrutime example](https://onnxruntime.ai/docs/get-started/with-python#pytorch-cv): +``` +import onnxruntime as ort +import numpy as np +x, y = test_data[0][0], test_data[0][1] +ort_sess = ort.InferenceSession('fashion_mnist_model.onnx') +outputs = ort_sess.run(None, {'input': x.numpy()}) + +# Print Result +predicted, actual = classes[outputs[0][0].argmax(0)], classes[y] +print(f'Predicted: "{predicted}", Actual: "{actual}"') +``` + +With onnxmlir package, onnx-mlir can be used to replace onnxrutnime as follows: +``` +import onnxmlir as ort +import numpy as np +x, y = test_data[0][0], test_data[0][1] +ort_sess = ort.InferenceSession('fashion_mnist_model.onnx') +outputs = ort_sess.run(None, {'input': x.numpy()}) + +# Print Result +predicted, actual = classes[outputs[0][0].argmax(0)], classes[y] +print(f'Predicted: "{predicted}", Actual: "{actual}"') +``` + +In current version, the onnx-mlir compiler is not contained in the python +package yet. Use env variable ONNX_MLIR_HOME to specify the location of the onnx-mlir compiler to be used. For example `export ONNX_MLIR_HOME=/mypath/onnx-mlir/build/Debug`. + +Another way to run the onnx model is to precompile it into a static library first. +``` +onnx-mlir -O3 fashin_mnist_mode.onnx +``` + +This compilation will generate fashin_mnist_mode.so. Then the library can be used as model in the Python script as follows: +``` +import onnxmlir as ort +import numpy as np +x, y = test_data[0][0], test_data[0][1] +ort_sess = ort.InferenceSession('fashion_mnist_model.so') +outputs = ort_sess.run(None, {'input': x.numpy()}) + +# Print Result +predicted, actual = classes[outputs[0][0].argmax(0)], classes[y] +print(f'Predicted: "{predicted}", Actual: "{actual}"') +``` + +This package supports list or dictionary for input and output. For example, the input for run could be list of tensor. +``` +outputs = ort_sess.run(None, [a, b, c]) +``` + +Another extra named argment for InferenceSession is introduced to specify the extra arguments accepted by onnx-mlir/utils/RunONNXModel.py. Here is an example: +``` +sess = onnxmlir.inferenceSession("test_add.onnx", options='--compile-args="-O3 --parallel" --print-output') +``` + +## Installation + +### Install from local directory +At top of onnx-mlir: `pip3 install utils/onnxmlir` + +### Install from repo +After the package is uploaded, you can install with 'pip3 install onnxmlir` + diff --git a/src/Runtime/python/onnxmlir/VERSION_NUMBER b/src/Runtime/python/onnxmlir/VERSION_NUMBER new file mode 100644 index 0000000000..6e8bf73aa5 --- /dev/null +++ b/src/Runtime/python/onnxmlir/VERSION_NUMBER @@ -0,0 +1 @@ +0.1.0 diff --git a/src/Runtime/python/onnxmlir/pyproject.toml b/src/Runtime/python/onnxmlir/pyproject.toml new file mode 100644 index 0000000000..612e38990a --- /dev/null +++ b/src/Runtime/python/onnxmlir/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" +[project] +name = "onnxmlir" +version = "0.1.0" +authors = [ + { name="Tong Chen", email="chentong@us.ibm.com" }, + { name="Alexandre Eichenberger", email="alexe@us.ibm.com" }, +] +description = "Python driver to compile/run onnx model with onnx-mlir" +readme = "README.md" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: POSIX :: Linux", +] +dependences = [ + "numpy", + "docker", +] + +[project.urls] +Homepage = "https://github.com/onnx/onnx-mlir" +Issues = "https://github.com/onnx/onnx-mlir/issues" diff --git a/src/Runtime/python/onnxmlir/src/onnxmlir/__init__.py b/src/Runtime/python/onnxmlir/src/onnxmlir/__init__.py new file mode 100644 index 0000000000..c35009abef --- /dev/null +++ b/src/Runtime/python/onnxmlir/src/onnxmlir/__init__.py @@ -0,0 +1 @@ +from .onnxmlirdocker import InferenceSession diff --git a/src/Runtime/python/onnxmlir/tests/test_1.py b/src/Runtime/python/onnxmlir/tests/test_1.py new file mode 100644 index 0000000000..50564a6fde --- /dev/null +++ b/src/Runtime/python/onnxmlir/tests/test_1.py @@ -0,0 +1,10 @@ +# Test: no name for input and output +import numpy as np +import onnxmlir + +a = np.zeros((3, 4, 5), dtype=np.float32) +b = a + 4 + +sess = onnxmlir.InferenceSession("test_add.onnx") +r = sess.run(None, [a, b]) +print(r) diff --git a/src/Runtime/python/onnxmlir/tests/test_2.py b/src/Runtime/python/onnxmlir/tests/test_2.py new file mode 100644 index 0000000000..5cc56b2ca9 --- /dev/null +++ b/src/Runtime/python/onnxmlir/tests/test_2.py @@ -0,0 +1,11 @@ +import numpy as np +import onnxmlir + +a0 = np.zeros((3, 4, 5), dtype=np.float32) +a = a0 + 2 +b = a0 + 4 + +sess = onnxmlir.InferenceSession("test_add.onnx") +# The name for input is specified by onnx model. +r = sess.run(["my_out"], {"x": a, "y": b}) +print(r) diff --git a/src/Runtime/python/onnxmlir/tests/test_3.py b/src/Runtime/python/onnxmlir/tests/test_3.py new file mode 100644 index 0000000000..d34defba09 --- /dev/null +++ b/src/Runtime/python/onnxmlir/tests/test_3.py @@ -0,0 +1,12 @@ +import numpy as np +import onnxmlir + +a0 = np.zeros((3, 4, 5), dtype=np.float32) +a = a0 + 2 +b = a0 + 4 + +sess = onnxmlir.InferenceSession( + "test_add.onnx", options='--compile-args="-O3 --parallel" --print-output' +) +r = sess.run(["my_out"], {"x": a, "y": b}) +print(r) diff --git a/src/Runtime/python/onnxmlir/tests/test_add.onnx b/src/Runtime/python/onnxmlir/tests/test_add.onnx new file mode 100644 index 0000000000000000000000000000000000000000..8aa4ab2bc385ac70420f1d31868757a543650cb9 GIT binary patch literal 129 zcmd;J7vf1uOwLZtOVKS!EiSRj Date: Wed, 15 Jan 2025 14:03:31 -0500 Subject: [PATCH 3/9] clean makefile Signed-off-by: Chen Tong --- CMakeLists.txt | 5 ----- MLIR.cmake | 1 - 2 files changed, 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b3350cfe5b..54e72b2d53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,6 @@ option(ONNX_MLIR_ENABLE_WERROR "Enable warnings as errors." OFF) option(ONNX_MLIR_SUPPRESS_THIRD_PARTY_WARNINGS "Suppress warning in third_party code." ON) option(ONNX_MLIR_ENABLE_JAVA "Set to ON for building the Java runtime, tools, and tests" ON) option(ONNX_MLIR_ENABLE_PYRUNTIME_LIT "Set to ON for building Python driver of running the compiled model without llvm-project." OFF) -#unset(ONNX_MLIR_ENABLE_PYRUNTIME_LIT CACHE) set(CMAKE_CXX_STANDARD 17) @@ -213,10 +212,6 @@ if (ONNX_MLIR_SUPPRESS_THIRD_PARTY_WARNINGS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSUPPRESS_THIRD_PARTY_WARNINGS") endif() -if (ONNX_MLIR_ENABLE_STABLEHLO) - add_compile_definitions(ONNX_MLIR_ENABLE_STABLEHLO) -endif() - if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) add_subdirectory(src) else() diff --git a/MLIR.cmake b/MLIR.cmake index 43ad3244e3..bc51ad937f 100644 --- a/MLIR.cmake +++ b/MLIR.cmake @@ -1,6 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -message(STATUS "ONNX_MLIR_ENABLE_PYRUNTIME_LIT: ${ONNX_MLIR_ENABLE_PYRUNTIE_LIT}") if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) function(llvm_update_compile_flags name) endfunction() From beff2e3b3c7fdbff32cf14cbcc18a4742cc044e9 Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 15 Jan 2025 15:23:30 -0500 Subject: [PATCH 4/9] document Signed-off-by: Chen Tong --- docs/BuildPyRuntimeLit.md | 35 ++++++++++ src/Runtime/ExecutionSession.cpp | 9 ++- src/Runtime/ExecutionSession.hpp | 2 +- src/Runtime/python/PyRuntime.py | 4 +- .../python/onnxmlir/tests/test_standalone.py | 6 +- src/Runtime/python/onnxmlirdocker.py | 68 +++++++++++-------- utils/build-pyruntime-lit.sh | 15 ++++ 7 files changed, 99 insertions(+), 40 deletions(-) create mode 100644 docs/BuildPyRuntimeLit.md create mode 100644 utils/build-pyruntime-lit.sh diff --git a/docs/BuildPyRuntimeLit.md b/docs/BuildPyRuntimeLit.md new file mode 100644 index 0000000000..e50f9bfa12 --- /dev/null +++ b/docs/BuildPyRuntimeLit.md @@ -0,0 +1,35 @@ +# How to build and use PyRuntime lit + +## Purpsoe + +PyRuntime lit is a different way to build the original PyRuntime (src/Runtime/python). +All necessary dependence, such as llvm_project and onnx-mlir compiler is removed. The purpose is to easily build the python driver for the model execution on +different systems. Currently, only the OMTenserUtils (src/Runtime), Python driver (src/Runtime/python), third_party/onnx and third_party/pybind11 are built. + +The build of PyRuntime lit is controlled by a CMake option: ONNX_MLIR_ENABLE_PYRUNTIME_LIT. Without this option to cmake, the whole system remains the same. + +## Functionalities +1. Build the python driver without llvm_project and onnx-mlir compiler built. +2. The python driver can be used with utils/RunONNXModel.py, or onnxmlir python package. +3. With PyRuntime lit, the compiler has not been built locally and docker image of onnx-mlir has to be usd to compile the model. The onnxmlir package contains +the python code to use python docker package to perform the compilation. Alternatively, the old script, onnx-mlir/docker/onnx-mlir.py, can do the fulfill the same task with subprocess and docker CLI. + +## How to use +You can find the script for build and run at "onnx-mlir/utils/build-pyruntime-lit.sh. +``` +#!/bin/bash + +# Assume you are in an empty directory for build in cloned onnx-mlir. +# Usually it is "your_path/onnx-mlir/build" +# then you can run this script as "../util/build-pyruntime-lit.sh" + +cmake .. -DONNX_MLIR_ENABLE_PYRUNTIME_LIT=ON +make +make OMCreatePyRuntimePackage + +# Install the package +pip3 install src/Runtime/python/onnxmlir + +# Run test case +python3 src/Runtime/python/onnxmlir/test/test_1.py +``` diff --git a/src/Runtime/ExecutionSession.cpp b/src/Runtime/ExecutionSession.cpp index 3941c04327..222e0a5be3 100644 --- a/src/Runtime/ExecutionSession.cpp +++ b/src/Runtime/ExecutionSession.cpp @@ -16,7 +16,6 @@ #include #include - #include #include #include @@ -83,7 +82,7 @@ void ExecutionSession::Init( throw std::runtime_error(reportLibraryOpeningError(sharedLibPath)); #else // Copy code from llvm/lib/Support/DynamicLibrary.cpp, especially the flags - // ToFix: copy the lock related code too. + // ToFix: copy the lock related code too. _sharedLibraryHandle = dlopen(sharedLibPath.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (!_sharedLibraryHandle) throw std::runtime_error(reportLibraryOpeningError(sharedLibPath)); @@ -96,7 +95,7 @@ void ExecutionSession::Init( queryEntryPointsNameWithTag.c_str())); #else _queryEntryPointsFunc = reinterpret_cast( - dlsym(_sharedLibraryHandle, queryEntryPointsNameWithTag.c_str())); + dlsym(_sharedLibraryHandle, queryEntryPointsNameWithTag.c_str())); #endif if (!_queryEntryPointsFunc) @@ -151,7 +150,7 @@ void ExecutionSession::Init( } ExecutionSession::~ExecutionSession() { -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIT if (_sharedLibraryHandle.isValid()) llvm::sys::DynamicLibrary::closeLibrary(_sharedLibraryHandle); #else @@ -174,7 +173,7 @@ const std::string *ExecutionSession::queryEntryPoints( void ExecutionSession::setEntryPoint(const std::string &entryPointName) { if (!isInitialized) throw std::runtime_error(reportInitError()); -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIT _entryPointFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol(entryPointName.c_str())); #else diff --git a/src/Runtime/ExecutionSession.hpp b/src/Runtime/ExecutionSession.hpp index a4b58c42ad..a53dce0ecd 100644 --- a/src/Runtime/ExecutionSession.hpp +++ b/src/Runtime/ExecutionSession.hpp @@ -25,7 +25,7 @@ #include "llvm/Support/DynamicLibrary.h" typedef llvm::sys::DynamicLibrary DynamicLibraryHandleType; #else -typedef void* DynamicLibraryHandleType; +typedef void *DynamicLibraryHandleType; #endif namespace onnx_mlir { diff --git a/src/Runtime/python/PyRuntime.py b/src/Runtime/python/PyRuntime.py index a24da63bab..58534eab93 100644 --- a/src/Runtime/python/PyRuntime.py +++ b/src/Runtime/python/PyRuntime.py @@ -13,9 +13,7 @@ try: from .PyRuntimeC import OMExecutionSession as OMExecutionSession_ except ImportError: - raise ImportError( - "Failure to load the prebuild PyRuntimeC.*.so." - ) + raise ImportError("Failure to load the prebuild PyRuntimeC.*.so.") else: try: from PyRuntimeC import OMExecutionSession as OMExecutionSession_ diff --git a/src/Runtime/python/onnxmlir/tests/test_standalone.py b/src/Runtime/python/onnxmlir/tests/test_standalone.py index b025103512..6114b3f6b1 100644 --- a/src/Runtime/python/onnxmlir/tests/test_standalone.py +++ b/src/Runtime/python/onnxmlir/tests/test_standalone.py @@ -2,15 +2,15 @@ import numpy as np import onnxmlirdocker -#sess = onnxmlirdocker.InferenceSession("test_add.so") +# sess = onnxmlirdocker.InferenceSession("test_add.so") sess = onnxmlirdocker.InferenceSession("test_add.onnx") a = np.zeros((3, 4, 5), dtype=np.float32) b = a + 4 # Run with list of array -#r = sess.run(None, [a, b]) +# r = sess.run(None, [a, b]) # Run with dictionary -r = sess.run(None, {'x': a, 'y': b}) +r = sess.run(None, {"x": a, "y": b}) print(r) diff --git a/src/Runtime/python/onnxmlirdocker.py b/src/Runtime/python/onnxmlirdocker.py index 6d9443e58b..2fc1789fc4 100644 --- a/src/Runtime/python/onnxmlirdocker.py +++ b/src/Runtime/python/onnxmlirdocker.py @@ -5,44 +5,42 @@ import tempfile import json + def get_names_in_signature(signature): - names = [] + names = [] # Load the input signature. signature_dict = json.loads(signature) for sig in signature_dict: names.append(sig["name"]) return names + class InferenceSession: def __init__(self, model_path, **kwargs): - if model_path.endswith(".mlir") : + if model_path.endswith(".mlir"): model_suffix = ".mlir" - elif model_path.endswith(".onnx") : + elif model_path.endswith(".onnx"): model_suffix = ".onnx" - elif model_path.endswith(".so") : + elif model_path.endswith(".so"): self.compiled_lib = os.path.abspath(model_path) self.session = self.getSession() - return; - else : - print( - "Invalid input model path. Must end with .onnx or .mlir or .onnxtext" - ) + return + else: + print("Invalid input model path. Must end with .onnx or .mlir or .onnxtext") exit(1) if "compile-options" in kwargs.keys(): self.compile_options = kwargs["compile-options"] else: self.compile_options = "" - if "onnx-mlir-container" in kwargs.keys(): self.compiler_container = kwargs["onnx-mlir-container"] else: # Default image # The compiler command may have different path in different image - #self.onnx_mlir_image = "ghcr.io/onnxmlir/onnx-mlir-dev" + # self.onnx_mlir_image = "ghcr.io/onnxmlir/onnx-mlir-dev" self.onnx_mlir_image = "onnxmlir/onnx-mlir-dev" - # Path to mount the model to the image self.container_model_dirname = "/myinput" @@ -57,25 +55,41 @@ def __init__(self, model_path, **kwargs): absolute_path = os.path.abspath(self.model_path) self.model_basename = os.path.basename(absolute_path) self.model_dirname = os.path.dirname(absolute_path) - + # Compiled library command_str += " " + self.compile_options - command_str += " " + os.path.join(self.container_model_dirname, self.model_basename) + command_str += " " + os.path.join( + self.container_model_dirname, self.model_basename + ) # ToFix: should use temporary directory for compilation, and # use "-o" to put the compiled library in the temporary directory. self.output_tempdir = tempfile.TemporaryDirectory() self.output_dirname = self.output_tempdir.name - self.compiled_model = os.path.join(self.output_dirname, self.model_basename.removesuffix(model_suffix)+".so") - command_str += " -o " + os.path.join(self.container_output_dirname, self.model_basename.removesuffix(model_suffix)) + self.compiled_model = os.path.join( + self.output_dirname, self.model_basename.removesuffix(model_suffix) + ".so" + ) + command_str += " -o " + os.path.join( + self.container_output_dirname, + self.model_basename.removesuffix(model_suffix), + ) self.container_client = docker.from_env() # Logically, the model directory could be mounted as read only. # But wrong time error occurred with "r" mode - msg=self.container_client.containers.run(self.onnx_mlir_image, + msg = self.container_client.containers.run( + self.onnx_mlir_image, command_str, - volumes={self.model_dirname: {'bind': self.container_model_dirname, 'mode': 'rw'}, self.output_dirname: {'bind': self.container_output_dirname, 'mode': 'rw'} - } + volumes={ + self.model_dirname: { + "bind": self.container_model_dirname, + "mode": "rw", + }, + self.output_dirname: { + "bind": self.container_output_dirname, + "mode": "rw", + }, + }, ) print("afterwards tempdir: ", [f for f in os.listdir(self.output_dirname)]) self.session = self.getSession() @@ -85,24 +99,22 @@ def getSession(self): # are within the package. Path in the pakcage should be used. # Otherwise, env variable ONNX_MLIR_HOME is used to for import path if __package__ == "onnxmlir": - try: + try: from .PyRuntime import OMExecutionSession except ImportError: - raise ImportError( - " Error in importing PyRuntime for onnxmlir package" - ) + raise ImportError(" Error in importing PyRuntime for onnxmlir package") else: if not os.environ.get("ONNX_MLIR_HOME", None): raise RuntimeError( - "Environment variable ONNX_MLIR_HOME is not set, please set it to the path to " + "Environment variable ONNX_MLIR_HOME is not set, please set it to the path to " "the HOME directory for onnx-mlir. The HOME directory for onnx-mlir refers to " "the parent folder containing the bin, lib, etc sub-folders in which ONNX-MLIR " - "execu tables and libraries can be found, typically `onnx-mlir/build/Debug`" - ) + "execu tables and libraries can be found, typically `onnx-mlir/build/Debug`" + ) RUNTIME_DIR = os.path.join(os.environ["ONNX_MLIR_HOME"], "lib") sys.path.append(RUNTIME_DIR) - try: + try: from PyRuntime import OMExecutionSession except ImportError: raise ImportError( @@ -135,5 +147,5 @@ def run(self, outputname, input_feed, **kwargs): # Provide random value inputs print("error: input is not provided. ToFix: random input") exit(1) - + return self.session.run(inputs) diff --git a/utils/build-pyruntime-lit.sh b/utils/build-pyruntime-lit.sh new file mode 100644 index 0000000000..063ae4f24f --- /dev/null +++ b/utils/build-pyruntime-lit.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Assume you are in an empty directory for build in cloned onnx-mlir. +# Usually it is "your_path/onnx-mlir/build" +# then you can run this script as "../util/build-pyruntime-lit.sh" + +cmake .. -DONNX_MLIR_ENABLE_PYRUNTIME_LIT=ON +make +make OMCreatePyRuntimePackage + +# Install the package +pip3 install src/Runtime/python/onnxmlir + +# Run test case +python3 src/Runtime/python/onnxmlir/test/test_1.py From 28584ddb70951fbe7e05546a7ca7fca43027ce27 Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 15 Jan 2025 16:19:55 -0500 Subject: [PATCH 5/9] fix MLIR.cmake Signed-off-by: Chen Tong --- MLIR.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/MLIR.cmake b/MLIR.cmake index bc51ad937f..da24f14126 100644 --- a/MLIR.cmake +++ b/MLIR.cmake @@ -60,7 +60,6 @@ if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND NOT LLVM_INSTALL_PREFIX) endif() message(STATUS "CMAKE_INSTALL_PREFIX : " ${CMAKE_INSTALL_PREFIX}) -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) # The tablegen functions below are modeled based on the corresponding functions # in mlir: https://github.com/llvm/llvm-project/blob/main/mlir/cmake/modules/AddMLIR.cmake function(add_onnx_mlir_dialect_doc dialect dialect_tablegen_file) @@ -132,7 +131,6 @@ function(add_onnx_mlir_interface interface) mlir_tablegen(${interface}.cpp.inc -gen-op-interface-defs) add_public_tablegen_target(OM${interface}IncGen) endfunction() -endif() # add_onnx_mlir_library(name sources... # This function (generally) has the same semantic as add_library. In From a92ccc2bb4f5035dc92624a5e65959e636b83490 Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 15 Jan 2025 16:50:37 -0500 Subject: [PATCH 6/9] fix script Signed-off-by: Chen Tong --- docs/BuildPyRuntimeLit.md | 8 ++++++-- src/Runtime/python/onnxmlirdocker.py | 2 +- utils/build-pyruntime-lit.sh | 8 ++++++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/BuildPyRuntimeLit.md b/docs/BuildPyRuntimeLit.md index e50f9bfa12..df53ff3c21 100644 --- a/docs/BuildPyRuntimeLit.md +++ b/docs/BuildPyRuntimeLit.md @@ -28,8 +28,12 @@ make make OMCreatePyRuntimePackage # Install the package -pip3 install src/Runtime/python/onnxmlir +pip3 install -e src/Runtime/python/onnxmlir +# -e is necessary for current package. Need to add resource description +# to install the pre-compiled binary # Run test case -python3 src/Runtime/python/onnxmlir/test/test_1.py +cd src/Runtime/python/onnxmlir/tests +python3 test_1.py +# Current limitation on where the model is ``` diff --git a/src/Runtime/python/onnxmlirdocker.py b/src/Runtime/python/onnxmlirdocker.py index 2fc1789fc4..72d74ccead 100644 --- a/src/Runtime/python/onnxmlirdocker.py +++ b/src/Runtime/python/onnxmlirdocker.py @@ -74,6 +74,7 @@ def __init__(self, model_path, **kwargs): self.model_basename.removesuffix(model_suffix), ) + print("model: ", self.model_dirname) self.container_client = docker.from_env() # Logically, the model directory could be mounted as read only. # But wrong time error occurred with "r" mode @@ -91,7 +92,6 @@ def __init__(self, model_path, **kwargs): }, }, ) - print("afterwards tempdir: ", [f for f in os.listdir(self.output_dirname)]) self.session = self.getSession() def getSession(self): diff --git a/utils/build-pyruntime-lit.sh b/utils/build-pyruntime-lit.sh index 063ae4f24f..0943ee53fb 100644 --- a/utils/build-pyruntime-lit.sh +++ b/utils/build-pyruntime-lit.sh @@ -9,7 +9,11 @@ make make OMCreatePyRuntimePackage # Install the package -pip3 install src/Runtime/python/onnxmlir +pip3 install -e src/Runtime/python/onnxmlir +# -e is necessary for current package. Need to add resource description +# to install the pre-compiled binary # Run test case -python3 src/Runtime/python/onnxmlir/test/test_1.py +cd src/Runtime/python/onnxmlir/tests +python3 test_1.py +# Current limitation on where the model is From 8ecd7ffe567e6ce4ecdb638cc6702ea6ae974f4f Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Mon, 20 Jan 2025 23:25:34 -0500 Subject: [PATCH 7/9] fix Signed-off-by: Chen Tong --- CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 54e72b2d53..7f3be2de73 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -212,6 +212,10 @@ if (ONNX_MLIR_SUPPRESS_THIRD_PARTY_WARNINGS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSUPPRESS_THIRD_PARTY_WARNINGS") endif() +if (ONNX_MLIR_ENABLE_STABLEHLO) + add_compile_definitions(ONNX_MLIR_ENABLE_STABLEHLO) +endif() + if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) add_subdirectory(src) else() From 069467887b2b548819addb048b8b2fa01989d649 Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Mon, 27 Jan 2025 10:46:20 -0500 Subject: [PATCH 8/9] add comments Signed-off-by: Chen Tong --- MLIR.cmake | 3 +++ src/Runtime/ExecutionSession.hpp | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/MLIR.cmake b/MLIR.cmake index da24f14126..7fccee7ef7 100644 --- a/MLIR.cmake +++ b/MLIR.cmake @@ -1,6 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + # This function is defined in llvm_project. + # Define a dummy function for PYRUNTIME_LIT. + # If needed, the definition from llvm_project can be copied. function(llvm_update_compile_flags name) endfunction() else() diff --git a/src/Runtime/ExecutionSession.hpp b/src/Runtime/ExecutionSession.hpp index a53dce0ecd..e7beac2b9c 100644 --- a/src/Runtime/ExecutionSession.hpp +++ b/src/Runtime/ExecutionSession.hpp @@ -21,6 +21,11 @@ #include #include "OnnxMlirRuntime.h" + +// LLVM provides the wrapper class, llvm::sys::DynamicLibrary, for dynamic +// library. When PYRUNTIME_LIT is built without the LLVM, the handle type for +// dynamic library in Linux is used. DynamicLibraryHandleType is defined for +// the two cases. #ifndef ENABLE_PYRUNTIME_LIT #include "llvm/Support/DynamicLibrary.h" typedef llvm::sys::DynamicLibrary DynamicLibraryHandleType; From 8c8a17fc1da85f08a835d2336f4750d9789a901b Mon Sep 17 00:00:00 2001 From: Chen Tong Date: Wed, 29 Jan 2025 11:45:10 -0500 Subject: [PATCH 9/9] LIGHT Signed-off-by: Chen Tong --- CMakeLists.txt | 8 ++++---- MLIR.cmake | 6 +++--- src/CMakeLists.txt | 4 ++-- src/Runtime/CMakeLists.txt | 6 +++--- src/Runtime/ExecutionSession.cpp | 18 +++++++++--------- src/Runtime/ExecutionSession.hpp | 4 ++-- src/Runtime/OMTensor.inc | 4 ++-- src/Runtime/python/CMakeLists.txt | 8 +++++--- src/Runtime/python/PyExecutionSessionBase.cpp | 6 +++--- ...runtime-lit.sh => build-pyruntime-light.sh} | 2 +- 10 files changed, 34 insertions(+), 32 deletions(-) rename utils/{build-pyruntime-lit.sh => build-pyruntime-light.sh} (91%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f3be2de73..bec9c49027 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,7 @@ option(ONNX_MLIR_ENABLE_STABLEHLO "Enable StableHLO support." ON) option(ONNX_MLIR_ENABLE_WERROR "Enable warnings as errors." OFF) option(ONNX_MLIR_SUPPRESS_THIRD_PARTY_WARNINGS "Suppress warning in third_party code." ON) option(ONNX_MLIR_ENABLE_JAVA "Set to ON for building the Java runtime, tools, and tests" ON) -option(ONNX_MLIR_ENABLE_PYRUNTIME_LIT "Set to ON for building Python driver of running the compiled model without llvm-project." OFF) +option(ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT "Set to ON for building Python driver of running the compiled model without llvm-project." OFF) set(CMAKE_CXX_STANDARD 17) @@ -74,7 +74,7 @@ set(ONNX_MLIR_INCLUDE_PATH ${CMAKE_INCLUDE_OUTPUT_DIRECTORY}) set(ONNX_MLIR_VENDOR ${PACKAGE_VENDOR} CACHE STRING "Vendor-specific text for showing with version information.") -if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) include(CTest) include(ExternalProject) endif() @@ -162,7 +162,7 @@ endif() set(CMAKE_MESSAGE_LOG_LEVEL NOTICE) # Add third party subdirectories and define options appropriate to run their cmakes. -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) add_subdirectory(third_party/onnx) add_subdirectory(third_party/pybind11) else() @@ -216,7 +216,7 @@ if (ONNX_MLIR_ENABLE_STABLEHLO) add_compile_definitions(ONNX_MLIR_ENABLE_STABLEHLO) endif() -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) add_subdirectory(src) else() add_subdirectory(utils) diff --git a/MLIR.cmake b/MLIR.cmake index 7fccee7ef7..1298ea565c 100644 --- a/MLIR.cmake +++ b/MLIR.cmake @@ -1,8 +1,8 @@ # SPDX-License-Identifier: Apache-2.0 -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) # This function is defined in llvm_project. - # Define a dummy function for PYRUNTIME_LIT. + # Define a dummy function for PYRUNTIME_LIGHT. # If needed, the definition from llvm_project can be copied. function(llvm_update_compile_flags name) endfunction() @@ -166,7 +166,7 @@ function(add_onnx_mlir_library name) ) if (NOT ARG_EXCLUDE_FROM_OM_LIBS) - if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) + if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) set_property(GLOBAL APPEND PROPERTY ONNX_MLIR_LIBS ${name}) endif() endif() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 031d3a8655..d1576a85d8 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,12 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) add_subdirectory(Runtime) # Accelerators introduces a target AcceleratorsInc. Define a dummy one here add_custom_target(AcceleratorsInc COMMAND echo "This is the dummy definition for AcceleratorsInc" ) - add_compile_definitions(ENABLE_PYRUNTIME_LIT) + add_compile_definitions(ENABLE_PYRUNTIME_LIGHT) return() endif() diff --git a/src/Runtime/CMakeLists.txt b/src/Runtime/CMakeLists.txt index f3c8bfb69a..e9e888f89f 100644 --- a/src/Runtime/CMakeLists.txt +++ b/src/Runtime/CMakeLists.txt @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 -if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if (NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) add_subdirectory(jni) add_subdirectory(omp) endif() @@ -67,8 +67,8 @@ set_target_properties(OMTensorUtils POSITION_INDEPENDENT_CODE TRUE ) -if (ONNX_MLIR_ENABLE_PYRUNTIME_LIT) -add_compile_definitions(ENABLE_PYRUNTIME_LIT) +if (ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) +add_compile_definitions(ENABLE_PYRUNTIME_LIGHT) add_onnx_mlir_library(OMExecutionSession ExecutionSession.cpp diff --git a/src/Runtime/ExecutionSession.cpp b/src/Runtime/ExecutionSession.cpp index 222e0a5be3..e71effa0c3 100644 --- a/src/Runtime/ExecutionSession.cpp +++ b/src/Runtime/ExecutionSession.cpp @@ -21,7 +21,7 @@ #include #include -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT #include "llvm/ADT/SmallString.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" @@ -50,7 +50,7 @@ void ExecutionSession::Init( if (tag == "") { // ToFix: equivalent implementation of llvm utilities. // The would not be an urgent issue, because tag is usually "NONE" -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT std::string fname = llvm::sys::path::filename(sharedLibPath).str(); llvm::SmallString<256> fnameWithoutExt(fname); llvm::sys::path::replace_extension(fnameWithoutExt, ""); @@ -61,7 +61,7 @@ void ExecutionSession::Init( // tag = "NONE" to use functions without tag. std::string lowDashTag; // ToFix: equivalent implementation of llv::StringRef -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT // Assume tag is always NONE if (!llvm::StringRef(tag).equals_insensitive("NONE")) lowDashTag = "_" + tag; @@ -75,7 +75,7 @@ void ExecutionSession::Init( #endif // Init symbols used by execution session. -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT _sharedLibraryHandle = llvm::sys::DynamicLibrary::getLibrary(sharedLibPath.c_str()); if (!_sharedLibraryHandle.isValid()) @@ -89,7 +89,7 @@ void ExecutionSession::Init( #endif std::string queryEntryPointsNameWithTag = _queryEntryPointsName + lowDashTag; -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT _queryEntryPointsFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( queryEntryPointsNameWithTag.c_str())); @@ -103,7 +103,7 @@ void ExecutionSession::Init( reportSymbolLoadingError(queryEntryPointsNameWithTag)); std::string inputSignatureNameWithTag = _inputSignatureName + lowDashTag; -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT _inputSignatureFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( inputSignatureNameWithTag.c_str())); @@ -116,7 +116,7 @@ void ExecutionSession::Init( reportSymbolLoadingError(inputSignatureNameWithTag)); std::string outputSignatureNameWithTag = _outputSignatureName + lowDashTag; -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT _outputSignatureFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol( outputSignatureNameWithTag.c_str())); @@ -150,7 +150,7 @@ void ExecutionSession::Init( } ExecutionSession::~ExecutionSession() { -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT if (_sharedLibraryHandle.isValid()) llvm::sys::DynamicLibrary::closeLibrary(_sharedLibraryHandle); #else @@ -173,7 +173,7 @@ const std::string *ExecutionSession::queryEntryPoints( void ExecutionSession::setEntryPoint(const std::string &entryPointName) { if (!isInitialized) throw std::runtime_error(reportInitError()); -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT _entryPointFunc = reinterpret_cast( _sharedLibraryHandle.getAddressOfSymbol(entryPointName.c_str())); #else diff --git a/src/Runtime/ExecutionSession.hpp b/src/Runtime/ExecutionSession.hpp index e7beac2b9c..88dfbcc71a 100644 --- a/src/Runtime/ExecutionSession.hpp +++ b/src/Runtime/ExecutionSession.hpp @@ -23,10 +23,10 @@ #include "OnnxMlirRuntime.h" // LLVM provides the wrapper class, llvm::sys::DynamicLibrary, for dynamic -// library. When PYRUNTIME_LIT is built without the LLVM, the handle type for +// library. When PYRUNTIME_LIGHT is built without the LLVM, the handle type for // dynamic library in Linux is used. DynamicLibraryHandleType is defined for // the two cases. -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT #include "llvm/Support/DynamicLibrary.h" typedef llvm::sys::DynamicLibrary DynamicLibraryHandleType; #else diff --git a/src/Runtime/OMTensor.inc b/src/Runtime/OMTensor.inc index c2d4b3860a..4be4f2af18 100644 --- a/src/Runtime/OMTensor.inc +++ b/src/Runtime/OMTensor.inc @@ -44,7 +44,7 @@ #include "src/Runtime/OMTensorHelper.hpp" #endif -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT #include "src/Support/SmallFPConversion.h" #endif @@ -54,7 +54,7 @@ int *__attribute__((__weak__)) __errno_location(void) { return &errno; } #endif -#ifdef ENABLE_PYRUNTIME_LIT +#ifdef ENABLE_PYRUNTIME_LIGHT // The implementation depends on src/Utility and llvm. Will be solved in // another PR. Here are just dummy definitions for compilation float om_f16_to_f32(uint16_t a) { diff --git a/src/Runtime/python/CMakeLists.txt b/src/Runtime/python/CMakeLists.txt index 43374c6b0b..515305bdcd 100644 --- a/src/Runtime/python/CMakeLists.txt +++ b/src/Runtime/python/CMakeLists.txt @@ -11,7 +11,7 @@ file(GENERATE ) # TODO: Remove pybind11::python_link_helper after cmake version bumped to 3.16+ -if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) add_onnx_mlir_library(OMPyExecutionSessionBase PyExecutionSessionBase.cpp @@ -24,7 +24,7 @@ if(NOT ONNX_MLIR_ENABLE_PYRUNTIME_LIT) pybind11::python_link_helper ) else() - add_compile_definitions(ENABLE_PYRUNTIME_LIT) + add_compile_definitions(ENABLE_PYRUNTIME_LIGHT) add_onnx_mlir_library(OMPyExecutionSessionBase PyExecutionSessionBase.cpp @@ -116,7 +116,9 @@ add_custom_target(OMCreatePyRuntimePackage DEPENDS PyRuntimeC ) -if(ONNX_MLIR_ENABLE_PYRUNTIME_LIT) +if(ONNX_MLIR_ENABLE_PYRUNTIME_LIGHT) + # Since the compiler is not built when PYRUNTIME_LIGHT is enabled, + # PyCompileAndRuntime can not be simply built. return() endif() diff --git a/src/Runtime/python/PyExecutionSessionBase.cpp b/src/Runtime/python/PyExecutionSessionBase.cpp index dc25eb5d99..eeb0795574 100644 --- a/src/Runtime/python/PyExecutionSessionBase.cpp +++ b/src/Runtime/python/PyExecutionSessionBase.cpp @@ -13,7 +13,7 @@ // //===----------------------------------------------------------------------===// -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT #include "src/Support/SmallFP.hpp" #else // ToFix: how to handle float_16 @@ -37,7 +37,7 @@ namespace detail { // // This implementation is copied from https://github.com/PaddlePaddle/Paddle -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT // ToFix: support for float_16 // Now onnx_mlir::float_16 is not defined without SmallFP.h @@ -183,7 +183,7 @@ std::vector PyExecutionSessionBase::pyRun( // string type missing else if (py::isinstance>(inputPyArray)) dtype = ONNX_TYPE_BOOL; -#ifndef ENABLE_PYRUNTIME_LIT +#ifndef ENABLE_PYRUNTIME_LIGHT else if (py::isinstance>(inputPyArray)) dtype = ONNX_TYPE_FLOAT16; #endif diff --git a/utils/build-pyruntime-lit.sh b/utils/build-pyruntime-light.sh similarity index 91% rename from utils/build-pyruntime-lit.sh rename to utils/build-pyruntime-light.sh index 0943ee53fb..dc6c12b789 100644 --- a/utils/build-pyruntime-lit.sh +++ b/utils/build-pyruntime-light.sh @@ -4,7 +4,7 @@ # Usually it is "your_path/onnx-mlir/build" # then you can run this script as "../util/build-pyruntime-lit.sh" -cmake .. -DONNX_MLIR_ENABLE_PYRUNTIME_LIT=ON +cmake .. -DONNX_MLIR_ENABLE_PYRUNTIME_LIGHT=ON make make OMCreatePyRuntimePackage pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy