|
| 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 | + |
| 15 | +import torch |
| 16 | +import torchvision |
| 17 | +import torchvision.transforms as transforms |
| 18 | +from lit_net import LitNet |
| 19 | +from pytorch_lightning import LightningDataModule, Trainer, seed_everything |
| 20 | +from torch.utils.data import DataLoader, random_split |
| 21 | + |
| 22 | +# (1) import nvflare lightning client API |
| 23 | +import nvflare.client.lightning as flare |
| 24 | + |
| 25 | +seed_everything(7) |
| 26 | + |
| 27 | + |
| 28 | +DATASET_PATH = "/tmp/nvflare/data" |
| 29 | +BATCH_SIZE = 4 |
| 30 | + |
| 31 | +transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) |
| 32 | + |
| 33 | + |
| 34 | +class CIFAR10DataModule(LightningDataModule): |
| 35 | + def __init__(self, data_dir: str = DATASET_PATH, batch_size: int = BATCH_SIZE): |
| 36 | + super().__init__() |
| 37 | + self.data_dir = data_dir |
| 38 | + self.batch_size = batch_size |
| 39 | + |
| 40 | + def prepare_data(self): |
| 41 | + torchvision.datasets.CIFAR10(root=self.data_dir, train=True, download=True, transform=transform) |
| 42 | + torchvision.datasets.CIFAR10(root=self.data_dir, train=False, download=True, transform=transform) |
| 43 | + |
| 44 | + def setup(self, stage: str): |
| 45 | + # Assign train/val datasets for use in dataloaders |
| 46 | + if stage == "fit" or stage == "validate": |
| 47 | + cifar_full = torchvision.datasets.CIFAR10( |
| 48 | + root=self.data_dir, train=True, download=False, transform=transform |
| 49 | + ) |
| 50 | + self.cifar_train, self.cifar_val = random_split(cifar_full, [0.8, 0.2]) |
| 51 | + |
| 52 | + # Assign test dataset for use in dataloader(s) |
| 53 | + if stage == "test" or stage == "predict": |
| 54 | + self.cifar_test = torchvision.datasets.CIFAR10( |
| 55 | + root=self.data_dir, train=False, download=False, transform=transform |
| 56 | + ) |
| 57 | + |
| 58 | + def train_dataloader(self): |
| 59 | + return DataLoader(self.cifar_train, batch_size=self.batch_size) |
| 60 | + |
| 61 | + def val_dataloader(self): |
| 62 | + return DataLoader(self.cifar_val, batch_size=self.batch_size) |
| 63 | + |
| 64 | + def test_dataloader(self): |
| 65 | + return DataLoader(self.cifar_test, batch_size=self.batch_size) |
| 66 | + |
| 67 | + def predict_dataloader(self): |
| 68 | + return DataLoader(self.cifar_test, batch_size=self.batch_size) |
| 69 | + |
| 70 | + |
| 71 | +def main(): |
| 72 | + model = LitNet() |
| 73 | + cifar10_dm = CIFAR10DataModule() |
| 74 | + trainer = Trainer(max_epochs=1, devices=1, accelerator="gpu" if torch.cuda.is_available() else "cpu") |
| 75 | + |
| 76 | + # (2) patch the lightning trainer |
| 77 | + flare.patch(trainer) |
| 78 | + |
| 79 | + while flare.is_running(): |
| 80 | + # (3) receives FLModel from NVFlare |
| 81 | + # Note that we don't need to pass this input_model to trainer |
| 82 | + # because after flare.patch the trainer.fit/validate will get the |
| 83 | + # global model internally |
| 84 | + input_model = flare.receive() |
| 85 | + print(f"\n[Current Round={input_model.current_round}, Site = {flare.get_site_name()}]\n") |
| 86 | + |
| 87 | + # (4) evaluate the current global model to allow server-side model selection |
| 88 | + print("--- validate global model ---") |
| 89 | + trainer.validate(model, datamodule=cifar10_dm) |
| 90 | + |
| 91 | + # perform local training starting with the received global model |
| 92 | + print("--- train new model ---") |
| 93 | + trainer.fit(model, datamodule=cifar10_dm) |
| 94 | + |
| 95 | + # test local model |
| 96 | + print("--- test new model ---") |
| 97 | + trainer.test(ckpt_path="best", datamodule=cifar10_dm) |
| 98 | + |
| 99 | + # get predictions |
| 100 | + print("--- prediction with new best model ---") |
| 101 | + trainer.predict(ckpt_path="best", datamodule=cifar10_dm) |
| 102 | + |
| 103 | + |
| 104 | +if __name__ == "__main__": |
| 105 | + main() |
0 commit comments