DEBUG.WIKI
RackNerd;$21.99/年 · 1GB KVM
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →
腾讯云;让你的想法跑起来;轻量服务器 · 建站 / Docker / API;查看产品 →

解决 TensorFlow 报错 OOM when allocating tensor 指南

分析 TensorFlow 启动时预占全部 GPU 显存触发 OOM 的排查方法,提供 set_memory_growth 动态显存分配方案。

问题现象

运行 TensorFlow 脚本时抛出显存分配失败异常:

2026-11-15 12:00:00.123456: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at conv_ops_fused_impl.h:625 : RESOURCE_EXHAUSTED: OOM when allocating tensor with shape [64,256,56,56] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc

触发根因

  1. TensorFlow 默认行为是在启动时一次性占满所有可见 GPU 的全部可用显存。
  2. 当有多个并发进程或与其他任务共享 GPU 时,默认贪婪分配策略立刻引发系统显存枯竭冲突。

解决步骤与操作命令

步骤一:开启显存按需增长(Memory Growth)

在脚本最开始初始化代码处加入动态显存增长配置:

import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
if gpus:
    try:
        for gpu in gpus:
            # 开启按需分配显存,不再一次性独占
            tf.config.experimental.set_memory_growth(gpu, True)
    except RuntimeError as e:
        print(e)

步骤二:硬性限制单个进程显存使用上限

若希望严格限制最大显存使用量(例如限制为 4GB):

if gpus:
    try:
        tf.config.set_logical_device_configuration(
            gpus[0],
            [tf.config.LogicalDeviceConfiguration(memory_limit=4096)]
        )
    except RuntimeError as e:
        print(e)

步骤三:降低图片分辨率或 Batch 大小

对于卷积神经网络(CNN),下采样特征图或减少每次前向传播的批次数量。

验证确认

重新启动程序执行: TensorFlow 进程平稳启动,显存随训练批次按需动态增长,未再抛出 RESOURCE_EXHAUSTED 异常。