tensorflow - 设置 tensorflow.keras.mixed_precision.Policy('mixed_float16') 几乎耗尽了所有 GPU 内存
问题描述
我注意到当我在代码中调用这两行时
policy = mixed_precision.Policy('mixed_float16')
mixed_precision.set_policy(policy)
在我的内核会话的其余部分中,我的 GPU 内存会激增并保持这种状态。在我重新启动内核之前,它不会再次关闭。
当我试图训练一个更大的图像分类模型时,我注意到了这一点,但它内存不足。
这是正常的吗?
我正在使用 tensorflow 版本 2.4.0
解决方案
这很正常。根据TensorFlow GPU 指南:
默认情况下,TensorFlow 将几乎所有 GPU 的所有 GPU 内存都映射
CUDA_VISIBLE_DEVICES
到进程可见的所有 GPU 上。这样做是为了通过减少内存碎片更有效地使用设备上相对宝贵的 GPU 内存资源。
使用混合精度允许您将更大的模型加载到 GPU 上。这并不一定意味着 TensorFlow 会保留更少的 GPU 内存。
有两个选项可以限制 GPU 上的内存。这些示例可在此答案开头的链接中找到。
- 使用
tf.config.experimental.set_memory_growth
.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across GPUs
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Memory growth must be set before GPUs have been initialized
print(e)
- 用于
tf.config.experimental.set_virtual_device_configuration
设置 GPU 内存的硬上限。
gpus = tf.config.list_physical_devices('GPU')
if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Virtual devices must be set before GPUs have been initialized
print(e)
推荐阅读
- windows - 在 Md5deep 结果上运行 findstr 并仅输出目录
- javascript - 无法从下拉列表中获取用户输入
- haskell - 将浮点列表字符串转换为 Haskell 中的浮点列表列表
- elasticsearch - Elasticsearch:使用一个索引与多个索引时性能有何不同
- c++ - Visual Studio C++ 寻找不存在的 obj,link1104
- angularjs - AngularJS 和 WebAPI 中的 IdentityServer 角色/权限
- html - CSS / HTML中的字体不会改变?
- c# - OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError 在 WebElement 提交单击
- c++ - 将 opencv_world400.lib 和 opencv_world400d.lib 添加到依赖项中,仍然出现 LNK2001 错误
- azure - API 管理设置策略给出错误 id 为“servicefabric”的后端找不到