在Linux上,PyTorch支持多种并行计算方式,主要包括数据并行和模型并行。以下是实现这些并行计算的方法:
数据并行是指将数据分成多个小批次(batches),然后在多个GPU上并行处理这些小批次。PyTorch通过torch.nn.DataParallel
模块来实现数据并行。
准备模型:
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc = nn.Linear(10, 10)
def forward(self, x):
return self.fc(x)
model = MyModel()
使用DataParallel:
if torch.cuda.device_count() > 1:
print(f"Let's use {torch.cuda.device_count()} GPUs!")
model = nn.DataParallel(model)
将模型和数据移动到GPU:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
训练模型:
for data, target in dataloader:
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = nn.CrossEntropyLoss()(output, target)
loss.backward()
optimizer.step()
模型并行是指将模型的不同部分放在不同的GPU上进行处理。PyTorch没有内置的模型并行模块,但可以通过手动管理张量的位置来实现。
假设我们有一个模型,其中一部分在前向传播中计算,另一部分在后向传播中计算。
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10).to('cuda:0')
self.fc2 = nn.Linear(10, 10).to('cuda:1')
def forward(self, x):
x = self.fc1(x.to('cuda:0'))
x = x.to('cuda:1')
return self.fc2(x)
model = MyModel()
混合并行结合了数据并行和模型并行。可以在数据并行中使用模型并行来进一步优化。
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10).to('cuda:0')
self.fc2 = nn.Linear(10, 10).to('cuda:1')
def forward(self, x):
x = self.fc1(x.to('cuda:0'))
x = x.to('cuda:1')
return self.fc2(x)
model = MyModel()
if torch.cuda.device_count() > 1:
print(f"Let's use {torch.cuda.device_count()} GPUs!")
model = nn.DataParallel(model)
model.to('cuda:0') # 将模型移动到第一个GPU
# 训练模型
for data, target in dataloader:
data, target = data.to('cuda:0'), target.to('cuda:0')
optimizer.zero_grad()
output = model(data)
loss = nn.CrossEntropyLoss()(output, target)
loss.backward()
optimizer.step()
通过以上方法,可以在Linux上实现PyTorch的并行计算,提高训练速度和效率。