Tensorflow 2:如何在 GPU 和 CPU 之间切换执行?

val*_*.in 11 gpu tf.keras tensorflow2.0

tensorflow带有独立keras2.X 的1.X 中,我曾经使用以下代码段在 GPU 上训练和在 CPU 上运行推理(由于某些原因,我的 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)
Run Code Online (Sandbox Code Playgroud)

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

ada*_*key 16

您可以使用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(...)
Run Code Online (Sandbox Code Playgroud)

如果您只有一个 CPU 和一个 GPU,则上面使用的名称应该有效。否则,device_lib.list_local_devices()可以为您提供设备列表。这篇文章提供了一个很好的功能,可以只列出名称,我在此处对其进行了调整以显示 CPU:

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']
Run Code Online (Sandbox Code Playgroud)