在Linux系统中,PyTorch与CUDA的协同工作主要依赖于NVIDIA提供的CUDA工具包和驱动程序。以下是它们协同工作的基本步骤:
安装CUDA工具包:
安装cuDNN库(可选但推荐):
安装PyTorch:
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
这个命令会安装与CUDA 11.3兼容的PyTorch版本。验证安装:
import torch
# 创建一个张量
x = torch.rand(3, 4)
# 将张量移动到GPU上
x = x.cuda()
# 打印张量
print(x)
编写和运行CUDA加速的PyTorch代码:
.cuda()
方法将张量和模型移动到GPU上,从而利用CUDA加速计算。import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = x.view(-1, 784)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 创建模型实例并移动到GPU上
model = Net().cuda()
# 创建一个输入张量并移动到GPU上
input_tensor = torch.rand(1, 1, 28, 28).cuda()
# 前向传播
output = model(input_tensor)
# 打印输出
print(output)
通过以上步骤,你可以在Linux系统中成功配置和使用PyTorch与CUDA进行协同工作。