查看gpu使用情况

nvidia-smi

指定gpu的计算模式
  • 指定gpu0为独占模式, 0为默认模式,1为独占

    nvidia-smi -i 0 -c 1
    

    Compute Mode
    The compute mode flag indicates whether individual or multiple compute applications may run on the GPU.

  • “Default” means multiple contexts are allowed per device.

  • “Exclusive Process” means only one context is allowed per device, usable from multiple threads at a time.

  • “Prohibited” means no contexts are allowed per device (no compute apps).
    “EXCLUSIVE_PROCESS” was added in CUDA 4.0.

tensorflow测试显卡是否存在及使用

import tensorflow as tf
print(tf.test.is_gpu_available())

设置只见gpu-0,1

import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0,1"

或者在终端输入

export CUDA_VISIBLE_DEVICES=0,1

TF2.0 is wonderful !

获取设备信息
GPUS = tf.config.experimental.list_physical_devices(device_type='GPU')
CPUS = tf.config.experimental.list_physical_devices(device_type='CPU')
指定GPU工作

TF 默认使用能使用的所有 GPU

# 设置当前程序只使用gpu0,1
tf.config.experimental.set_visible_devices(devices=gpus[0:1], device_type='GPU')

另一种方式是使用环境变量 CUDA_VISIBLE_DEVICES 也可以控制程序所使用的 GPU。

指定显存的使用设置

默认情况尽可能占满显存,TF也可以控制程序的显存使用方式,自定义控制显存使用:

动态申请缓存(推荐)
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)
指定最大占用显存值
# z最大占4G
tf.config.experimental.set_virtual_device_configuration(gpus[0],
    [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)]
)
single GPU as multi-GPU
# build two virtual GPU with 4G
tf.config.experimental.set_virtual_device_configuration(
    gpus[0],
    [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096),
     tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)])

TensorFlow=1.15.0

举个例子:指定gpu-1,自适应分配显存

import os
os.environ['CUDA_VISIBLE_DEVICES'] = "1"
tf_config = tf.ConfigProto()  
tf_config.gpu_options.allow_growth = True # 自适应 
# 或者指定最大占用比例
# tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1 
session = tf.Session(config=tf_config)  

参考

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐