|
| 1 | +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from collections import OrderedDict |
| 15 | +from logging import INFO |
| 16 | + |
| 17 | +import torch |
| 18 | +import torch.nn as nn |
| 19 | +import torch.nn.functional as F |
| 20 | +from flwr.common.logger import log |
| 21 | +from torch.utils.data import DataLoader |
| 22 | +from torchvision.datasets import CIFAR10 |
| 23 | +from torchvision.transforms import Compose, Normalize, ToTensor |
| 24 | + |
| 25 | +DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") |
| 26 | + |
| 27 | + |
| 28 | +class Net(nn.Module): |
| 29 | + """Model (simple CNN adapted from 'PyTorch: A 60 Minute Blitz')""" |
| 30 | + |
| 31 | + def __init__(self) -> None: |
| 32 | + super(Net, self).__init__() |
| 33 | + self.conv1 = nn.Conv2d(3, 6, 5) |
| 34 | + self.pool = nn.MaxPool2d(2, 2) |
| 35 | + self.conv2 = nn.Conv2d(6, 16, 5) |
| 36 | + self.fc1 = nn.Linear(16 * 5 * 5, 120) |
| 37 | + self.fc2 = nn.Linear(120, 84) |
| 38 | + self.fc3 = nn.Linear(84, 10) |
| 39 | + |
| 40 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 41 | + x = self.pool(F.relu(self.conv1(x))) |
| 42 | + x = self.pool(F.relu(self.conv2(x))) |
| 43 | + x = x.view(-1, 16 * 5 * 5) |
| 44 | + x = F.relu(self.fc1(x)) |
| 45 | + x = F.relu(self.fc2(x)) |
| 46 | + return self.fc3(x) |
| 47 | + |
| 48 | + |
| 49 | +def load_data(): |
| 50 | + """Load CIFAR-10 (training and test set).""" |
| 51 | + trf = Compose([ToTensor(), Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) |
| 52 | + trainset = CIFAR10("./data", train=True, download=True, transform=trf) |
| 53 | + testset = CIFAR10("./data", train=False, download=True, transform=trf) |
| 54 | + return DataLoader(trainset, batch_size=32, shuffle=True), DataLoader(testset) |
| 55 | + |
| 56 | + |
| 57 | +def train(net, trainloader, valloader, epochs, device): |
| 58 | + """Train the model on the training set.""" |
| 59 | + log(INFO, "Starting training...") |
| 60 | + net.to(device) # move model to GPU if available |
| 61 | + criterion = torch.nn.CrossEntropyLoss().to(device) |
| 62 | + optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9) |
| 63 | + net.train() |
| 64 | + for _ in range(epochs): |
| 65 | + for images, labels in trainloader: |
| 66 | + images, labels = images.to(device), labels.to(device) |
| 67 | + optimizer.zero_grad() |
| 68 | + loss = criterion(net(images), labels) |
| 69 | + loss.backward() |
| 70 | + optimizer.step() |
| 71 | + |
| 72 | + train_loss, train_acc = test(net, trainloader) |
| 73 | + val_loss, val_acc = test(net, valloader) |
| 74 | + |
| 75 | + results = { |
| 76 | + "train_loss": train_loss, |
| 77 | + "train_accuracy": train_acc, |
| 78 | + "val_loss": val_loss, |
| 79 | + "val_accuracy": val_acc, |
| 80 | + } |
| 81 | + return results |
| 82 | + |
| 83 | + |
| 84 | +def test(net, testloader): |
| 85 | + """Validate the model on the test set.""" |
| 86 | + net.to(DEVICE) |
| 87 | + criterion = torch.nn.CrossEntropyLoss() |
| 88 | + correct, loss = 0, 0.0 |
| 89 | + with torch.no_grad(): |
| 90 | + for images, labels in testloader: |
| 91 | + outputs = net(images.to(DEVICE)) |
| 92 | + labels = labels.to(DEVICE) |
| 93 | + loss += criterion(outputs, labels).item() |
| 94 | + correct += (torch.max(outputs.data, 1)[1] == labels).sum().item() |
| 95 | + accuracy = correct / len(testloader.dataset) |
| 96 | + return loss, accuracy |
| 97 | + |
| 98 | + |
| 99 | +def get_weights(net): |
| 100 | + return [val.cpu().numpy() for _, val in net.state_dict().items()] |
| 101 | + |
| 102 | + |
| 103 | +def set_weights(net, parameters): |
| 104 | + params_dict = zip(net.state_dict().keys(), parameters) |
| 105 | + state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict}) |
| 106 | + net.load_state_dict(state_dict, strict=True) |
0 commit comments