Tensorflow 2:如何将执行从 GPU 切换到 CPU 并返回?

Tensorflow 2: how to switch execution from GPU to CPU and back?

tensorflow 1.X 独立 keras 2.X 中,我曾经在 GPU 训练和 运行 推理 [=26] 之间切换=](出于某种原因,我的 RNN 模型要快得多)使用以下代码段:

keras.backend.clear_session()

def set_session(gpus: int = 0):
    num_cores = cpu_count()

    config = tf.ConfigProto(
        intra_op_parallelism_threads=num_cores,
        inter_op_parallelism_threads=num_cores,
        allow_soft_placement=True,
        device_count={"CPU": 1, "GPU": gpus},
    )

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

ConfigProto 功能在 tensorflow 2.0 中不再可用(我正在使用集成的 tensorflow.keras)。一开始,可以 运行 tf.config.experimental.set_visible_devices() 例如禁用 GPU,但对 set_visible_devices 的任何后续调用都会导致 RuntimeError: Visible devices cannot be modified after being initialized。有没有一种方法可以重新初始化可见设备,或者是否有另一种切换可用设备的方法?

使用tf.device对您有帮助吗?

这样,您可以在 CPU 或 GPU 上设置一些操作。

您可以使用 tf.device 来明确设置您要使用的设备。例如:

import tensorflow as tf    

model = tf.keras.Model(...)

# Run training on GPU
with tf.device('/gpu:0'):
    model.fit(...)

# Run inference on CPU
with tf.device('/cpu:0'):
    model.predict(...)

如果您只有一个 CPU 和一个 GPU,上面使用的名称应该有效。否则,device_lib.list_local_devices() can give you a list of your devices. 提供了一个很好的函数来仅列出名称,我在此处对其进行了调整以显示 CPUs:

from tensorflow.python.client import device_lib

def get_available_devices():
    local_device_protos = device_lib.list_local_devices()
    return [x.name for x in local_device_protos if x.device_type == 'GPU' or x.device_type == 'CPU']

我会重启内核,这对我有用