我在一个计算资源共享的环境中工作,也就是说,我们有几台服务器机器,每台机器都配备了几个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支持的GPU,无论你设置它只使用CPU还是GPU,会话都会首先分配所有的GPU。我可以补充我的提示,即使你设置图形只使用CPU,你也应该设置相同的配置(如上所述:)),以防止不必要的GPU占用。

在像IPython和Jupyter这样的交互界面中,您也应该设置该配置,否则,它将分配所有内存,而几乎没有内存留给其他内存。这一点有时很难注意到。

这段代码对我有用:

import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.InteractiveSession(config=config)

好吧,我是张sorflow的新手,我有Geforce 740m或一些带有2GB ram的GPU,我正在运行mnist手写的原生语言示例,训练数据包含38700张图像和4300张测试图像,并试图获得精度,回忆,F1使用以下代码,因为sklearn没有给我精确的结果。一旦我把这个添加到我现有的代码,我开始得到GPU错误。

TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)

prec = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * prec * recall / (prec + recall)

加上我的模型是沉重的我猜,我是内存错误147年之后,148年的时代,然后我想为什么不创建函数的任务,所以我不知道如果在tensrorflow这种方式工作,但我认为如果使用局部变量,当定义的范围可能释放内存和i上述元素的训练和测试模块,我能够达到10000时代没有任何问题,我希望这将帮助. .

对于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设备的硬限制。

config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)

https://github.com/tensorflow/tensorflow/issues/1578