我在一个计算资源共享的环境中工作,也就是说,我们有几台服务器机器,每台机器都配备了几个Nvidia Titan X gpu。
For small to moderate size models, the 12 GB of the Titan X is usually enough for 2–3 people to run training concurrently on the same GPU. If the models are small enough that a single model does not take full advantage of all the computational units of the GPU, this can actually result in a speedup compared with running one training process after the other. Even in cases where the concurrent access to the GPU does slow down the individual training time, it is still nice to have the flexibility of having multiple users simultaneously train on the GPU.
TensorFlow的问题在于,默认情况下,它在启动时分配了全部可用的GPU内存。即使是一个小型的两层神经网络,我看到所有12 GB的GPU内存都用完了。
有没有一种方法让TensorFlow只分配,比如说,4 GB的GPU内存,如果我们知道这对一个给定的模型来说已经足够了?
对于TensorFlow 2.0和2.1 (docs):
import tensorflow as tf
tf.config.gpu.set_per_process_memory_growth(True)
对于TensorFlow 2.2+ (docs):
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
文档还列出了更多的方法:
设置环境变量TF_FORCE_GPU_ALLOW_GROWTH为true。
使用tf.config.experimental。set_virtual_device_configuration设置虚拟GPU设备的硬限制。
Tensorflow 2.0 Beta和(可能)更高版本
API再次改变。现在可以在以下地方找到它:
tf.config.experimental.set_memory_growth(
device,
enable
)
别名:
tf.compat.v1.config.experimental.set_memory_growth
tf.compat.v2.config.experimental.set_memory_growth
引用:
https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/config/experimental/set_memory_growth
https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth
参见:
Tensorflow—使用GPU: https://www.tensorflow.org/guide/gpu
对于Tensorflow 2.0 Alpha,请参见:这个答案