赞
踩
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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。