import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x)
def load_checkpoint(log_dir):
filepath = log_dir + '/checkpoint-{epoch}.pth.tar'.format(epoch=3)
return torch.load(filepath)
def test(log_dir):
device = torch.device('cuda')
loaded_model = Net().to(device)
checkpoint = load_checkpoint(log_dir)
loaded_model.load_state_dict(checkpoint['model'])
loaded_model.eval()
test_dataset = datasets.MNIST(
'data',
train=False,
download=True,
transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]))
data_loader = torch.utils.data.DataLoader(test_dataset)
test_loss = 0
for data, target in data_loader:
data, target = data.to(device), target.to(device)
output = loaded_model(data)
test_loss += F.nll_loss(output, target)
test_loss /= len(data_loader.dataset)
print("Average test loss: {}".format(test_loss.item()))
Distributed training on a PyTorch file
Distributed training on PyTorch is often done by creating a file (
train.py
) and using thetorchrun
CLI to run distributed training using that file. Databricks streamlines that process by allowing you to import a file (or even a repository) and use a Databricks notebook to start distributed training on that file using the TorchDistributor API. The example file that is used in this example is:/Workspace/Repos/user.name@databricks.com/.../Basic_MNIST/train.py
.This file is laid out similar to other solutions that use
torchrun
under the hood for distributed training.Requirements