当前位置:   article > 正文

pytorch 指定GPU设备

pytorch 指定GPU设备

使用os.environ["CUDA_VISIBLE_DEVICES"]

这种方法是通过环境变量限制可见的CUDA设备,从而在多个GPU的机器上只让PyTorch看到并使用指定的GPU。这种方式的好处是所有后续的CUDA调用都会使用这个GPU,并且代码中不需要显式地指定设备索引。

  1. import os
  2. # 设置只使用2号GPU
  3. os.environ["CUDA_VISIBLE_DEVICES"] = '2'
  4. import torch
  5. import torch.nn as nn
  6. # 检查PyTorch是否检测到GPU
  7. if torch.cuda.is_available():
  8. print(f"Using GPU: {torch.cuda.get_device_name(0)}") # 注意这里是0,因为只有一个可见的GPU
  9. else:
  10. print("No GPU available, using CPU instead.")
  11. # 定义模型
  12. class YourModel(nn.Module):
  13. def __init__(self):
  14. super(YourModel, self).__init__()
  15. self.layer = nn.Linear(10, 1)
  16. def forward(self, x):
  17. return self.layer(x)
  18. # 创建模型并移动到GPU
  19. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  20. model = YourModel().to(device)
  21. # 示例数据和前向传播
  22. input_data = torch.randn(5, 10).to(device)
  23. output = model(input_data)
  24. print(output)

直接指定设备索引

这种方法是在代码中直接指定要使用的设备索引,无需修改环境变量。这种方式更加显式,并且可以在同一脚本中使用多个不同的GPU

  1. import torch
  2. import torch.nn as nn
  3. # 检查设备是否可用并打印设备名称
  4. if torch.cuda.is_available():
  5. device = torch.device("cuda:2") # 直接指定设备索引
  6. print(f"Using GPU: {torch.cuda.get_device_name(2)}")
  7. else:
  8. device = torch.device("cpu")
  9. print("No GPU available, using CPU instead.")
  10. # 定义模型
  11. class YourModel(nn.Module):
  12. def __init__(self):
  13. super(YourModel, self).__init__()
  14. self.layer = nn.Linear(10, 1)
  15. def forward(self, x):
  16. return self.layer(x)
  17. # 创建模型并移动到指定的GPU
  18. model = YourModel().to(device)
  19. # 示例数据和前向传播
  20. input_data = torch.randn(5, 10).to(device)
  21. output = model(input_data)
  22. print(output)

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/816618
推荐阅读
相关标签
  

闽ICP备14008679号