TensorFlow默认用CPU、指定GPU执行代码时,设置CUDA参数仍占用GPU的问题
解决TensorFlow默认用CPU、仅指定代码跑GPU的问题
- 注意:环境变量必须在导入TensorFlow前设置,否则完全不生效。如果先
import tensorflow再修改环境变量,TensorFlow已经完成GPU初始化,设置等于白忙活。 - 你之前把
CUDA_VISIBLE_DEVICES设为空的做法错了——这会直接屏蔽所有GPU,连tf.device("/gpu:0")都没法调用GPU,而且如果设置时机不对,还会导致TensorFlow提前占用GPU内存。 - 正确的配置步骤:
- 先让TensorFlow识别GPU,但默认用CPU,且GPU内存按需分配:
import os # 开启GPU内存按需分配,避免TensorFlow启动就占满显存 os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' # 先别屏蔽GPU,让TensorFlow能找到它 import tensorflow as tf # 获取CPU和GPU设备列表 cpus = tf.config.list_physical_devices('CPU') gpus = tf.config.list_physical_devices('GPU') # 设置全局默认设备为CPU tf.config.set_visible_devices(cpus, 'CPU') # 保留第一个GPU设备,方便后续指定使用(如果有多个GPU可按需调整) if gpus: tf.config.set_visible_devices(gpus[0], 'GPU') - 之后想让哪部分代码跑GPU,就用
tf.device("/gpu:0")包裹:# 默认执行在CPU上 x = tf.random.normal((1000, 1000)) y = tf.matmul(x, x) # 指定这部分代码跑GPU with tf.device("/gpu:0"): a = tf.random.normal((1000, 1000)) b = tf.matmul(a, a)
- 先让TensorFlow识别GPU,但默认用CPU,且GPU内存按需分配:
- 这样配置后,TensorFlow默认所有操作都在CPU执行,只有你用
tf.device("/gpu:0")包裹的代码才会调用GPU,而且GPU内存是按需分配,不会启动就占满。
内容的提问来源于stack exchange,提问作者dustsucker
相关产品推荐
相关产品推荐

