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

Azure ML单节点多GPU集群训练:脚本重复执行问题及用法咨询

问题原因及解决方法

现象原因

这是因为深度学习框架在单节点多GPU训练时,默认会为每张GPU启动一个独立进程(数据并行模式)。你的打印语句写在分布式训练初始化之前的进程启动阶段,所以每个GPU对应的进程都会执行一遍这段打印代码;而训练过程因为框架的分布式协调机制(比如PyTorch DDP、TensorFlow MirroredStrategy),会统一执行一次完整的训练逻辑,因此看起来训练只跑了一次。

正确使用多GPU的配置步骤

1. 配置RunConfig的分布式参数

在创建RunConfig时,需要明确指定单节点的进程数(对应GPU数量),以AML的PyTorch配置为例:

from azureml.core.runconfig import RunConfiguration
from azureml.core.runconfig import PyTorchConfiguration

# 配置分布式训练参数:单节点,每个节点8个进程(对应8张V100)
dist_config = PyTorchConfiguration(node_count=1, process_count_per_node=8)

runconfig = RunConfiguration()
runconfig.target = compute_target
runconfig.framework = "pytorch"
runconfig.distributed_job_config = dist_config
# 补充其他配置(如Docker环境、conda依赖等)

2. 在训练脚本中区分主进程,控制非训练代码的执行

修改训练脚本,只让主进程执行打印、数据预处理初始化等不需要重复执行的逻辑,以PyTorch为例:

import torch.distributed as dist

def run_script_stage(input_ds, output_ds, args):
    # 初始化分布式环境
    dist.init_process_group(backend="nccl")
    
    # 仅主进程执行打印和初始化操作
    if dist.is_main_process():
        input_ls, output_ls = print_stage_input_output(input_ds, output_ds, args)
        params = json.loads(args.params)
        print(f"params: {params}")
    
    # 训练逻辑(框架会自动分配到多GPU执行)
    # some lines for accessing the data from the blob, and other lines for training the model
    
    # 销毁分布式环境
    dist.destroy_process_group()

如果使用TensorFlow,可通过tf.distribute.MirroredStrategy控制:

import tensorflow as tf

def run_script_stage(input_ds, output_ds, args):
    strategy = tf.distribute.MirroredStrategy()
    
    # 仅主worker执行初始化和打印
    if tf.distribute.get_replica_context().replica_id_in_sync_group == 0:
        input_ls, output_ls = print_stage_input_output(input_ds, output_ds, args)
        params = json.loads(args.params)
        print(f"params: {params}")
    
    with strategy.scope():
        # 构建模型和训练逻辑
        # some lines for accessing the data from the blob, and other lines for training the model

3. 确保训练逻辑适配分布式框架

训练部分的代码需要适配分布式模式:比如PyTorch中用DistributedDataParallel包装模型、DistributedSampler加载数据;TensorFlow中把模型构建放在strategy.scope()内,确保数据能正确分发到各GPU。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:27:54