单机多GPU训练

torch.distributed

from torch.utils.data.distributed import DistributedSampler
# 1) 初始化
torch.distributed.init_process_group(backend="nccl")

# 2) 配置每个进程的gpu
local_rank = torch.distributed.get_rank()
print('local_rank',local_rank)
torch.cuda.set_device(local_rank)
device = torch.device("cuda", local_rank)


# 3)使用DistributedSampler
rand_loader = DataLoader(dataset=dataset,
                         batch_size=batch_size,
                         sampler=DistributedSampler(dataset))

# 4) 封装之前要把模型移到对应的gpu
model.to(device)
 
if torch.cuda.device_count() > 1:
    print("Let's use", torch.cuda.device_count(), "GPUs!")
    # 5) 封装
    model = torch.nn.parallel.DistributedDataParallel(model,
                                                      device_ids=[local_rank],
                                                      output_device=local_rank)

运行

python -m torch.distributed.launch --nproc_per_node=2 main.py

使用argparse.ArgumentParser()解析参数时可能会出现unrecognized arguments: --local-rank=2的错误一般只需要加上
parser.add_argument("--rank", default=-1, type=int, help="node rank for distributed training")就行
但是在新服务器上发现此方法失效,暂时只能能将argparse.ArgumentParser()模块删去,解决报错。

报错显示为--local-rank没有识别,之前一直加的参数为parser.add_argument("--local_rank", default=-1, type=int) 现修改为parser.add_argument("--local-rank", default=-1, type=int)(下划线改为破折号)正常运行。

报错

RuntimeError: Expected to have finished reduction in the prioriteration before starting a new one. This error indicates that yourmodule has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument find_unused_parameters=True to torch.nn.parallel.DistributedDataParallel; (2) making sure all forward function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn’t able to locate the output tensors in the return value of your module’s forward function. Please include the loss function and the structure of the return value of forward of your module when reporting this issue (e.g. list, dict, iterable).

使用单GPU可以正常梯度下降,多GPU时提醒这个报错。
torch.nn.parallel.DistributedDataParallel中加入find_unused_parameters=True忽略这些报错参数

    model = torch.nn.parallel.DistributedDataParallel(model,find_unused_parameters=True, 
                                                      device_ids=[local_rank],
                                                      output_device=local_rank)
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Keras中进行单机GPU的并行训练通常有两种方法:数据并行和模型并行。 数据并行:将数据分成多个小批次,每个GPU使用不同的小批次进行训练,然后将梯度聚合并更新模型。这种方法适用于较大的模型和较小的批量大小。 模型并行:将模型分成多个部分,每个GPU训练其中的一部分,然后将梯度聚合并更新模型。这种方法适用于较大的模型和较大的批量大小。 下面是一个使用数据并行的例子: ```python import tensorflow as tf from keras.models import Model from keras.layers import Input, Dense from keras.utils import multi_gpu_model num_gpus = 2 batch_size = 64 # 定义模型 input_layer = Input(shape=(100,)) hidden_layer = Dense(64, activation='relu')(input_layer) output_layer = Dense(10, activation='softmax')(hidden_layer) model = Model(inputs=input_layer, outputs=output_layer) # 复制模型到多个GPU parallel_model = multi_gpu_model(model, gpus=num_gpus) # 编译模型 parallel_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 生成数据 x_train = tf.random.normal(shape=(1000, 100)) y_train = tf.random.normal(shape=(1000, 10)) # 训练模型 parallel_model.fit(x_train, y_train, batch_size=batch_size*num_gpus, epochs=10) ``` 在上面的例子中,我们使用了`multi_gpu_model`函数将模型复制到两个GPU中。然后我们编译这个模型,并使用`fit`函数进行训练。我们将批量大小乘以GPU的数量来确保每个GPU使用的批量大小相同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值