马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
先插入一行简单代码,以下复制即可用来设置GPU利用率:
- import tensorflow as tf
- import numpy as np
- print(tf.__version__)
- import os
- # 设置可使用的 gpu 序号
- os.environ['CUDA_VISIBLE_DEVICES'] = '0'
- # 用来设置是否在特殊情况下在cpu上进行计算
- tf.config.set_soft_device_placement = False
- #
- tf.config.experimental.set_memory_growth = True
- gpus = tf.config.experimental.list_physical_devices('GPU')
- print(gpus)
- if gpus:
- tf.config.experimental.set_virtual_device_configuration(gpus[0],
- [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
-
- logical_gpus = tf.config.experimental.list_logical_devices('GPU')
- print(len(gpus), len(logical_gpus), 'Logical gpus')
- # tf.debugging.set_log_device_placement(True)
- # loggpus = config.experimental.list_logical_devices()
- # strategy = tf.distribute.MirroredStrategy()
- with tf.device('/device:GPU:0'):
- w = tf.constant([[2, -3.4]])
- b = tf.constant([4.2])
- x = tf.random.normal([1000, 2], mean=0, stddev=10)
- e = tf.random.normal([1000, 2], mean=0, stddev=0.1)
- W = tf.Variable(tf.constant([5, 1]))
- B = tf.Variable(tf.constant([1]))
复制代码 1. 获得当前主机上特定运算设备的列表
- # 获取当前物理gpu
- gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
- # 获取当前物理cpu
- cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
- print(gpus, cpus)
- # 获取当前虚拟gpu个数
- logical_gpus = tf.config.experimental.list_logical_devices('GPU')
复制代码 2. 设置当前步伐可见的设备范围
默认情况下 TensorFlow 会利用其所可以大概利用的所有 GPU
- tf.config.experimental.set_visible_devices(devices=gpus[2:4], device_type='GPU')
复制代码 设置之后,当前步伐只会利用自己可见的设备,不可见的设备不会被当前步伐利用。
另一种方式是利用情况变量 CUDA_VISIBLE_DEVICES 也可以控制步伐所利用的 GPU。
在终端输入
- export CUDA_VISIBLE_DEVICES=2,3
复制代码 或者在代码里加入
- import os
- os.environ['CUDA_VISIBLE_DEVICES'] = "2,3"
复制代码 3. 显存的利用
默认情况下,TensorFlow 将利用几乎所有可用的显存,以制止内存碎片化所带来的性能损失。
但是TensorFlow 提供两种显存利用策略,让我们可以大概更灵活地控制步伐的显存利用方式:
- 仅在必要时申请显存空间(步伐初始运行时消耗很少的显存,随着步伐的运行而动态申请显存);
- 限制消耗固定巨细的显存(步伐不会超出限定的显存巨细,若超出的报错)。
- for gpu in gpus:
- tf.config.experimental.set_memory_growth(gpu, True)
复制代码
- 下面的方式是设置Tensorflow固定消耗GPU:0的2GB显存。
- tf.config.experimental.set_virtual_device_configuration(
- gpus[0],
- [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)]
- )
复制代码 4. 单GPU模仿多GPU情况
上面的方式不仅可以设置显存的利用,还可以在只有单GPU的情况模仿多GPU举行调试。
- tf.config.experimental.set_virtual_device_configuration(
- gpus[0],
- [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048),
- tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
复制代码 上面的代码就在GPU:0上创建了两个显存均为 2GB 的虚拟 GPU。
进一步说,在物理GPU0上虚拟,那么利用
- with tf.device('/device:GPU:3')
复制代码 做指定gpu盘算时,如果gpu0虚拟成3个,那么在 /device:GPU:3 中的gpu序数中,物理gpu1序号为3,即依次往后推
Tensorflow 2.0 GPU的利用与限制利用率及虚拟多GPU
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |