1. 查看电脑中可以使用的GPU
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
输出:
2. 选择使用GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0" ##表示使用GPU编号为0的GPU进行计算
from tensorflow.compat.v1 import ConfigProto# tf 2.x的写法
config =ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction=0.6 # 设置最大使用显存60%
3. 清理GPU内存
出现下面问题时:
2022-12-08 16:09:39.813281: W tensorflow/core/common_runtime/bfc_allocator.cc:479] Allocator (GPU_0_bfc) ran out of memory trying to allocate 128.0KiB (rounded to 131072)requested by op Fill
If the cause is memory fragmentation maybe the environment variable 'TF_GPU_ALLOCATOR=cuda_malloc_async' will improve the situation.
Current allocation summary follows.
Current allocation summary follows.
...这里省略...
ResourceExhaustedError: {{function_node __wrapped__Fill_device_/job:localhost/replica:0/task:0/device:GPU:0}} OOM when allocating tensor with shape[256,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:Fill]
当一个GPU内存满了,再去加载模型训练时会出错,这个时候可以先清理GPU内存后再去训练
可以在代码中直接清除( 推荐使用的方式):
from numba import cuda
device = cuda.get_current_device()
device.reset()
也可以将PID进程关掉:kill -9 1891022
在命令行中输入:nvidia-smi 查看GPU Memory Usage
4. 使用CPU进行推理
当不方便使用GPU的时候,可以考虑使用CPU进行推理预测。
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # 使用CPU进行推理
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"