在使用独立的Keras 2.X和TensorFlow 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)
在 tensorflow
2.0 中,ConfigProto
功能不再可用(我正在使用集成的 tensorflow.keras
)。在开始时,可以运行 tf.config.experimental.set_visible_devices()
以禁用 GPU,但任何后续对 set_visible_devices
的调用都会导致 RuntimeError:Visible devices cannot be modified after being initialized
。是否有一种重新初始化可见设备或切换可用设备的方法?
tf.set_device('/cpu:0')
这样的东西? - Lucas Azevedotf.device('/cpu:0'):
,TF仍然会分配GPU内存。我认为这是TF的一个限制。 - Jongwook Choiphysical_devices = tf.config.list_physical_devices('GPU'); tf.config.set_visible_devices(physical_devices[0], 'GPU')
。这个功能从tensorflow 2.1版本开始实现。 - BeCurious