Keras 线程安全吗?

Is Keras thread safe?

我正在使用 Python 和 Keras(目前使用 Theano 后端,但我对切换没有任何疑虑)。我有一个神经网络,可以并行加载和处理多个信息源。目前,我已经 运行 在一个单独的进程中对每一个进行了设置,并且它从文件中加载了自己的网络副本。这似乎是对 RAM 的浪费,所以我认为拥有一个单一的多线程进程和一个由所有线程使用的网络实例会更有效。但是,我想知道 Keras 是否对任一后端都是线程安全的。如果我 运行 .predict(x) 在不同的线程中同时处理两个不同的输入,我会 运行 进入竞争条件或其他问题吗?

谢谢

是的,Keras 是线程安全的,如果你稍加注意的话。

其实在强化学习中有一个算法叫Asynchronous Advantage Actor Critics (A3C) where each agent relies on the same neural network to tell them what they should do in a given state. In other words, each thread calls model.predict concurrently as in your problem. An example implementation with Keras of it is here.

但是,如果您查看代码,则应格外注意这一行: model._make_predict_function() # have to initialize before threading

这在 Keras 文档中从未提及,但有必要使其同时工作。简而言之,_make_predict_function是编译predict函数的函数。在多线程设置中,必须提前手动调用这个函数编译predict,否则predict函数要等到你第一次运行才编译,会有问题当许多线程同时调用它时。可以看到详细的解释here.

到目前为止,我还没有遇到 Keras 中多线程的任何其他问题。

引用实物fcholet:

_make_predict_function is a private API. We should not recommend calling it.

Here, the user should simply call predict first.

Note that Keras models can't be guaranteed to be thread-safe. Consider having independent copies of the model in each thread for CPU inference.