[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
一、获得当前主机上特定运算设备的列表
gpus = tf.config.experimental.list_physical_devices(device_type='GPU') cpus =
tf.config.experimental.list_physical_devices(device_type='CPU') print(gpus,
cpus)
二、设置当前程序可见的设备范围
默认情况下 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"
都可以达到同样的效果。
三、显存的使用
默认情况下,TensorFlow 将使用几乎所有可用的显存,以避免内存碎片化所带来的性能损失。
但是TensorFlow 提供两种显存使用策略,让我们能够更灵活地控制程序的显存使用方式:
1. 仅在需要时申请显存空间(程序初始运行时消耗很少的显存,随着程序的运行而动态申请显存);
2. 限制消耗固定大小的显存(程序不会超出限定的显存大小,若超出的报错)。
设置仅在需要时申请显存空间。
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)] )
四、单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。