You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Keras配置多GPU后仅单卡运行?附MirroredStrategy实现代码

TensorFlow MirroredStrategy单卡生效问题排查方案
  • 优先修正模型编译的作用域问题
    你的代码仅将模型实例化放在了strategy.scope()上下文内,model.compile()操作在作用域外,导致分布式训练配置未生效,这是最常见的单卡生效原因,修正后的代码如下:
    cross_device_ops = tf.distribute.HierarchicalCopyAllReduce()
    strategy = tf.distribute.MirroredStrategy(["device:GPU:%d" % i for i in range(2)],cross_device_ops=cross_device_ops)
    print('Number of devices: {}'.format(strategy.num_replicas_in_sync))
    
    with strategy.scope():
        model = UNet()
        model.summary()
        # compile操作必须放在scope作用域内
        model.compile(optimizer=Adam(lr=0.0001), loss=dice_coef_loss, metrics=[dice_coef])
    
  • 验证物理GPU识别状态
    运行以下代码确认TensorFlow可以识别到所有目标GPU:
    import tensorflow as tf
    print(tf.config.list_physical_devices('GPU'))
    
    若输出少于2个GPU,检查CUDA、cuDNN、TensorFlow版本匹配关系,以及显卡驱动是否正常安装。
  • 调整全局批量大小配置
    MirroredStrategy会自动将全局批量大小拆分到各卡并行运算,全局批量大小需要设置为单卡最优批量大小 * 卡数(此处为2),如果批量设置过小,会出现仅单卡有负载的假象。
  • 检查跨设备通信配置兼容性
    同机多GPU场景下框架会自动选择最优的跨设备通信实现,手动指定的HierarchicalCopyAllReduce可能存在硬件兼容性问题,可以删除自定义配置尝试恢复:
    strategy = tf.distribute.MirroredStrategy(["device:GPU:%d" % i for i in range(2)])
    
  • 优化数据加载逻辑
    若使用自定义数据生成器,可能存在IO瓶颈导致多卡无法并行加载数据,优先使用tf.data.Dataset接口加载数据,配置prefetch参数预加载数据,避免IO阻塞导致只有单卡处于运算状态。

内容的提问来源于stack exchange,提问作者Amanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 17:06:07