ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

tensorflow如何使用gpu

2022-06-28 23:35:37  阅读:160  来源: 互联网

标签:gpu devices 如何 gpus GPU tf tensorflow config experimental


https://blog.csdn.net/To_be_little/article/details/124438800

 

目录
1、查看GPU的数量
2、设置GPU加速
3、单GPU模拟多GPU环境
1、查看GPU的数量
import tensorflow as tf
# 查看gpu和cpu的数量
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus, cpus)
1
2
3
4
5
2、设置GPU加速
第一种:限制使用的gpu,没有限制消耗内存的大小:

  通过 tf.config.experimental.set_visible_devices 。可以设置当前程序可见的设备范围(当前程序只会使用自己可见的设备,不可见的设备不会被当前程序使用。使用部分gpu加速。如下面使用gpu设备0,1

gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
tf.config.experimental.set_visible_devices(devices=gpus[0:2], device_type='GPU')
1
2
或者使用os来进行控制:使用环境变量 CUDA_VISIBLE_DEVICES 也可以控制程序所使用的GPU。

import os
os.environ['CUDA_VISIBLE_DEVICES'] = "2,3"
1
2
第二种:动态申请显存,仅在需要时申请显存空间。

  通过 tf.config.experimental.set_memory_growth 将GPU的显存使用策略设置为“仅在需要时申请显存空间”。以下代码将所有GPU设置为仅在需要时申请显存空间:

gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
1
2
3
第三种:限制使用的gpu,并且限制使用的内存大小。
  通过 tf.config.experimental.set_virtual_device_configuration 选项并传入 tf.config.experimental.VirtualDeviceConfiguration 实例,设置TensorFlow固定消耗 GPU:0 的1GB显存

gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
1
2
3
4
3、单GPU模拟多GPU环境
  当我们的本地开发环境只有一个GPU,但却需要编写多GPU的程序在工作站上进行训练任务时,TensorFlow为我们提供了一个方便的功能,可以让我们在本地开发环境中建立多个模拟GPU,从而让多GPU的程序调试变得更加方便。以下代码在实体GPU GPU:0 的基础上建立了两个显存均为2GB的虚拟GPU。

gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048),
tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
————————————————
版权声明:本文为CSDN博主「浅冲一下」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/To_be_little/article/details/124438800

标签:gpu,devices,如何,gpus,GPU,tf,tensorflow,config,experimental
来源: https://www.cnblogs.com/chinasoft/p/16421646.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有