You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "tqchen (via GitHub)" <gi...@apache.org> on 2026/04/26 13:27:10 UTC

[PR] [REFACTOR] Isolate backend module creation via ffi.Module.create. registry [tvm]

tqchen opened a new pull request, #19447:
URL: https://github.com/apache/tvm/pull/19447

   ## Summary
   
   Introduces FFI registry indirection for all backend module-creation functions, eliminating the hard linker dependency from `libtvm_compiler.so` on runtime-defined creator symbols. After this PR, `nm -u libtvm_compiler.so | grep ModuleCreate` returns nothing.
   
   ## Changes
   
   - **Registry convention**: each backend runtime `.cc` registers `ffi.Module.create.<kind>` in a `TVM_FFI_STATIC_INIT_BLOCK` with FFI-compatible argument types. The static init runs when the `.so` is loaded; until then the creator is unreachable from the registry.
   
   - **Inline header wrappers**: `XxxModuleCreate` in each backend header becomes `inline`, does a `static const auto fcreate = ffi::Function::GetGlobal("ffi.Module.create.<kind>")` (cached after first call), and dispatches through FFI. Compiler-side codegen callsites are unchanged.
   
   - **Backends registered**: `ffi.Module.create.cuda`, `.rocm`, `.metal`, `.hexagon`, `.opencl`, `.opencl.spirv`, `.vulkan`, `.const_loader`.
   
   - **FFI arg type conversions**: `std::string` → `ffi::String`; `std::unordered_map<string,string>` → `ffi::Map<ffi::String,ffi::String>` (metal smap); `SPIRVShader` → `ffi::Bytes` (serialised as flag+data uint32 stream); `unordered_map<string,Tensor>` → `ffi::Map<ffi::String,Tensor>`; `unordered_map<string,vector<string>>` → `ffi::Map<ffi::String,ffi::Array<ffi::String>>`.
   
   - **spirv\_shader.h moved**: `src/runtime/spirv/spirv_shader.h` → `src/runtime/vulkan/spirv_shader.h` (only consumed by vulkan + opencl runtime). Old path becomes a redirect-include for backward compatibility.
   
   - **Off-build stubs updated**: cuda/rocm/metal off-stubs are now empty (inline wrappers handle the "off" case by throwing a clear registry-not-found error); opencl/hexagon off-stubs register fallback creators.
   
   - **DeviceSourceModuleCreate** left as-is — its `std::function<>` argument is not FFI-serialisable.
   
   ## Verification
   
   - `ninja tvm_runtime tvm_compiler cpptest` clean with `HIDE_PRIVATE_SYMBOLS=ON`
   - `./cpptest`: 128/128 tests pass
   - `all-platform-minimal-test`: 54 passed, 98 skipped
   - `tests/python/runtime/`: 81 passed, 2 skipped
   - `tests/python/relax/test_vm_build.py`: 84 passed, 2 xfailed
   - JVM: BUILD SUCCESS
   - `nm -u build/lib/libtvm_compiler.so | grep ModuleCreate` → (empty)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REFACTOR] Isolate backend module creation via ffi.Module.create. registry [tvm]

Posted by "spectrometerHBH (via GitHub)" <gi...@apache.org>.
spectrometerHBH merged PR #19447:
URL: https://github.com/apache/tvm/pull/19447


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [REFACTOR] Isolate backend module creation via ffi.Module.create. registry [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #19447:
URL: https://github.com/apache/tvm/pull/19447#discussion_r3143547435


##########
src/runtime/vulkan/vulkan_module.h:
##########
@@ -20,21 +20,52 @@
 #ifndef TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_
 #define TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_
 
+#include <tvm/ffi/container/map.h>
 #include <tvm/ffi/extra/module.h>
+#include <tvm/ffi/function.h>
 #include <tvm/runtime/base.h>
 
 #include <string>
 #include <unordered_map>
 
+#include "../../support/bytes_io.h"
 #include "../metadata.h"
-#include "../spirv/spirv_shader.h"
+#include "spirv_shader.h"
 
 namespace tvm {
 namespace runtime {
 namespace vulkan {
-TVM_RUNTIME_DLL ffi::Module VulkanModuleCreate(std::unordered_map<std::string, SPIRVShader> smap,
-                                               ffi::Map<ffi::String, FunctionInfo> fmap,
-                                               std::string source);
+
+/*!
+ * \brief Create a Vulkan module from SPIRV shaders.
+ *
+ * \param smap Map from function name to SPIRVShader.
+ * \param fmap Map from function name to FunctionInfo.
+ * \param source Optional SPIRV text (for inspection).
+ *
+ * Dispatches through the FFI registry ("ffi.Module.create.vulkan").
+ * Each SPIRVShader is serialised to ffi::Bytes before crossing the FFI boundary
+ * and rehydrated on the runtime side.
+ * Requires libtvm_runtime built with USE_VULKAN=ON to have registered the creator.
+ */
+inline ffi::Module VulkanModuleCreate(std::unordered_map<std::string, SPIRVShader> smap,
+                                      ffi::Map<ffi::String, FunctionInfo> fmap,
+                                      std::string source) {
+  static const auto fcreate = ffi::Function::GetGlobal("ffi.Module.create.vulkan");
+  TVM_FFI_CHECK(fcreate.has_value(), RuntimeError)
+      << "ffi.Module.create.vulkan is not registered in runtime. "
+      << "Link or load libtvm_runtime built with USE_VULKAN=ON.";
+  // Serialise each SPIRVShader to ffi::Bytes for the FFI boundary.
+  ffi::Map<ffi::String, ffi::Bytes> shader_bytes;
+  for (const auto& kv : smap) {
+    std::string buf;
+    support::BytesOutStream strm(&buf);
+    strm.Write(kv.second.flag);
+    strm.Write(kv.second.data);

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `SPIRVShader` struct has a custom serializer defined in `spirv_shader.h`. You can simplify this manual serialization by using `strm.Write(kv.second);` directly, which is more maintainable and concise.
   
   ```suggestion
       strm.Write(kv.second);
   ```



##########
src/runtime/vulkan/vulkan_module.cc:
##########
@@ -25,14 +25,28 @@
 
 #include "../../support/bytes_io.h"
 #include "../file_utils.h"
+#include "spirv_shader.h"
 #include "vulkan_wrapped_func.h"
 
 namespace tvm {
 namespace runtime {
 namespace vulkan {
 
-ffi::Module VulkanModuleCreate(std::unordered_map<std::string, SPIRVShader> smap,
-                               ffi::Map<ffi::String, FunctionInfo> fmap, std::string source) {
+/*!
+ * \brief Deserialize a SPIRVShader from ffi::Bytes.
+ * Format: flag (uint32_t) followed by data (vector<uint32_t>).
+ */
+static SPIRVShader DeserializeSPIRVShader(const ffi::Bytes& bytes) {
+  support::BytesInStream stream(bytes);
+  SPIRVShader shader;
+  TVM_FFI_ICHECK(stream.Read(&shader.flag));
+  TVM_FFI_ICHECK(stream.Read(&shader.data));

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `SPIRVShader` struct has a custom serializer defined in `spirv_shader.h`. You can simplify this manual deserialization by using `stream.Read(&shader);` directly.
   
   ```suggestion
     TVM_FFI_ICHECK(stream.Read(&shader));
   ```



##########
src/runtime/opencl/opencl_module_spirv.cc:
##########
@@ -129,13 +130,31 @@ cl_kernel OpenCLSPIRVModuleNode::InstallKernel(cl::OpenCLWorkspace* w, cl::OpenC
   return kernel;
 }
 
-ffi::Module OpenCLModuleCreate(const std::unordered_map<std::string, SPIRVShader>& shaders,
-                               const std::string& spirv_text,
-                               ffi::Map<ffi::String, FunctionInfo> fmap) {
+static ffi::Module OpenCLSPIRVModuleCreateInternal(
+    const std::unordered_map<std::string, SPIRVShader>& shaders, const std::string& spirv_text,
+    ffi::Map<ffi::String, FunctionInfo> fmap) {
   auto n = ffi::make_object<OpenCLSPIRVModuleNode>(shaders, spirv_text, fmap);
   n->Init();
   return ffi::Module(n);
 }
 
+TVM_FFI_STATIC_INIT_BLOCK() {
+  namespace refl = tvm::ffi::reflection;
+  refl::GlobalDef().def("ffi.Module.create.opencl.spirv",
+                        [](ffi::Map<ffi::String, ffi::Bytes> shader_bytes, ffi::String spirv_text,
+                           ffi::Map<ffi::String, FunctionInfo> fmap) {
+                          std::unordered_map<std::string, SPIRVShader> shaders;
+                          for (const auto& kv : shader_bytes) {
+                            support::BytesInStream stream(kv.second);
+                            SPIRVShader shader;
+                            TVM_FFI_ICHECK(stream.Read(&shader.flag));
+                            TVM_FFI_ICHECK(stream.Read(&shader.data));

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `SPIRVShader` struct has a custom serializer defined in `spirv_shader.h`. You can simplify this manual deserialization by using `stream.Read(&shader);` directly.
   
   ```suggestion
                               TVM_FFI_ICHECK(stream.Read(&shader));
   ```



##########
src/runtime/opencl/opencl_module.h:
##########
@@ -43,21 +46,50 @@ namespace runtime {
  * \param fmt The format of the data, can be "clbin", "cl"
  * \param fmap The map function information map of each function.
  * \param source Generated OpenCL kernels.
+ *
+ * Dispatches through the FFI registry ("ffi.Module.create.opencl").
+ * Requires libtvm_runtime built with USE_OPENCL=ON to have registered the creator.
  */
-TVM_RUNTIME_DLL ffi::Module OpenCLModuleCreate(std::string data, std::string fmt,
-                                               ffi::Map<ffi::String, FunctionInfo> fmap,
-                                               std::string source);
+inline ffi::Module OpenCLModuleCreate(ffi::String data, ffi::String fmt,
+                                      ffi::Map<ffi::String, FunctionInfo> fmap,
+                                      ffi::String source) {
+  static const auto fcreate = ffi::Function::GetGlobal("ffi.Module.create.opencl");
+  TVM_FFI_CHECK(fcreate.has_value(), RuntimeError)
+      << "ffi.Module.create.opencl is not registered in runtime. "
+      << "Link or load libtvm_runtime built with USE_OPENCL=ON.";
+  return (*fcreate)(data, fmt, fmap, source).cast<ffi::Module>();
+}
 
 /*!
  * \brief Create a opencl module from SPIRV.
  *
  * \param shaders The map from function names to SPIRV binaries.
  * \param spirv_text The concatenated text representation of SPIRV modules.
  * \param fmap The map function information map of each function.
+ *
+ * Dispatches through the FFI registry ("ffi.Module.create.opencl.spirv").
+ * Each SPIRVShader is serialised to ffi::Bytes before crossing the FFI boundary.
+ * Requires libtvm_runtime built with USE_OPENCL=ON and TVM_ENABLE_SPIRV to have
+ * registered the creator.
  */
-TVM_RUNTIME_DLL ffi::Module OpenCLModuleCreate(
+inline ffi::Module OpenCLModuleCreate(
     const std::unordered_map<std::string, spirv::SPIRVShader>& shaders,
-    const std::string& spirv_text, ffi::Map<ffi::String, FunctionInfo> fmap);
+    const std::string& spirv_text, ffi::Map<ffi::String, FunctionInfo> fmap) {
+  static const auto fcreate = ffi::Function::GetGlobal("ffi.Module.create.opencl.spirv");
+  TVM_FFI_CHECK(fcreate.has_value(), RuntimeError)
+      << "ffi.Module.create.opencl.spirv is not registered in runtime. "
+      << "Link or load libtvm_runtime built with USE_OPENCL=ON and TVM_ENABLE_SPIRV.";
+  // Serialise each SPIRVShader to ffi::Bytes for the FFI boundary.
+  ffi::Map<ffi::String, ffi::Bytes> shader_bytes;
+  for (const auto& kv : shaders) {
+    std::string buf;
+    support::BytesOutStream strm(&buf);
+    strm.Write(kv.second.flag);
+    strm.Write(kv.second.data);

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `SPIRVShader` struct has a custom serializer defined in `spirv_shader.h`. You can simplify this manual serialization by using `strm.Write(kv.second);` directly, which is more maintainable and concise.
   
   ```suggestion
       strm.Write(kv.second);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org