Package: torchfl
Table of ContentsKey FeaturesInstallationExamples and UsageAvailable ModelsAvailable DatasetsContributingCitationFeaturesPython 3.6+ support. Built usingtorch-1.10.1,torchvision-0.11.2, andpytorch-lightning-1.5.7.Customizable implementations for state-of-the-art deep learningmodelswhich can be trained in federated or non-federated settings.Supports finetuning of the pre-trained deep learning models, allowing for faster training using transfer learning.PyTorch LightningDataModule wrappers for the most commonly useddatasetsto reduce the boilerplate code before experiments.Built using the bottom-up approach for the datamodules and models which ensures abstractions while allowing for customization.Provides implementation of the federated learning (FL) samplers, aggregators, and wrappers, to prototype FL experiments on-the-go.Backwards compatible with the PyTorch LightningDataModule, LightningModule, loggers, and DevOps tools.More details about the examples and usage can be foundbelow.For more documentation related to the usage, visit -https://torchfl.readthedocs.io/.InstallationStable ReleaseAs of now,torchflis available on PyPI and can be installed using the following command in your terminal:$ pip install torchflThis is the preferred method to installtorchflwith the most stable release.
If you don't havepipinstalled, thisPython installation guidecan guide you through the process.Examples and UsageAlthoughtorchflis primarily built for quick prototyping of federated learning experiments, the models, datasets, and abstractions can also speed up the non-federated learning experiments. In this section, we will explore examples and usages under both the settings.Non-Federated LearningThe following steps should be followed on a high-level to train a non-federated learning experiment. We are using theEMNIST (MNIST)dataset anddensenet121for this example.Import the relevant modules.fromtorchfl.datamodules.emnistimportEMNISTDataModulefromtorchfl.models.wrapper.emnistimportMNISTEMNISTimportpytorch_lightningasplfrompytorch_lightning.loggersimportTensorBoardLoggerfrompytorch_lightning.callbacksimport(ModelCheckpoint,LearningRateMonitor,DeviceStatsMonitor,ModelSummary,ProgressBar,...)For more details, view the full list of PyTorch Lightningcallbacksandloggerson the official website.Setup the PyTorch Lightning trainer.trainer=pl.Trainer(...logger=[TensorBoardLogger(name=experiment_name,save_dir=os.path.join(checkpoint_save_path,experiment_name),)],callbacks=[ModelCheckpoint(save_weights_only=True,mode="max",monitor="val_acc"),LearningRateMonitor("epoch"),DeviceStatsMonitor(),ModelSummary(),ProgressBar(),],...)More details about the PyTorch LightningTrainer APIcan be found on their official website.Prepare the dataset using the wrappers provided bytorchfl.datamodules.datamodule=EMNISTDataModule(dataset_name="mnist")datamodule.prepare_data()datamodule.setup()Initialize the model using the wrappers provided bytorchfl.models.wrappers.# check if the model can be loaded from a given checkpointif(checkpoint_load_path)andos.path.isfile(checkpoint_load_path):model=MNISTEMNIST("densenet121","adam",{"lr":0.001}).load_from_checkpoint(checkpoint_load_path)else:pl.seed_everything(42)model=MNISTEMNIST("densenet121","adam",{"lr":0.001})trainer.fit(model,datamodule.train_dataloader(),datamodule.val_dataloader())Collect the results.val_result=trainer.test(model,test_dataloaders=datamodule.val_dataloader(),verbose=True)test_result=trainer.test(model,test_dataloaders=datamodule.test_dataloader(),verbose=True)The corresponding files for the experiment (model checkpoints and logger metadata) will be stored atdefault_root_dirargument given to the PyTorch LightningTrainerobject in Step 2. For this experiment, we use theTensorboardlogger. To view the logs (and related plots and metrics), go to thedefault_root_dirpath and find the Tensorboard log files. Upload the files to the Tensorboard Development portal following the instructionshere. Once the log files are uploaded, a unique url to your experiment will be generated which can be shared with ease! An example can be foundhere.Note that,torchflis compatible with all the loggers supported by PyTorch Lightning. More information about the PyTorch Lightning loggers can be foundhere.For full non-federated learning example scripts, checkexamples/trainers.Federated LearningThe following steps should be followed on a high-level to train a federated learning experiment.Pick a dataset and use thedatamodulesto create federated data shards with iid or non-iid distribution.defget_datamodule()->EMNISTDataModule:datamodule:EMNISTDataModule=EMNISTDataModule(dataset_name=SUPPORTED_DATASETS_TYPE.MNIST,train_batch_size=10)datamodule.prepare_data()datamodule.setup()returndatamoduleagent_data_shard_map=get_agent_data_shard_map().federated_iid_dataloader(num_workers=fl_params.num_agents,workers_batch_size=fl_params.local_train_batch_size,)Use the TorchFLagentsmodule and themodelsmodule to initialize the global model, agents, and distribute their models.definitialize_agents(fl_params:FLParams,agent_data_shard_map:Dict[int,DataLoader])->List[V1Agent]:"""Initialize agents."""agents=[]foragent_idinrange(fl_params.num_agents):agent=V1Agent(id=agent_id,model=MNISTEMNIST(model_name=EMNIST_MODELS_ENUM.MOBILENETV3SMALL,optimizer_name=OPTIMIZERS_TYPE.ADAM,optimizer_hparams={"lr":0.001},model_hparams={"pre_trained":True,"feature_extract":True},fl_hparams=fl_params,),data_shard=agent_data_shard_map[agent_id],)agents.append(agent)returnagentsglobal_model=MNISTEMNIST(model_name=EMNIST_MODELS_ENUM.MOBILENETV3SMALL,optimizer_name=OPTIMIZERS_TYPE.ADAM,optimizer_hparams={"lr":0.001},model_hparams={"pre_trained":True,"feature_extract":True},fl_hparams=fl_params,)all_agents=initialize_agents(fl_params,agent_data_shard_map)Initiliaze anFLParamobject with the desired FL hyperparameters and pass it on to theEntrypointobject which will abstract the training.fl_params=FLParams(experiment_name="iid_mnist_fedavg_10_agents_5_sampled_50_epochs_mobilenetv3small_latest",num_agents=10,global_epochs=10,local_epochs=2,sampling_ratio=0.5,)entrypoint=Entrypoint(global_model=global_model,global_datamodule=get_agent_data_shard_map(),fl_hparams=fl_params,agents=all_agents,aggregator=FedAvgAggregator(all_agents=all_agents),sampler=RandomSampler(all_agents=all_agents),)entrypoint.run()For full federated learning example scripts, checkexamples/federated.Available ModelsFor the initial release,torchflwill only support state-of-the-art computer vision models. The following table summarizes the available models, support for pre-training, and the possibility of feature-extracting. Please note that the models have been tested with all the available datasets. Therefore, the link to the tests will be provided in the next section.NamePre-TrainingFeature ExtractionAlexNet:white_check_mark::white_check_mark:DenseNet121:white_check_mark::white_check_mark:DenseNet161:white_check_mark::white_check_mark:DenseNet169:white_check_mark::white_check_mark:DenseNet201:white_check_mark::white_check_mark:LeNet:x::x:MLP:x::x:MobileNetV2:white_check_mark::white_check_mark:MobileNetV3Small:white_check_mark::white_check_mark:MobileNetV3Large:white_check_mark::white_check_mark:ResNet18:white_check_mark::white_check_mark:ResNet34:white_check_mark::white_check_mark:ResNet50:white_check_mark::white_check_mark:ResNet101:white_check_mark::white_check_mark:ResNet152:white_check_mark::white_check_mark:ResNext50(32x4d):white_check_mark::white_check_mark:ResNext101(32x8d):white_check_mark::white_check_mark:WideResNet(50x2):white_check_mark::white_check_mark:WideResNet(101x2):white_check_mark::white_check_mark:ShuffleNetv2(x0.5):white_check_mark::white_check_mark:ShuffleNetv2(x1.0):white_check_mark::white_check_mark:ShuffleNetv2(x1.5):x::x:ShuffleNetv2(x2.0):x::x:SqueezeNet1.0:white_check_mark::white_check_mark:SqueezeNet1.1:white_check_mark::white_check_mark:VGG11:white_check_mark::white_check_mark:VGG11_BatchNorm:white_check_mark::white_check_mark:VGG13:white_check_mark::white_check_mark:VGG13_BatchNorm:white_check_mark::white_check_mark:VGG16:white_check_mark::white_check_mark:VGG16_BatchNorm:white_check_mark::white_check_mark:VGG19:white_check_mark::white_check_mark:VGG19_BatchNorm:white_check_mark::white_check_mark:Available DatasetsFollowing datasets have been wrapped inside aLightningDataModuleand made available for the initial release oftorchfl. To add a new dataset, check the source code intorchfl.datamodules, add tests, and create a PR withFeaturestag.GroupDatasetsIID SplitNon-IID SplitDatamodules TestsModelsModels TestsCIFARCIFAR10CIFAR100:white_check_mark::white_check_mark:CIFAR10CIFAR100EMNISTBy ClassBy MergeBalancedDigitsLettersMNIST:white_check_mark::white_check_mark:By ClassBy MergeBalancedDigitsLettersMNISTFashionMNISTFashionMNIST:white_check_mark::white_check_mark:FashionMNISTContributingContributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.You can contribute in many ways:Types of ContributionsReport BugsReport bugs athttps://github.com/vivekkhimani/torchfl/issues.If you are reporting a bug, please include:Your operating system name and version.Any details about your local setup that might be helpful in troubleshooting.Detailed steps to reproduce the bug.Fix BugsLook through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it.Implement FeaturesLook through the GitHub issues for features. Anything tagged with "enhancement", "help wanted", "feature" is open to whoever wants to implement it.Write Documentationtorchflcould always use more documentation, whether as part of the official torchfl docs, in docstrings, or even on the web in blog posts, articles, and such.Submit FeedbackThe best way to send feedback is to file an issue athttps://github.com/vivekkhimani/torchfl/issues.
If you are proposing a feature:Explain in detail how it would work.Keep the scope as narrow as possible, to make it easier to implement.Remember that this is a volunteer-driven project, and that contributions are welcome :)Get StartedReady to contribute? Here's how to set up torchfl for local development.Fork the torchfl repo on GitHub.Clone your fork locally:$ git clone git@github.com:<your_username_here>/torchfl.gitInstall your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:$ mkvirtualenv torchfl
$ cd torchfl/
$ python setup.py developCreate a branch for local development:$ git checkout -b name-of-your-bugfix-or-featureNow you can make your changes locally and maintain them on your own branch.When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:toxRuntox --helpto explore more features for tox.Your changes need to pass the existing test cases and add the new ones if required under thetestsdirectory. Following approaches can be used to run the test cases.To run all the test cases.$ coverage run -m pytest testsTo run a specific file containing the test cases.$ coverage run -m pytest <path-to-the-file>Commit your changes and push your branch to GitHub:$ git add --all
$ git commit -m "Your detailed description of your changes."
$ git push origin <name-of-your-bugfix-or-feature>Submit a pull request through the Github web interface.Once the pull request has been submitted, the continuous integration pipelines on Github Actions will be triggered. Ensure that all of them pass before one of the maintainers can review the request.Pull Request GuidelinesBefore you submit a pull request, check that it meets these guidelines:The pull request should include tests.Try adding new test cases for new features or enhancements and make changes to the CI pipelines accordingly.Modify the existing tests (if required) for the bug fixes.If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list inREADME.md.The pull request should pass all the existing CI pipelines (Github Actions) and the new/modified workflows should be added as required.Please note that the test cases should only be run in the CI pipeline if the direct/indirect dependencies of the tests have changed. Look at theworkflow YAML filesfor more details or reach out to one of the contributors.DeployingA reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:$ bump2version patch # possible: major / minor / patch
$ git push
$ git push --tagsCitationPlease cite the following article if you end up using this software:@misc{https://doi.org/10.48550/arxiv.2211.00735,
  doi = {10.48550/ARXIV.2211.00735},
  url = {https://arxiv.org/abs/2211.00735},
  author = {Khimani, Vivek and Jabbari, Shahin},
  keywords = {Machine Learning (cs.LG), Distributed, Parallel, and Cluster Computing (cs.DC), Systems and Control (eess.SY), FOS: Computer and information sciences, FOS: Computer and information sciences, FOS: Electrical engineering, electronic engineering, information engineering, FOS: Electrical engineering, electronic engineering, information engineering, I.2.11},
  title = {TorchFL: A Performant Library for Bootstrapping Federated Learning Experiments},
  publisher = {arXiv},
  year = {2022},
  copyright = {Creative Commons Attribution Non Commercial Share Alike 4.0 International}
}