DDP-script.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
  2. # Source for "Build a Large Language Model From Scratch"
  3. # - https://www.manning.com/books/build-a-large-language-model-from-scratch
  4. # Code: https://github.com/rasbt/LLMs-from-scratch
  5. # Appendix A: Introduction to PyTorch (Part 3)
  6. import torch
  7. import torch.nn.functional as F
  8. from torch.utils.data import Dataset, DataLoader
  9. # NEW imports:
  10. import os
  11. import torch.multiprocessing as mp
  12. from torch.utils.data.distributed import DistributedSampler
  13. from torch.nn.parallel import DistributedDataParallel as DDP
  14. from torch.distributed import init_process_group, destroy_process_group
  15. # NEW: function to initialize a distributed process group (1 process / GPU)
  16. # this allows communication among processes
  17. def ddp_setup(rank, world_size):
  18. """
  19. Arguments:
  20. rank: a unique process ID
  21. world_size: total number of processes in the group
  22. """
  23. # rank of machine running rank:0 process
  24. # here, we assume all GPUs are on the same machine
  25. os.environ["MASTER_ADDR"] = "localhost"
  26. # any free port on the machine
  27. os.environ["MASTER_PORT"] = "12345"
  28. # initialize process group
  29. # Windows users may have to use "gloo" instead of "nccl" as backend
  30. # nccl: NVIDIA Collective Communication Library
  31. init_process_group(backend="nccl", rank=rank, world_size=world_size)
  32. torch.cuda.set_device(rank)
  33. class ToyDataset(Dataset):
  34. def __init__(self, X, y):
  35. self.features = X
  36. self.labels = y
  37. def __getitem__(self, index):
  38. one_x = self.features[index]
  39. one_y = self.labels[index]
  40. return one_x, one_y
  41. def __len__(self):
  42. return self.labels.shape[0]
  43. class NeuralNetwork(torch.nn.Module):
  44. def __init__(self, num_inputs, num_outputs):
  45. super().__init__()
  46. self.layers = torch.nn.Sequential(
  47. # 1st hidden layer
  48. torch.nn.Linear(num_inputs, 30),
  49. torch.nn.ReLU(),
  50. # 2nd hidden layer
  51. torch.nn.Linear(30, 20),
  52. torch.nn.ReLU(),
  53. # output layer
  54. torch.nn.Linear(20, num_outputs),
  55. )
  56. def forward(self, x):
  57. logits = self.layers(x)
  58. return logits
  59. def prepare_dataset():
  60. X_train = torch.tensor([
  61. [-1.2, 3.1],
  62. [-0.9, 2.9],
  63. [-0.5, 2.6],
  64. [2.3, -1.1],
  65. [2.7, -1.5]
  66. ])
  67. y_train = torch.tensor([0, 0, 0, 1, 1])
  68. X_test = torch.tensor([
  69. [-0.8, 2.8],
  70. [2.6, -1.6],
  71. ])
  72. y_test = torch.tensor([0, 1])
  73. train_ds = ToyDataset(X_train, y_train)
  74. test_ds = ToyDataset(X_test, y_test)
  75. train_loader = DataLoader(
  76. dataset=train_ds,
  77. batch_size=2,
  78. shuffle=False, # NEW: False because of DistributedSampler below
  79. pin_memory=True,
  80. drop_last=True,
  81. # NEW: chunk batches across GPUs without overlapping samples:
  82. sampler=DistributedSampler(train_ds) # NEW
  83. )
  84. test_loader = DataLoader(
  85. dataset=test_ds,
  86. batch_size=2,
  87. shuffle=False,
  88. )
  89. return train_loader, test_loader
  90. # NEW: wrapper
  91. def main(rank, world_size, num_epochs):
  92. ddp_setup(rank, world_size) # NEW: initialize process groups
  93. train_loader, test_loader = prepare_dataset()
  94. model = NeuralNetwork(num_inputs=2, num_outputs=2)
  95. model.to(rank)
  96. optimizer = torch.optim.SGD(model.parameters(), lr=0.5)
  97. model = DDP(model, device_ids=[rank]) # NEW: wrap model with DDP
  98. # the core model is now accessible as model.module
  99. for epoch in range(num_epochs):
  100. model.train()
  101. for features, labels in train_loader:
  102. features, labels = features.to(rank), labels.to(rank) # New: use rank
  103. logits = model(features)
  104. loss = F.cross_entropy(logits, labels) # Loss function
  105. optimizer.zero_grad()
  106. loss.backward()
  107. optimizer.step()
  108. # LOGGING
  109. print(f"[GPU{rank}] Epoch: {epoch+1:03d}/{num_epochs:03d}"
  110. f" | Batchsize {labels.shape[0]:03d}"
  111. f" | Train/Val Loss: {loss:.2f}")
  112. model.eval()
  113. train_acc = compute_accuracy(model, train_loader, device=rank)
  114. print(f"[GPU{rank}] Training accuracy", train_acc)
  115. test_acc = compute_accuracy(model, test_loader, device=rank)
  116. print(f"[GPU{rank}] Test accuracy", test_acc)
  117. destroy_process_group() # NEW: cleanly exit distributed mode
  118. def compute_accuracy(model, dataloader, device):
  119. model = model.eval()
  120. correct = 0.0
  121. total_examples = 0
  122. for idx, (features, labels) in enumerate(dataloader):
  123. features, labels = features.to(device), labels.to(device)
  124. with torch.no_grad():
  125. logits = model(features)
  126. predictions = torch.argmax(logits, dim=1)
  127. compare = labels == predictions
  128. correct += torch.sum(compare)
  129. total_examples += len(compare)
  130. return (correct / total_examples).item()
  131. if __name__ == "__main__":
  132. print("PyTorch version:", torch.__version__)
  133. print("CUDA available:", torch.cuda.is_available())
  134. print("Number of GPUs available:", torch.cuda.device_count())
  135. torch.manual_seed(123)
  136. # NEW: spawn new processes
  137. # note that spawn will automatically pass the rank
  138. num_epochs = 3
  139. world_size = torch.cuda.device_count()
  140. mp.spawn(main, args=(world_size, num_epochs), nprocs=world_size)
  141. # nprocs=world_size spawns one process per GPU