-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13_ddp.py
121 lines (109 loc) · 4.28 KB
/
13_ddp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.nn.parallel import DistributedDataParallel as DDP
import time
import os
def print0(message):
if dist.is_initialized():
if dist.get_rank() == 0:
print(message, flush=True)
else:
print(message, flush=True)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(train_loader,model,criterion,optimizer,epoch,device,world_size):
model.train()
t = time.perf_counter()
for batch_idx, (data, target) in enumerate(train_loader):
data = data.to(device)
target = target.to(device)
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch_idx % 200 == 0:
print0('Train Epoch: {} [{:>5}/{} ({:.0%})]\tLoss: {:.6f}\t Time:{:.4f}'.format(
epoch, batch_idx * len(data) * world_size, len(train_loader.dataset),
batch_idx / len(train_loader), loss.data.item(),
time.perf_counter() - t))
t = time.perf_counter()
def validate(val_loader,model,criterion,device):
model.eval()
val_loss, val_acc = 0, 0
for data, target in val_loader:
data = data.to(device)
target = target.to(device)
output = model(data)
loss = criterion(output, target)
val_loss += loss.item()
pred = output.data.max(1)[1]
val_acc += 100. * pred.eq(target.data).cpu().sum() / target.size(0)
val_loss /= len(val_loader)
val_acc /= len(val_loader)
print0('\nValidation set: Average loss: {:.4f}, Accuracy: {:.1f}%\n'.format(
val_loss, val_acc))
def main():
master_addr = os.getenv("MASTER_ADDR", default="localhost")
master_port = os.getenv('MASTER_PORT', default='8888')
method = "tcp://{}:{}".format(master_addr, master_port)
rank = int(os.getenv('OMPI_COMM_WORLD_RANK', '0'))
world_size = int(os.getenv('OMPI_COMM_WORLD_SIZE', '1'))
dist.init_process_group("nccl", init_method=method, rank=rank, world_size=world_size)
ngpus = torch.cuda.device_count()
device = torch.device('cuda',rank % ngpus)
epochs = 10
batch_size = 32
learning_rate = 1.0e-02
train_dataset = datasets.MNIST('./data',
train=True,
download=True,
transform=transforms.ToTensor())
val_dataset = datasets.MNIST('./data',
train=False,
transform=transforms.ToTensor())
train_sampler = torch.utils.data.distributed.DistributedSampler(
train_dataset,
num_replicas=dist.get_world_size(),
rank=dist.get_rank())
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
sampler=train_sampler)
val_loader = torch.utils.data.DataLoader(dataset=val_dataset,
batch_size=batch_size,
shuffle=False)
model = CNN().to(device)
model = DDP(model, device_ids=[rank % ngpus])
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
for epoch in range(epochs):
model.train()
train(train_loader,model,criterion,optimizer,epoch,device,world_size)
validate(val_loader,model,criterion,device)
dist.destroy_process_group()
if __name__ == '__main__':
main()