简体   繁体   English

使用 TensorFlow C API 的 Python 扩展模块

[英]Python extension module using TensorFlow C API

I've written a Python extension module that uses TensorFlow through the C API.我编写了一个 Python 扩展模块,它通过 C API 使用 TensorFlow。 I installed the API as described in https://www.tensorflow.org/install/lang_c .我按照https://www.tensorflow.org/install/lang_c 中的描述安装了 API。 On its own, my module works correctly.就其本身而言,我的模块工作正常。 But if I import my extension module and also import tensorflow, Python crashes with this error.但是,如果我输入我的扩展模块,进口tensorflow,Python的崩溃,此错误。

[libprotobuf ERROR external/protobuf_archive/src/google/protobuf/descriptor_database.cc:58] File already exists in database: tensorflow/core/protobuf/master.proto
[libprotobuf FATAL external/protobuf_archive/src/google/protobuf/descriptor.cc:1370] CHECK failed: GeneratedDatabase()->Add(encoded_file_descriptor, size): 
libc++abi.dylib: terminating with uncaught exception of type google::protobuf::FatalException: CHECK failed: GeneratedDatabase()->Add(encoded_file_descriptor, size): 
Abort trap: 6

I believe this happens because the C API includes its own complete copy of TensorFlow, so now I get two different copies loaded into the same process at the same time.我相信这是因为 C API 包含它自己的 TensorFlow 完整副本,所以现在我将两个不同的副本同时加载到同一个进程中。

What is the solution to this?解决这个问题的方法是什么? How can I have Python code that uses TensorFlow, and also invokes C code that uses TensorFlow?我如何拥有使用 TensorFlow 的 Python 代码,并调用使用 TensorFlow 的 C 代码?

TensorFlow uses Protobuf and it stores data globally, by registering message types with specific names. TensorFlow 使用 Protobuf 并通过使用特定名称注册消息类型来全局存储数据。

In your case, both TensorFlow and your extension are linked with Protobuf (probably statically) and upon initialization try to register all the necessary messages.在您的情况下,TensorFlow 和您的扩展都与 Protobuf(可能是静态的)相关联,并且在初始化时尝试注册所有必要的消息。 The first (TensorFlow) succeeds, and the second fails with this very message, that specifies that someone (TensorFlow..) has already registered such a message.第一个 (TensorFlow) 成功,第二个失败并显示此消息,该消息指定某人 (TensorFlow..) 已经注册了这样的消息。

Try not to link with the TensorFlow library (which is dependent on Protobuf) and load it dynamically.尽量不要链接TensorFlow库(依赖于Protobuf)并动态加载。

This may be done using dlopen() but then you'll have to manually get all TF methods using dlsym() which is a bit different than what you'd like.这可以使用dlopen()但是您必须使用dlsym()手动获取所有 TF 方法,这与您想要的有点不同。

If you compile a Python extension, I guess you're compiling a shared-object so I'd expect it to be dynamically linked with TensorFlow.如果你编译一个 Python 扩展,我猜你正在编译一个共享对象,所以我希望它与 TensorFlow 动态链接。 What is the command line you used for compilation?您用于编译的命令行是什么? Did you use -fPIC ?你用过-fPIC吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM