有 Tensorflow 后端的 Keras 是否可以强制使用 CPU 或随意使用 GPU?

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

我安装了带有 Tensorflow 后端和 CUDA 的 Keras。我想有时按需强制 Keras 使用 CPU。如果不说在虚拟环境中安装单独的 CPU-only Tensorflow 就可以做到这一点吗?如果是这样怎么办?如果后端是 Theano,则可以设置标志,但我还没有听说过可通过 Keras 访问的 Tensorflow 标志。

根据 keras tutorial,您可以简单地使用与常规 tensorflow 中相同的 tf.device 作用域:

with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0

with tf.device('/cpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0

如果你想强制Keras使用CPU

方式一

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""

在导入 Keras / Tensorflow 之前。

方式 2

运行 你的脚本为

$ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py

另见

  1. https://github.com/keras-team/keras/issues/152
  2. https://github.com/fchollet/keras/issues/4613

我只是花了一些时间弄清楚。 托马斯的回答并不完整。 假设你的程序是 test.py,你想使用 gpu0 来 运行 这个程序,并保持其他 gpus 空闲。

你应该写CUDA_VISIBLE_DEVICES=0 python test.py

注意它是 DEVICES 而不是 DEVICE

一个相当独立的方法是使用

import tensorflow as tf
from keras import backend as K

num_cores = 4

if GPU:
    num_GPU = 1
    num_CPU = 1
if CPU:
    num_CPU = 1
    num_GPU = 0

config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
                        inter_op_parallelism_threads=num_cores, 
                        allow_soft_placement=True,
                        device_count = {'CPU' : num_CPU,
                                        'GPU' : num_GPU}
                       )

session = tf.Session(config=config)
K.set_session(session)

在这里,使用 booleans GPUCPU,我们表明我们是否希望 运行 我们的代码与 GPU 或 CPU 严格地定义允许 Tensorflow 会话访问的 GPU 和 CPUs 的数量。变量 num_GPUnum_CPU 定义了这个值。 num_cores 然后通过 intra_op_parallelism_threadsinter_op_parallelism_threads 设置可供使用的 CPU 核心数。

intra_op_parallelism_threads 变量指示计算图中单个节点中的并行操作允许使用的线程数(内部)。虽然 inter_ops_parallelism_threads 变量定义了计算图(inter)节点间并行操作可访问的线程数。

如果满足以下任何条件,

allow_soft_placement 允许在 CPU 上进行 运行 操作:

  1. 该操作没有 GPU 实现

  2. 没有已知或注册的 GPU 设备

  3. 需要与来自 CPU

  4. 的其他输入放在一起

所有这些都在我的 class 的构造函数中执行,然后再进行任何其他操作,并且与我使用的任何模型或其他代码完全分离。

注意:这需要安装 tensorflow-gpucuda/cudnn,因为提供了使用 GPU 的选项。

参考:

  • Meaning of inter_op_parallelism_threads and intra_op_parallelism_threads

这对我有用 (win10),在导入 keras 之前放置:

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

导入tensortflow,使用keras,就这么简单

import tensorflow as tf
# your code here
with tf.device('/gpu:0'):
    model.fit(X, y, epochs=20, batch_size=128, callbacks=callbacks_list)

对于使用 PyCharm 和强制 CPU 的人,您可以在环境变量下的 Run/Debug 配置中添加以下行:

<OTHER_ENVIRONMENT_VARIABLES>;CUDA_VISIBLE_DEVICES=-1