pytorch 指定GPU设备

使用os.environ["CUDA_VISIBLE_DEVICES"]

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

import os

# 设置只使用2号GPU
os.environ["CUDA_VISIBLE_DEVICES"] = '2'

import torch
import torch.nn as nn

# 检查PyTorch是否检测到GPU
if torch.cuda.is_available():
    print(f"Using GPU: {torch.cuda.get_device_name(0)}")  # 注意这里是0,因为只有一个可见的GPU
else:
    print("No GPU available, using CPU instead.")

# 定义模型
class YourModel(nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.layer = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.layer(x)

# 创建模型并移动到GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = YourModel().to(device)

# 示例数据和前向传播
input_data = torch.randn(5, 10).to(device)
output = model(input_data)
print(output)

直接指定设备索引

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

import torch
import torch.nn as nn

# 检查设备是否可用并打印设备名称
if torch.cuda.is_available():
    device = torch.device("cuda:2")  # 直接指定设备索引
    print(f"Using GPU: {torch.cuda.get_device_name(2)}")
else:
    device = torch.device("cpu")
    print("No GPU available, using CPU instead.")

# 定义模型
class YourModel(nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.layer = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.layer(x)

# 创建模型并移动到指定的GPU
model = YourModel().to(device)

# 示例数据和前向传播
input_data = torch.randn(5, 10).to(device)
output = model(input_data)
print(output)

相关推荐

  1. pytorch 指定GPU设备

    2024-07-12 21:18:03       22 阅读
  2. PYTorch训练和推理 指定GPU

    2024-07-12 21:18:03       38 阅读
  3. 指定GPU无效

    2024-07-12 21:18:03       55 阅读
  4. paddle指定运行gpu

    2024-07-12 21:18:03       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 21:18:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 21:18:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 21:18:03       57 阅读
  4. Python语言-面向对象

    2024-07-12 21:18:03       68 阅读

热门阅读

  1. C#-反射

    C#-反射

    2024-07-12 21:18:03      15 阅读
  2. Codeforces Round #956 (Div. 2) and ByteRace 2024 A-C题解

    2024-07-12 21:18:03       23 阅读
  3. 科技与狠活

    2024-07-12 21:18:03       19 阅读
  4. 大语言模型系列-Transformer

    2024-07-12 21:18:03       21 阅读
  5. Git-Updates were rejected 解决

    2024-07-12 21:18:03       20 阅读
  6. 推荐系统中的冷启动问题及其解决方案

    2024-07-12 21:18:03       18 阅读
  7. vue在线预览excel、pdf、word文件

    2024-07-12 21:18:03       24 阅读
  8. 解决el-table表格没有横向滚动条

    2024-07-12 21:18:03       22 阅读