[学习笔记]深度学习:pytorch多GPU训练

一、检查GPU可用性

运行以下代码检查GPU的数量,若数量大于1,则可以启用多GPU训练

import torch

# 打印可用 GPU 的数量
print("多少个GPU啊", torch.cuda.device_count())

# 列出所有可用的 GPU
for i in range(torch.cuda.device_count()):
    print("GPU", i+1, ":", torch.cuda.get_device_name(i))

二、使用 DataParallel进行多GPU训练

   代码如下

model = ConvNet()  # 这里的 ConvNet 是提前定好的模型类
if torch.cuda.device_count() > 1:
    print("用这么多的GPU: ", torch.cuda.device_count())
    # 包装模型以使用多 GPU
    model = torch.nn.DataParallel(model)

model.to(torch.device("cuda"))  # 将模型移到 GPU

三、DistributedDataParallel的浅显探索

        对于更高效的多 GPU 训练,可以使用 torch.nn.parallel.DistributedDataParallel,到那时这会比刚刚的有更复杂的设置(多进程运行和特定的数据加载方式)。这种方法通常用于更大规模的训练任务和跨多个节点的训练,这里留个标记,日后需要再做拓展。

        DataParallel通常不需要修改数据加载方式,但 DistributedDataParallel则需要使用 torch.utils.data.distributed.DistributedSampler 来控制数据的采样方式。

from torch.utils.data import DataLoader, Dataset, DistributedSampler

# 提前定义好的数据集
dataset = YourDataset()
sampler = DistributedSampler(dataset)
data_loader = DataLoader(dataset, batch_size=batch_size, sampler=sampler)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值