简单的方式,设置pytorch框架上,使用两个GPU进行加速
时间: 2024-05-03 09:23:32 浏览: 94
使用PyTorch框架进行多GPU加速非常简单,只需要遵循以下步骤:
1. 导入必要的PyTorch库
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
```
2. 定义模型
```python
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.fc2 = nn.Linear(512, 10)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
model = MyModel()
```
3. 定义数据集
```python
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=2)
```
4. 设置GPU设备
```python
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
```
5. 将模型放到GPU上
```python
model = model.to(device)
```
6. 定义损失函数和优化器
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
```
7. 训练模型
```python
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
```
8. 在测试集上测试模型
```python
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
```
可以看到,只需要在适当的地方添加一些代码,就可以轻松地将PyTorch模型放在多个GPU上进行加速运算。
阅读全文