鱼C论坛

 找回密码
 立即注册
查看: 1334|回复: 1

[学习笔记] torch 指定gpu进行训练

[复制链接]
发表于 2023-7-26 16:57:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Handsome_zhou 于 2023-9-21 10:52 编辑

总结:如果设置了环境变量,模型和张量就用.cuda()方法进行GPU迁移。否则使用.to(device)

1、sh文件中使用CUDA_VISIBLE_DEVICE环境变量:
        在训练脚本运行之前,可以设置'CUDA_VISIBLE_DEVICES'来指定使用哪个GPU。这是最简单的方式,适用于单个或多个GPU的情况。
        例如,当有单机多GPU时,可以在sh文件中将以下命令添加到训练脚本之前,以选择第一块GPU:
  1.         export CUDA_VISIBLE_DEVICES=0
  2.         python your_training_script.py
复制代码


2、py文件中使用torch.device对象:
        可以使用torch.device对象将模型和张量移动到特定的GPU上。这样可以在代码中灵活地控制GPU的选择。
  1.         import torch

  2.         device = torch.device("cuda:0")  # 选择第一块 GPU
  3.         #或者使用 device = 0 if torch.cuda.is_available() else -1
  4.         model = YourModel().to(device)
  5.         input_tensor = input_tensor.to(device)
复制代码


3、在命令行中指定GPU设备:
        可以在命令行中通过传递'--device'或者类似的参数来指定要使用的GPU设备。然后在训练脚本中解析这些参数并将模型和数据移到相应的设备上。
  1. python your_training_script.py --device 0
复制代码


4、使用torch.nn.DataParallel或者torch.nn.parallel.DistributedDataParallel进行多GPU训练。
        这两种方法可以在多个GPU上进行模型的正向和反向传播,使训练更快。
  1.         import torch
  2.         from torch.nn import DataParallel

  3.         device_ids = [0, 1]  # 指定要使用的 GPU 设备
  4.         model = YourModel()
  5.         model = DataParallel(model, device_ids=device_ids)
  6.         model.to(device_ids[0])  # 将模型移动到第一个 GPU
复制代码


        4.1、使用torch.nn.DataParallel进行多GPU训练的示例:

  1. # 测试可用
  2. import numpy as np
  3. import torch
  4. import torch.nn as nn
  5. from torch.autograd import Variable
  6. import os
  7. import torch.optim as optim
  8. from torch.utils.data import DataLoader, TensorDataset

  9. # 设置CUDA可见设备
  10. os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"

  11. class Net(nn.Module):
  12.     def __init__(self):
  13.         super(Net, self).__init__()

  14.         modules = [
  15.             nn.Linear(10, 3),
  16.             nn.Linear(3, 4),
  17.             nn.Linear(4, 5),
  18.         ]
  19.         self.net = nn.ModuleList(modules)

  20.     def forward(self, inputs):
  21.         for i, n in enumerate(self.net):
  22.             inputs = n(inputs)

  23.         return inputs

  24. def main():
  25.     X = np.random.uniform(-1, 1, (15, 10)).astype(np.float32)
  26.     y = np.random.randint(0, 5, (15,))
  27.     print(X.shape)
  28.     print(y.shape)

  29.     model = Net()
  30.     loss = nn.CrossEntropyLoss()
  31.     print('Model:', type(model))
  32.     print('Loss:', type(loss))

  33.     X = torch.from_numpy(X)
  34.     y = torch.from_numpy(y)
  35.     print('X', X.size(), 'y', y.size())

  36.     if torch.cuda.is_available():
  37.         # 将模型移到GPU上,并使用DataParallel
  38.         model = nn.DataParallel(model, device_ids=[0, 1])
  39.         model = model.cuda()

  40.         optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
  41.         loss = loss.cuda()
  42.         X = X.cuda()
  43.         y = y.cuda()
  44.         print('Using', torch.cuda.device_count(), 'GPUs')

  45.     else:
  46.         print('No GPUs available')

  47.     dataset = TensorDataset(X, y)
  48.     dataloader = DataLoader(dataset, batch_size=32, shuffle=True)

  49.     epochs = 10000
  50.     for epoch in range(epochs):
  51.         running_loss = 0.0
  52.         for i, data in enumerate(dataloader, 0):
  53.             inputs, labels = data
  54.             optimizer.zero_grad()

  55.             # 前向传播
  56.             outputs = model(inputs)
  57.             loss_value = loss(outputs, labels)

  58.             # 反向传播和优化
  59.             loss_value.backward()
  60.             optimizer.step()

  61.             running_loss += loss_value.item()

  62.             # print(f"第 {i+1} 批,损失: {loss_value.item()}")

  63.         print(f"第 {epoch+1} 轮,平均损失: {running_loss / len(dataloader)}")

  64.     print("训练结束")

  65. if __name__ == '__main__':
  66.     main()
复制代码





       
  1. import os
  2. import torch
  3. import torch.nn as nn
  4. import torch.optim as optim
  5. from torch.nn.parallel import DataParallel

  6. # 设置 CUDA_VISIBLE_DEVICES 环境变量来指定使用 GPU 0 和 1
  7. os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'

  8. # 定义一个简单的模型
  9. class SimpleModel(nn.Module):
  10.     def __init__(self):
  11.         super(SimpleModel, self).__init__()
  12.         self.fc = nn.Linear(10, 1)

  13.     def forward(self, x):
  14.         return self.fc(x)

  15. # 创建模型并将其包装在 DataParallel 中
  16. model = SimpleModel()
  17. model = DataParallel(model)

  18. # 创建数据加载器和优化器
  19. # 注意:您需要适应您的数据加载逻辑和损失函数
  20. dataloader = YourDataLoader()
  21. optimizer = optim.SGD(model.parameters(), lr=0.001)

  22. # 模拟训练循环
  23. for epoch in range(num_epochs):
  24.     for batch_data, batch_labels in dataloader:
  25.         # batch_data, batch_labels 已经在 DataParallel 内部自动分发到多个 GPU
  26.         optimizer.zero_grad()
  27.         outputs = model(batch_data)
  28.         loss = YourLossFunction(outputs, batch_labels)
  29.         loss.backward()
  30.         optimizer.step()

  31. # 保存模型
  32. torch.save(model.module.state_dict(), 'model.pth')  # 使用 model.module 获得原始模型的状态字典
复制代码


        4.2、使用torch.nn.parallel.DistributedDataParallel进行多GPU训练的示例:
        使用 torch.nn.parallel.DistributedDataParallel(DDP)进行多 GPU 训练通常需要在多个进程中运行,其中每个进程可以使用一个或多个 GPU。
  1. import torch
  2. import torch.nn as nn
  3. import torch.optim as optim
  4. import torch.distributed as dist
  5. import torch.multiprocessing as mp
  6. from torch.nn.parallel import DistributedDataParallel

  7. # 定义一个简单的模型
  8. class SimpleModel(nn.Module):
  9.     def __init__(self):
  10.         super(SimpleModel, self).__init__()
  11.         self.fc = nn.Linear(10, 1)

  12.     def forward(self, x):
  13.         return self.fc(x)

  14. # 定义一个训练函数,该函数在每个进程中运行
  15. def train(rank, world_size):
  16.     # 设置每个进程的 GPU 设备,这里假设有4个GPU
  17.     os.environ['CUDA_VISIBLE_DEVICES'] = str(rank)

  18.     # 初始化分布式环境
  19.     dist.init_process_group(backend='nccl', init_method='env://')

  20.     # 创建模型并将其包装在 DistributedDataParallel 中
  21.     model = SimpleModel().cuda()
  22.     model = DistributedDataParallel(model)

  23.     # 创建数据加载器和优化器
  24.     # 注意:您需要适应您的数据加载逻辑和损失函数
  25.     dataloader = YourDataLoader()
  26.     optimizer = optim.SGD(model.parameters(), lr=0.001)

  27.     # 模拟训练循环
  28.     for epoch in range(num_epochs):
  29.         for batch_data, batch_labels in dataloader:
  30.             optimizer.zero_grad()
  31.             outputs = model(batch_data)
  32.             loss = YourLossFunction(outputs, batch_labels)
  33.             loss.backward()
  34.             optimizer.step()

  35. if __name__ == '__main__':
  36.     # 设置分布式训练的参数
  37.     num_processes = 4  # 四个进程,每个进程使用一个 GPU
  38.     mp.spawn(train, args=(num_processes, ), nprocs=num_processes)
复制代码





5、py文件中通过os.environ['CUDA_VISIBLE_DEVICES']指定GPU进行训练
        使用'CUDA_VISIBLE_DEVICES'环境变量来选择要使用的GPU,然后使用.cuda()方法将模型和张量移到指定的GPU上。

  1.         import os
  2.         import torch

  3.         # 设置 CUDA_VISIBLE_DEVICES 环境变量来指定 GPU
  4.         os.environ['CUDA_VISIBLE_DEVICES'] = '0'  # 选择第一块 GPU

  5.         # 创建一个简单的模型并将其移到 GPU 上
  6.         model = torch.nn.Linear(10, 1).cuda()  # 这里将模型移到指定的 GPU 上

  7.         # 创建一个示例输入并将其移到 GPU 上
  8.         input_tensor = torch.randn(1, 10).cuda()

  9.         # 运行模型
  10.         output = model(input_tensor)

  11.         # 确保输出是在指定的 GPU 上
  12.         print(output.device)  # 输出应该是 "cuda:0"
复制代码


       



       
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-7-26 17:06:21 | 显示全部楼层
你这个头像绝了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 07:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表