diff --git a/baselines/fedpara/EXTENDED_README.md b/baselines/fedpara/EXTENDED_README.md new file mode 100644 index 000000000000..9c8f5bc72fa9 --- /dev/null +++ b/baselines/fedpara/EXTENDED_README.md @@ -0,0 +1,123 @@ + +# Extended Readme + +> The baselines are expected to run in a machine running Ubuntu 22.04 + +While `README.md` should include information about the baseline you implement and how to run it, this _extended_ readme provides info on what's the expected directory structure for a new baseline and more generally the instructions to follow before your baseline can be merged into the Flower repository. Please follow closely these instructions. It is likely that you have already completed steps 1-2. + +1. Fork the Flower repository and clone it. +2. Navigate to the `baselines/` directory and from there run: + ```bash + # This will create a new directory with the same structure as this `baseline_template` directory. + ./dev/create-baseline.sh + ``` +3. All your code and configs should go into a sub-directory with the same name as the name of your baseline. + * The sub-directory contains a series of Python scripts that you can edit. Please stick to these files and consult with us if you need additional ones. + * There is also a basic config structure in `/conf` ready be parsed by [Hydra](https://hydra.cc/) when executing your `main.py`. +4. Therefore, the directory structure in your baseline should look like: + ```bash + baselines/ + ├── README.md # describes your baseline and everything needed to use it + ├── EXTENDED_README.md # to remove before creating your PR + ├── pyproject.toml # details your Python environment + └── + ├── *.py # several .py files including main.py and __init__.py + └── conf + └── *.yaml # one or more Hydra config files + + ``` +> :warning: Make sure the variable `name` in `pyproject.toml` is set to the name of the sub-directory containing all your code. + +5. Add your dependencies to the `pyproject.toml` (see below a few examples on how to do it). Read more about Poetry below in this `EXTENDED_README.md`. +6. Regularly check that your coding style and the documentation you add follow good coding practices. To test whether your code meets the requirements, please run the following: + ```bash + # After activating your environment and from your baseline's directory + cd .. # to go to the top-level directory of all baselines + ./dev/test-baseline.sh + ./dev/test-baseline-structure.sh + ``` + Both `test-baseline.sh` and `test-baseline-structure.sh` will also be automatically run when you create a PR, and both tests need to pass for the baseline to be merged. + To automatically solve some formatting issues and apply easy fixes, please run the formatting script: + ```bash + # After activating your environment and from your baseline's directory + cd .. # to go to the top-level directory of all baselines + ./dev/format-baseline.sh + ``` +7. Ensure that the Python environment for your baseline can be created without errors by simply running `poetry install` and that this is properly described later when you complete the `Environment Setup` section in `README.md`. This is specially important if your environment requires additional steps after doing `poetry install`. +8. Ensure that your baseline runs with default arguments by running `poetry run python -m .main`. Then, describe this and other forms of running your code in the `Running the Experiments` section in `README.md`. +9. Once your code is ready and you have checked: + * that following the instructions in your `README.md` the Python environment can be created correctly + + * that running the code following your instructions can reproduce the experiments in the paper + + , then you just need to create a Pull Request (PR) to kickstart the process of merging your baseline into the Flower repository. + +> Once you are happy to merge your baseline contribution, please delete this `EXTENDED_README.md` file. + + +## About Poetry + +We use Poetry to manage the Python environment for each individual baseline. You can follow the instructions [here](https://python-poetry.org/docs/) to install Poetry in your machine. + + +### Specifying a Python Version (optional) +By default, Poetry will use the Python version in your system. In some settings, you might want to specify a particular version of Python to use inside your Poetry environment. You can do so with [`pyenv`](https://github.com/pyenv/pyenv). Check the documentation for the different ways of installing `pyenv`, but one easy way is using the [automatic installer](https://github.com/pyenv/pyenv-installer): +```bash +curl https://pyenv.run | bash # then, don't forget links to your .bashrc/.zshrc +``` + +You can then install any Python version with `pyenv install ` (e.g. `pyenv install 3.9.17`). Then, in order to use that version for your baseline, you'd do the following: + +```bash +# cd to your baseline directory (i.e. where the `pyproject.toml` is) +pyenv local + +# set that version for poetry +poetry env use + +# then you can install your Poetry environment (see the next setp) +``` + +### Installing Your Environment +With the Poetry tool already installed, you can create an environment for this baseline with commands: +```bash +# run this from the same directory as the `pyproject.toml` file is +poetry install +``` + +This will create a basic Python environment with just Flower and additional packages, including those needed for simulation. Next, you should add the dependencies for your code. It is **critical** that you fix the version of the packages you use using a `=` not a `=^`. You can do so via [`poetry add`](https://python-poetry.org/docs/cli/#add). Below are some examples: + +```bash +# For instance, if you want to install tqdm +poetry add tqdm==4.65.0 + +# If you already have a requirements.txt, you can add all those packages (but ensure you have fixed the version) in one go as follows: +poetry add $( cat requirements.txt ) +``` +With each `poetry add` command, the `pyproject.toml` gets automatically updated so you don't need to keep that `requirements.txt` as part of this baseline. + + +More critically however, is adding your ML framework of choice to the list of dependencies. For some frameworks you might be able to do so with the `poetry add` command. Check [the Poetry documentation](https://python-poetry.org/docs/cli/#add) for how to add packages in various ways. For instance, let's say you want to use PyTorch: + +```bash +# with plain `pip` you'd run a command such as: +pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu117 + +# to add the same 3 dependencies to your Poetry environment you'd need to add the URL to the wheel that the above pip command auto-resolves for you. +# You can find those wheels in `https://download.pytorch.org/whl/cu117`. Copy the link and paste it after the `poetry add` command. +# For instance to add `torch==1.13.1+cu117` and a x86 Linux system with Python3.8 you'd: +poetry add https://download.pytorch.org/whl/cu117/torch-1.13.1%2Bcu117-cp38-cp38-linux_x86_64.whl +# you'll need to repeat this for both `torchvision` and `torchaudio` +``` +The above is just an example of how you can add these dependencies. Please refer to the Poetry documentation to extra reference. + +If all attempts fail, you can still install packages via standard `pip`. You'd first need to source/activate your Poetry environment. +```bash +# first ensure you have created your environment +# and installed the base packages provided in the template +poetry install + +# then activate it +poetry shell +``` +Now you are inside your environment (pretty much as when you use `virtualenv` or `conda`) so you can install further packages with `pip`. Please note that, unlike with `poetry add`, these extra requirements won't be captured by `pyproject.toml`. Therefore, please ensure that you provide all instructions needed to: (1) create the base environment with Poetry and (2) install any additional dependencies via `pip` when you complete your `README.md`. \ No newline at end of file diff --git a/baselines/fedpara/LICENSE b/baselines/fedpara/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/baselines/fedpara/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/baselines/fedpara/README.md b/baselines/fedpara/README.md new file mode 100644 index 000000000000..682952717426 --- /dev/null +++ b/baselines/fedpara/README.md @@ -0,0 +1,87 @@ +--- +title: title of the paper +url: URL to the paper page (not the pdf) +labels: [label1, label2] # please add between 4 and 10 single-word (maybe two-words) labels (e.g. "system heterogeneity", "image classification", "asynchronous", "weight sharing", "cross-silo") +dataset: [dataset1, dataset2] # list of datasets you include in your baseline +--- + +# :warning:*_Title of your baseline_* + +> Note: If you use this baseline in your work, please remember to cite the original authors of the paper as well as the Flower paper. + +> :warning: This is the template to follow when creating a new Flower Baseline. Please follow the instructions in `EXTENDED_README.md` + +> :warning: Please follow the instructions carefully. You can see the [FedProx-MNIST baseline](https://github.com/adap/flower/tree/main/baselines/fedprox) as an example of a baseline that followed this guide. + +> :warning: Please complete the metadata section at the very top of this README. This generates a table at the top of the file that will facilitate indexing baselines. + +****Paper:**** :warning: *_add the URL of the paper page (not to the .pdf). For instance if you link a paper on ArXiv, add here the URL to the abstract page (e.g. https://arxiv.org/abs/1512.03385). If your paper is in from a journal or conference proceedings, please follow the same logic._* + +****Authors:**** :warning: *_list authors of the paper_* + +****Abstract:**** :warning: *_add here the abstract of the paper you are implementing_* + + +## About this baseline + +****What’s implemented:**** :warning: *_Concisely describe what experiment(s) in the publication can be replicated by running the code. Please only use a few sentences. Start with: “The code in this directory …”_* + +****Datasets:**** :warning: *_List the datasets you used (if you used a medium to large dataset, >10GB please also include the sizes of the dataset)._* + +****Hardware Setup:**** :warning: *_Give some details about the hardware (e.g. a server with 8x V100 32GB and 256GB of RAM) you used to run the experiments for this baseline. Someone out there might not have access to the same resources you have so, could list the absolute minimum hardware needed to run the experiment in a reasonable amount of time ? (e.g. minimum is 1x 16GB GPU otherwise a client model can’t be trained with a sufficiently large batch size). Could you test this works too?_* + +****Contributors:**** :warning: *_let the world know who contributed to this baseline. This could be either your name, your name and affiliation at the time, or your GitHub profile name if you prefer. If multiple contributors signed up for this baseline, please list yourself and your colleagues_* + + +## Experimental Setup + +****Task:**** :warning: *_what’s the primary task that is being federated? (e.g. image classification, next-word prediction). If you have experiments for several, please list them_* + +****Model:**** :warning: *_provide details about the model you used in your experiments (if more than use a list). If your model is small, describing it as a table would be :100:. Some FL methods do not use an off-the-shelve model (e.g. ResNet18) instead they create your own. If this is your case, please provide a summary here and give pointers to where in the paper (e.g. Appendix B.4) is detailed._* + +****Dataset:**** :warning: *_Earlier you listed already the datasets that your baseline uses. Now you should include a breakdown of the details about each of them. Please include information about: how the dataset is partitioned (e.g. LDA with alpha 0.1 as default and all clients have the same number of training examples; or each client gets assigned a different number of samples following a power-law distribution with each client only instances of 2 classes)? if your dataset is naturally partitioned just state “naturally partitioned”; how many partitions there are (i.e. how many clients)? Please include this an all information relevant about the dataset and its partitioning into a table._* + +****Training Hyperparameters:**** :warning: *_Include a table with all the main hyperparameters in your baseline. Please show them with their default value._* + + +## Environment Setup + +:warning: _The Python environment for all baselines should follow these guidelines in the `EXTENDED_README`. Specify the steps to create and activate your environment. If there are any external system-wide requirements, please include instructions for them too. These instructions should be comprehensive enough so anyone can run them (if non standard, describe them step-by-step)._ + + +## Running the Experiments + +:warning: _Provide instructions on the steps to follow to run all the experiments._ +```bash +# The main experiment implemented in your baseline using default hyperparameters (that should be setup in the Hydra configs) should run (including dataset download and necessary partitioning) by executing the command: + +poetry run python -m .main # where is the name of this directory and that of the only sub-directory in this directory (i.e. where all your source code is) + +# If you are using a dataset that requires a complicated download (i.e. not using one natively supported by TF/PyTorch) + preprocessing logic, you might want to tell people to run one script first that will do all that. Please ensure the download + preprocessing can be configured to suit (at least!) a different download directory (and use as default the current directory). The expected command to run to do this is: + +poetry run python -m .dataset_preparation + +# It is expected that you baseline supports more than one dataset and different FL settings (e.g. different number of clients, dataset partitioning methods, etc). Please provide a list of commands showing how these experiments are run. Include also a short explanation of what each one does. Here it is expected you'll be using the Hydra syntax to override the default config. + +poetry run python -m .main +. +. +. +poetry run python -m .main +``` + + +## Expected Results + +:warning: _Your baseline implementation should replicate several of the experiments in the original paper. Please include here the exact command(s) needed to run each of those experiments followed by a figure (e.g. a line plot) or table showing the results you obtained when you ran the code. Below is an example of how you can present this. Please add command followed by results for all your experiments._ + +```bash +# it is likely that for one experiment you need to sweep over different hyperparameters. You are encouraged to use Hydra's multirun functionality for this. This is an example of how you could achieve this for some typical FL hyperparameteres + +poetry run python -m .main --multirun num_client_per_round=5,10,50 dataset=femnist,cifar10 +# the above command will run a total of 6 individual experiments (because 3client_configs x 2datasets = 6 -- you can think of it as a grid). + +[Now show a figure/table displaying the results of the above command] + +# add more commands + plots for additional experiments. +``` diff --git a/baselines/fedpara/fedpara/__init__.py b/baselines/fedpara/fedpara/__init__.py new file mode 100644 index 000000000000..a5e567b59135 --- /dev/null +++ b/baselines/fedpara/fedpara/__init__.py @@ -0,0 +1 @@ +"""Template baseline package.""" diff --git a/baselines/fedpara/fedpara/client.py b/baselines/fedpara/fedpara/client.py new file mode 100644 index 000000000000..408ac2bc52ab --- /dev/null +++ b/baselines/fedpara/fedpara/client.py @@ -0,0 +1,87 @@ +"""Client for FedPara.""" + +import copy +from collections import OrderedDict +from typing import Callable, Dict, List, Tuple + +import flwr as fl +import torch +from flwr.common import NDArrays, Scalar +from hydra.utils import instantiate +from omegaconf import DictConfig +from torch.nn.utils import parameters_to_vector +from torch.utils.data import DataLoader + +from fedpara.models import train + + +class FlowerClient(fl.client.NumPyClient): + """Standard Flower client for CNN training.""" + + def __init__( + self, + cid: int, + net: torch.nn.Module, + train_loader: DataLoader, + device: str, + num_epochs: int, + ): # pylint: disable=too-many-arguments + print(f"Initializing Client {cid}") + self.cid = cid + self.net = net + self.train_loader = train_loader + self.device = torch.device(device) + self.num_epochs = num_epochs + + def get_parameters(self, config: Dict[str, Scalar]) -> NDArrays: + """Returns the parameters of the current net.""" + return [val.cpu().numpy() for _, val in self.net.state_dict().items()] + + def _set_parameters(self, parameters: NDArrays) -> None: + params_dict = zip(self.net.state_dict().keys(), parameters) + state_dict = OrderedDict({k: torch.Tensor(v) for k, v in params_dict}) + self.net.load_state_dict(state_dict, strict=True) + + def fit( + self, parameters: NDArrays, config: Dict[str, Scalar] + ) -> Tuple[NDArrays, int, Dict]: + """Train the network on the training set.""" + self._set_parameters(parameters) + print(f"Client {self.cid} Training...") + + train( + self.net, + self.train_loader, + self.device, + epochs=self.num_epochs, + hyperparams=config, + round=config["curr_round"], + ) + + return ( + self.get_parameters({}), + len(self.train_loader), + {}, + ) + + +def gen_client_fn( + train_loaders: List[DataLoader], + model: DictConfig, + num_epochs: int, + args: Dict, +) -> Callable[[str], FlowerClient]: + """Return a function which creates a new FlowerClient for a given cid.""" + + def client_fn(cid: str) -> FlowerClient: + """Create a new FlowerClient for a given cid.""" + cid = int(cid) + return FlowerClient( + cid=cid, + net=instantiate(model).to(args["device"]), + train_loader=train_loaders[cid], + device=args["device"], + num_epochs=num_epochs, + ) + + return client_fn diff --git a/baselines/fedpara/fedpara/conf/base.yaml b/baselines/fedpara/fedpara/conf/base.yaml new file mode 100644 index 000000000000..12aaebf68483 --- /dev/null +++ b/baselines/fedpara/fedpara/conf/base.yaml @@ -0,0 +1,44 @@ +--- +seed: 17 + +num_clients: 100 +num_rounds: 200 +clients_per_round: 16 +num_epochs: 5 +batch_size: 64 + +server_device: cuda +client_device: cuda + +client_resources: + num_cpus: 2 + num_gpus: 0.25 + +dataset_config: + name: CIFAR10 + partition: non-iid + num_classes: 10 + alpha: 0.5 + +model: + _target_: fedpara.models.VGG + num_classes: ${dataset_config.num_classes} + conv_type: lowrank # lowrank or standard + activation: relu # relu or leaky_relu + +hyperparams: + eta_l: 0.1 + learning_decay: 0.992 + momentum: 0.0 + weight_decay: 0 + +strategy: + _target_: fedpara.strategy.FedPara + algorithm: FedPara + fraction_fit: 0.00001 + fraction_evaluate: 0.0 + min_evaluate_clients: 0 + min_fit_clients: ${clients_per_round} + min_available_clients: ${clients_per_round} + accept_failures: false + diff --git a/baselines/fedpara/fedpara/conf/cifar10.yaml b/baselines/fedpara/fedpara/conf/cifar10.yaml new file mode 100644 index 000000000000..3dabc0f07ed1 --- /dev/null +++ b/baselines/fedpara/fedpara/conf/cifar10.yaml @@ -0,0 +1,45 @@ +--- +seed: 17 + +num_clients: 100 +num_rounds: 200 +clients_per_round: 16 +num_epochs: 5 +batch_size: 64 + +server_device: cuda +client_device: cuda + +client_resources: + num_cpus: 2 + num_gpus: 0.0625 + +dataset_config: + name: CIFAR10 + partition: non-iid + num_classes: 10 + alpha: 0.5 + +model: + _target_: fedpara.models.VGG + num_classes: ${dataset_config.num_classes} + conv_type: lowrank # lowrank or standard + activation: relu # relu or leaky_relu + ratio: 0.1 # lowrank ratio + +hyperparams: + eta_l: 0.1 + learning_decay: 0.992 + momentum: 0.0 + weight_decay: 0 + +strategy: + _target_: fedpara.strategy.FedPara + algorithm: FedPara + fraction_fit: 0.00001 + fraction_evaluate: 0.0 + min_evaluate_clients: 0 + min_fit_clients: ${clients_per_round} + min_available_clients: ${clients_per_round} + accept_failures: false + diff --git a/baselines/fedpara/fedpara/conf/cifar100.yaml b/baselines/fedpara/fedpara/conf/cifar100.yaml new file mode 100644 index 000000000000..b30a93f3a8c9 --- /dev/null +++ b/baselines/fedpara/fedpara/conf/cifar100.yaml @@ -0,0 +1,46 @@ +--- +seed: 34213 + +num_clients: 50 +num_rounds: 400 +clients_per_round: 8 +num_epochs: 5 +batch_size: 64 + +server_device: cuda +client_device: cuda + +client_resources: + num_cpus: 2 + num_gpus: 0.125 + +dataset_config: + name: CIFAR100 + partition: -iid + num_classes: 100 + alpha: 0.5 + + +model: + _target_: fedpara.models.VGG + num_classes: ${dataset_config.num_classes} + conv_type: lowrank # lowrank or standard + activation: relu # relu or leaky_relu + ratio: 0.4 # lowrank ratio + +hyperparams: + eta_l: 0.1 + learning_decay: 0.992 + momentum: 0.0 + weight_decay: 0 + +strategy: + _target_: fedpara.strategy.FedPara + algorithm: FedPara + fraction_fit: 0.00001 + fraction_evaluate: 0.0 + min_evaluate_clients: 0 + min_fit_clients: ${clients_per_round} + min_available_clients: ${clients_per_round} + accept_failures: false + diff --git a/baselines/fedpara/fedpara/conf/femnist.yaml b/baselines/fedpara/fedpara/conf/femnist.yaml new file mode 100644 index 000000000000..5ce343368b5b --- /dev/null +++ b/baselines/fedpara/fedpara/conf/femnist.yaml @@ -0,0 +1,45 @@ +--- +seed: 17 + +num_clients: 100 +num_rounds: 100 +clients_per_round: 10 +num_epochs: 5 +batch_size: 10 + +server_device: cuda +client_device: cuda + +client_resources: + num_cpus: 2 + num_gpus: 0.0625 + +dataset_config: + name: FEMNIST + partition: non-iid #redundent + num_classes: 62 + alpha: 0 # redundant + +model: + _target_: fedpara.models.VGG + num_classes: ${dataset_config.num_classes} + conv_type: lowrank # lowrank or standard + activation: relu # relu or leaky_relu + ratio: 0.1 # lowrank ratio + +hyperparams: + eta_l: 0.1 + learning_decay: 0.999 + momentum: 0.0 + weight_decay: 0 + +strategy: + _target_: fedpara.strategy.FedPara + algorithm: FedPara + fraction_fit: 0.00001 + fraction_evaluate: 0.0 + min_evaluate_clients: 0 + min_fit_clients: ${clients_per_round} + min_available_clients: ${clients_per_round} + accept_failures: false + diff --git a/baselines/fedpara/fedpara/dataset.py b/baselines/fedpara/fedpara/dataset.py new file mode 100644 index 000000000000..2ff2f28a30c1 --- /dev/null +++ b/baselines/fedpara/fedpara/dataset.py @@ -0,0 +1,132 @@ +"""Dataset loading and processing utilities.""" + +import pickle +from typing import List, Tuple +import random +import numpy as np +from collections import defaultdict +import torch +from torch.utils.data import DataLoader, Dataset +from torchvision import datasets, transforms +import omegaconf + +class DatasetSplit(Dataset): + def __init__(self, dataset, idxs): + self.dataset = dataset + self.targets = dataset.targets + self.idxs = list(idxs) + + def __len__(self): + return len(self.idxs) + + def __getitem__(self, item): + image, label = self.dataset[self.idxs[item]] + return image, label + +def iid(dataset, num_users): + """ + Sample I.I.D. client data from CIFAR dataset + :param dataset: + :param num_users: + :return: dict of image index + """ + num_items = int(len(dataset)/num_users) + dict_users, all_idxs = {}, [i for i in range(len(dataset))] + for i in range(num_users): + dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False)) + all_idxs = list(set(all_idxs) - dict_users[i]) + return dict_users + + +def noniid(dataset, no_participants, alpha=0.5): + """ + Input: Number of participants and alpha (param for distribution) + Output: A list of indices denoting data in CIFAR training set. + Requires: cifar_classes, a preprocessed class-indice dictionary. + Sample Method: take a uniformly sampled 10/100-dimension vector as parameters for + dirichlet distribution to sample number of images in each class. + """ + np.random.seed(666) + random.seed(666) + cifar_classes = {} + for ind, x in enumerate(dataset): + _, label = x + if label in cifar_classes: + cifar_classes[label].append(ind) + else: + cifar_classes[label] = [ind] + + per_participant_list = defaultdict(list) + no_classes = len(cifar_classes.keys()) + class_size = len(cifar_classes[0]) + datasize = {} + for n in range(no_classes): + random.shuffle(cifar_classes[n]) + sampled_probabilities = class_size * np.random.dirichlet( + np.array(no_participants * [alpha])) + for user in range(no_participants): + no_imgs = int(round(sampled_probabilities[user])) + datasize[user, n] = no_imgs + sampled_list = cifar_classes[n][:min(len(cifar_classes[n]), no_imgs)] + per_participant_list[user].extend(sampled_list) + cifar_classes[n] = cifar_classes[n][min(len(cifar_classes[n]), no_imgs):] + train_img_size = np.zeros(no_participants) + for i in range(no_participants): + train_img_size[i] = sum([datasize[i,j] for j in range(no_classes)]) + clas_weight = np.zeros((no_participants,no_classes)) + for i in range(no_participants): + for j in range(no_classes): + clas_weight[i,j] = float(datasize[i,j])/float((train_img_size[i])) + return per_participant_list, clas_weight + + +def load_datasets( + config, num_clients, batch_size +) -> Tuple[List[DataLoader], DataLoader]: + + """Load the dataset and return the dataloaders for the clients and the server.""" + print("Loading data...") + if config.name == "CIFAR10": + Dataset = datasets.CIFAR10 + elif config.name == "CIFAR100": + Dataset = datasets.CIFAR100 + else: + raise NotImplementedError + data_directory = f"./data/{config.name.lower()}/" + ds_path = f"{data_directory}train_{num_clients}_{config.alpha:.2f}.pkl" + transform_train = transforms.Compose([ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ]) + transform_test = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ]) + try: + with open(ds_path, "rb") as file: + train_datasets = pickle.load(file) + except FileNotFoundError: + dataset_train = Dataset( + data_directory, train=True, download=True, transform=transform_train) + if config.partition == "iid": + train_datasets = iid( + dataset_train, + num_clients) + else: + train_datasets, _ = noniid( + dataset_train, + num_clients, + config.alpha) + dataset_test = Dataset( + data_directory, train=False, download=True, transform=transform_test + ) + test_loader = DataLoader(dataset_test, batch_size=batch_size, num_workers=2) + train_loaders = [ + DataLoader(DatasetSplit(dataset_train, ids), batch_size=batch_size, shuffle=True, num_workers=2) + for ids in train_datasets.values() + ] + + return train_loaders, test_loader + diff --git a/baselines/fedpara/fedpara/main.py b/baselines/fedpara/fedpara/main.py new file mode 100644 index 000000000000..a4045a82f413 --- /dev/null +++ b/baselines/fedpara/fedpara/main.py @@ -0,0 +1,115 @@ +"""Main script for running FedPara.""" +from comet_ml import Experiment +import flwr as fl +import hydra +import numpy as np +from hydra.core.hydra_config import HydraConfig +from hydra.utils import instantiate +from omegaconf import DictConfig, OmegaConf +from fedpara import client, server, utils +from fedpara.dataset import load_datasets +from fedpara.utils import get_parameters, seed_everything + +@hydra.main(config_path="conf", config_name="cifar10", version_base=None) +def main(cfg: DictConfig) -> None: + """Run the baseline. + + Parameters + ---------- + cfg : DictConfig + An omegaconf object that stores the hydra config. + """ + # 1. Print parsed config + print(OmegaConf.to_yaml(cfg)) + seed_everything(cfg.seed) + # # Comet ML tracking + credentials = OmegaConf.load("fedpara/conf/credentials.yaml") + experiment = Experiment( + api_key=credentials.api_key, + project_name=credentials.project_name, + workspace=credentials.workspace, + ) + experiment.set_name(f"flower | {cfg.strategy.algorithm} | {cfg.dataset_config.name} | Seed {cfg.seed}") + hyper_params = { + "dataset": cfg.dataset_config.name, + "seed": cfg.seed, + } + # experiment.log_parameters(hyper_params) + # 2. Prepare dataset + train_loaders, test_loader = load_datasets( + config=cfg.dataset_config, + num_clients=cfg.num_clients, + batch_size=cfg.batch_size, + ) + + # 3. Define clients + client_fn = client.gen_client_fn( + train_loaders=train_loaders, + model=cfg.model, + num_epochs=cfg.num_epochs, + args={"device": cfg.client_device}, + ) + + evaluate_fn = server.gen_evaluate_fn( + test_loader=test_loader, + model=cfg.model, + device=cfg.server_device, + experiment=experiment, + ) + + def get_on_fit_config(): + def fit_config_fn(server_round: int): + fit_config = OmegaConf.to_container(cfg.hyperparams, resolve=True) + fit_config["curr_round"] = server_round + return fit_config + + return fit_config_fn + + net_glob = instantiate(cfg.model) + + # 4. Define strategy + strategy = instantiate( + cfg.strategy, + evaluate_fn=evaluate_fn, + on_fit_config_fn=get_on_fit_config(), + initial_parameters=fl.common.ndarrays_to_parameters(get_parameters(net_glob)), + ) + + # 5. Start Simulation + history = fl.simulation.start_simulation( + client_fn=client_fn, + num_clients=cfg.num_clients, + config=fl.server.ServerConfig(num_rounds=cfg.num_rounds), + strategy=strategy, + client_resources={ + "num_cpus": cfg.client_resources.num_cpus, + "num_gpus": cfg.client_resources.num_gpus, + }, + ray_init_args={ + "num_cpus": 40, + "num_gpus": 1, + "_memory": 30 * 1024 * 1024 * 1024, + }, + ) + + # 6. Save results + save_path = HydraConfig.get().runtime.output_dir + file_suffix = "_".join( + [ + repr(strategy), + cfg.dataset_config.name, + f"{cfg.seed}", + f"{cfg.dataset_config.alpha}", + f"{cfg.num_clients}", + f"{cfg.num_rounds}", + f"{cfg.clients_per_round}", + ] + ) + + utils.plot_metric_from_history( + hist=history, save_plot_path=save_path, suffix=file_suffix, cfg=cfg + ) + + +if __name__ == "__main__": + main() diff --git a/baselines/fedpara/fedpara/models.py b/baselines/fedpara/fedpara/models.py new file mode 100644 index 000000000000..b7df4295aba1 --- /dev/null +++ b/baselines/fedpara/fedpara/models.py @@ -0,0 +1,308 @@ +"""Model definitions for FedPara.""" + +from typing import Dict, Tuple +from torch.nn import init +import torch +import torch.nn.functional as F +from flwr.common import Scalar +from torch import nn +from torch.nn.utils import parameters_to_vector +from torch.utils.data import DataLoader +from torchvision import transforms +from tqdm import tqdm +import torchvision.models as models +import numpy as np +import math + +class LowRank(nn.Module): + def __init__(self, + in_channels: int, + out_channels: int, + low_rank: int, + kernel_size: int + ,activation: str = 'relu'): + super().__init__() + self.T = nn.Parameter( + torch.empty(size=(low_rank, low_rank, kernel_size, kernel_size)), + requires_grad=True + ) + self.X = nn.Parameter( + torch.empty(size=(low_rank, out_channels)), + requires_grad=True + ) + self.Y = nn.Parameter( + torch.empty(size=(low_rank, in_channels)), + requires_grad=True + ) + if activation == 'leakyrelu': activation = 'leaky_relu' + init.kaiming_normal_(self.T, mode='fan_out', nonlinearity=activation) + init.kaiming_normal_(self.X, mode='fan_out', nonlinearity=activation) + init.kaiming_normal_(self.Y, mode='fan_out', nonlinearity=activation) + + def forward(self): + # torch.einsum simplify the tensor produce (matrix multiplication) + return torch.einsum("xyzw,xo,yi->oizw", self.T, self.X, self.Y) +class Conv2d(nn.Module): + def __init__(self, + in_channels: int, + out_channels: int, + kernel_size: int = 3, + stride: int = 1, + padding: int = 0, + bias: bool = False, + ratio: float = 0.1, + add_nonlinear: bool = False, + activation: str = 'relu'): + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.bias = bias + self.ratio = ratio + self.low_rank = self._calc_from_ratio() + self.add_nonlinear = add_nonlinear + self.activation = activation + self.W1 = LowRank(in_channels, out_channels, self.low_rank, kernel_size,activation) + self.W2 = LowRank(in_channels, out_channels, self.low_rank, kernel_size,activation) + self.bias = nn.Parameter(torch.zeros(out_channels)) if bias else None + self.tanh = nn.Tanh() + + def _calc_from_ratio(self): + # Return the low-rank of sub-matrices given the compression ratio + r1 = int(np.ceil(np.sqrt(self.out_channels))) + r2 = int(np.ceil(np.sqrt(self.in_channels))) + r = np.max((r1, r2)) + + num_target_params = self.out_channels * self.in_channels * \ + (self.kernel_size ** 2) * self.ratio + r3 = np.sqrt( + ((self.out_channels + self.in_channels) ** 2) / (4 * (self.kernel_size ** 4)) + \ + num_target_params / (2 * (self.kernel_size ** 2)) + ) - (self.out_channels + self.in_channels) / (2 * (self.kernel_size ** 2)) + r3 = int(np.ceil(r3)) + r = np.max((r, r3)) + + return r + + def forward(self, x): + # Hadamard product of two submatrices + if self.add_nonlinear: + W = self.tanh(self.W1()) * self.tanh(self.W2()) + else: + W = self.W1() * self.W2() + out = F.conv2d(input=x, weight=W, bias=self.bias, + stride=self.stride, padding=self.padding) + return out +class VGG(nn.Module): + def __init__(self,num_classes, num_groups=2, ratio=0.1, activation='relu', + conv_type='lowrank', add_nonlinear=False): + super(VGG, self).__init__() + if activation == 'relu': + self.activation = nn.ReLU(inplace=True) + elif activation == 'leaky_relu': + self.activation = nn.LeakyReLU(inplace=True) + self.conv_type = conv_type + self.num_groups = num_groups + self.num_classes = num_classes + self.ratio = ratio + self.add_nonlinear = add_nonlinear + self.features = self.make_layers([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M' + , 512, 512, 512, 'M', 512, 512, 512, 'M']) + self.classifier = nn.Sequential( + nn.Dropout(), + nn.Linear(512, 512), + self.activation, + nn.Dropout(), + nn.Linear(512, 512), + self.activation, + nn.Linear(512, num_classes), + ) + self.init_weights() + + def init_weights(self): + for name, module in self.features.named_children(): + module = getattr(self.features, name) + if isinstance(module, nn.Conv2d): + if self.conv_type == 'lowrank': + num_channels = module.in_channels + setattr(self.features, name, Conv2d( + num_channels, + module.out_channels, + module.kernel_size[0], + module.stride[0], + module.padding[0], + module.bias is not None, + ratio=self.ratio, + add_nonlinear=self.add_nonlinear, + # send the name of the activation function to the Conv2d class + activation=self.activation.__class__.__name__.lower() + )) + elif self.conv_type == 'standard': + n = module.kernel_size[0] * module.kernel_size[1] * module.out_channels + module.weight.data.normal_(0, math.sqrt(2. / n)) + module.bias.data.zero_() + + def make_layers(self,cfg, group_norm=True): + layers = [] + in_channels = 3 + for v in cfg: + if v == 'M': + layers += [nn.MaxPool2d(kernel_size=2, stride=2)] + else: + conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) + if group_norm: + layers += [conv2d, nn.GroupNorm(self.num_groups,v), self.activation] + else: + layers += [conv2d, self.activation] + in_channels = v + return nn.Sequential(*layers) + + def forward(self, input): + x = self.features(input) + x = x.view(x.size(0), -1) + x = self.classifier(x) + return x + + +# Create an instance of the VGG16GN model with Group Normalization, custom Conv2d, and modified classifier + +def test( + net: nn.Module, test_loader: DataLoader, device: torch.device +) -> Tuple[float, float]: + """Evaluate the network on the entire test set. + + Parameters + ---------- + net : nn.Module + The neural network to test. + test_loader : DataLoader + The DataLoader containing the data to test the network on. + device : torch.device + The device on which the model should be tested, either 'cpu' or 'cuda'. + + Returns + ------- + Tuple[float, float] + The loss and the accuracy of the input model on the given data. + """ + if len(test_loader.dataset) == 0: + raise ValueError("Testloader can't be 0, exiting...") + + criterion = torch.nn.CrossEntropyLoss() + correct, total, loss = 0, 0, 0.0 + net.eval() + with torch.no_grad(): + for images, labels in tqdm(test_loader, "Testing ..."): + images, labels = images.to(device), labels.to(device) + outputs = net(images) + loss += criterion(outputs, labels).item() + _, predicted = torch.max(outputs.data, 1) + total += labels.size(0) + correct += (predicted == labels).sum().item() + loss /= len(test_loader.dataset) + accuracy = correct / total + return loss, accuracy + + +def train( # pylint: disable=too-many-arguments + net: nn.Module, + trainloader: DataLoader, + device: torch.device, + epochs: int, + hyperparams: Dict[str, Scalar], + round: int, +) -> None: + """Train the network on the training set. + + Parameters + ---------- + net : nn.Module + The neural network to train. + trainloader : DataLoader + The DataLoader containing the data to train the network on. + device : torch.device + The device on which the model should be trained, either 'cpu' or 'cuda'. + epochs : int + The number of epochs the model should be trained for. + hyperparams : Dict[str, Scalar] + The hyperparameters to use for training. + """ + lr=hyperparams["eta_l"]*hyperparams["learning_decay"]**(round-1) + print(f"Learning rate: {lr}") + criterion = torch.nn.CrossEntropyLoss() + optimizer = torch.optim.SGD( + net.parameters(), + lr=lr, + momentum=hyperparams["momentum"], + weight_decay=hyperparams["weight_decay"], + ) + net.train() + for _ in tqdm(range(epochs), desc="Local Training ..."): + net = _train_one_epoch( + net=net, + trainloader=trainloader, + device=device, + criterion=criterion, + optimizer=optimizer, + hyperparams=hyperparams, + ) + + +def _train_one_epoch( # pylint: disable=too-many-arguments + net: nn.Module, + trainloader: DataLoader, + device: torch.device, + criterion, + optimizer, + hyperparams: Dict[str, Scalar], +) -> nn.Module: + """Train for one epoch. + + Parameters + ---------- + net : nn.Module + The neural network to train. + trainloader : DataLoader + The DataLoader containing the data to train the network on. + device : torch.device + The device on which the model should be trained, either 'cpu' or 'cuda'. + criterion : + The loss function to use for training + optimizer : + The optimizer to use for training + hyperparams : Dict[str, Scalar] + The hyperparameters to use for training. + + Returns + ------- + nn.Module + The model that has been trained for one epoch. + """ + for images, labels in trainloader: + images, labels = images.to(device), labels.to(device) + net.zero_grad() + log_probs = net(images) + loss = criterion(log_probs, labels) + loss.backward() + optimizer.step() + return net + + +if __name__ == "__main__": + model = VGG(num_classes=10, num_groups=2, conv_type='standard') + model = torch.nn.Sequential(*list(model.features.children())) + # Print the modified VGG16GN model architecture + print(model) + total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + print(f"Total number of parameters: {total_trainable_params / 1e6}") + param_size = 0 + for param in model.parameters(): + param_size += param.nelement() * param.element_size() + buffer_size = 0 + for buffer in model.buffers(): + buffer_size += buffer.nelement() * buffer.element_size() + + size_all_mb = (param_size + buffer_size) / 1024**2 + print('model size: {:.3f}MB'.format(size_all_mb)) diff --git a/baselines/fedpara/fedpara/server.py b/baselines/fedpara/fedpara/server.py new file mode 100644 index 000000000000..f25732d22e18 --- /dev/null +++ b/baselines/fedpara/fedpara/server.py @@ -0,0 +1,58 @@ +"""Global evaluation function.""" + +from collections import OrderedDict +from typing import Callable, Dict, Optional, Tuple + +import torch +from flwr.common import NDArrays, Scalar +from hydra.utils import instantiate +from omegaconf import DictConfig +from torch.utils.data import DataLoader + +from fedpara.models import test + + +def gen_evaluate_fn( + test_loader: DataLoader, + model: DictConfig, + device, + experiment=None, +) -> Callable[ + [int, NDArrays, Dict[str, Scalar]], Optional[Tuple[float, Dict[str, Scalar]]] +]: + """Generate a centralized evaluation function. + + Parameters + ---------- + model: DictConfig + The model details to evaluate. + test_loader : DataLoader + The dataloader to test the model with. + device : torch.device + The device to test the model on. + + Returns + ------- + Callable[ [int, NDArrays, Dict[str, Scalar]], + Optional[Tuple[float, Dict[str, Scalar]]] ] + The centralized evaluation function. + """ + + def evaluate( + server_round, parameters_ndarrays: NDArrays, __ + ) -> Optional[Tuple[float, Dict[str, Scalar]]]: # pylint: disable=unused-argument + """Use the entire CIFAR-10/100 test set for evaluation.""" + net = instantiate(model) + params_dict = zip(net.state_dict().keys(), parameters_ndarrays) + state_dict = OrderedDict({k: torch.Tensor(v) for k, v in params_dict}) + net.load_state_dict(state_dict, strict=True) + net.to(device) + + loss, accuracy = test(net, test_loader, device=device) + + experiment.log_metric("loss", loss, epoch=server_round) + experiment.log_metric("accuracy", accuracy*100, epoch=server_round) + + return loss, {"accuracy": accuracy} + + return evaluate diff --git a/baselines/fedpara/fedpara/strategy.py b/baselines/fedpara/fedpara/strategy.py new file mode 100644 index 000000000000..e4085f3f97fa --- /dev/null +++ b/baselines/fedpara/fedpara/strategy.py @@ -0,0 +1,28 @@ +"""FedPara strategy.""" + +from typing import Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from flwr.common import FitRes, Parameters, Scalar, ndarrays_to_parameters +from flwr.server.client_proxy import ClientProxy +from flwr.server.strategy import FedAvg +from torch.nn.utils import parameters_to_vector, vector_to_parameters + +from fedpara.utils import get_parameters + + +class FedPara(FedAvg): + """FedPara strategy.""" + + def __init__( + self, + algorithm: str, + **kwargs, + ) -> None: + super().__init__(**kwargs) + self.algorithm = algorithm + + def __repr__(self) -> str: + """Return the name of the strategy.""" + return self.algorithm diff --git a/baselines/fedpara/fedpara/utils.py b/baselines/fedpara/fedpara/utils.py new file mode 100644 index 000000000000..6c5cbd339123 --- /dev/null +++ b/baselines/fedpara/fedpara/utils.py @@ -0,0 +1,63 @@ +"""Utility functions for FedPara.""" + +import random +from pathlib import Path +from typing import Optional + +import matplotlib.pyplot as plt +import numpy as np +import torch +from flwr.common import NDArrays +from flwr.server import History +from omegaconf import DictConfig +from torch.nn import Module + + +def plot_metric_from_history( + hist: History, + save_plot_path: str, + suffix: Optional[str] = "", + cfg: Optional[DictConfig] = None, +) -> None: + """Plot the metrics from the history of the server. + + Parameters + ---------- + hist : History + Object containing evaluation for all rounds. + save_plot_path : str + Folder to save the plot to. + suffix: Optional[str] + Optional string to add at the end of the filename for the plot. + cfg : Optional[DictConfig] + Optional dictionary containing the configuration of the experiment. + """ + metric_type = "centralized" + metric_dict = ( + hist.metrics_centralized + if metric_type == "centralized" + else hist.metrics_distributed + ) + rounds, values_accuracy = zip(*metric_dict["accuracy"]) + _, axs = plt.subplots() + # Set the title + axs.set_title(f"{cfg.strategy.algorithm} | {cfg.dataset_config.name} | Seed {cfg.seed}") + axs.plot(np.asarray(rounds), np.asarray(values_accuracy)) + axs.set_ylabel("Accuracy") + axs.set_xlabel("Rounds") + fig_name = "_".join([metric_type, "metrics", suffix]) + ".png" + plt.savefig(Path(save_plot_path) / Path(fig_name)) + plt.close() + + +def seed_everything(seed): + """Seed everything for reproducibility.""" + np.random.seed(seed) + torch.manual_seed(seed) + random.seed(seed) + torch.backends.cudnn.deterministic = True + + +def get_parameters(net: Module) -> NDArrays: + """Get the parameters of the network.""" + return [val.cpu().numpy() for _, val in net.state_dict().items()] diff --git a/baselines/fedpara/pyproject.toml b/baselines/fedpara/pyproject.toml new file mode 100644 index 000000000000..e07a100940f3 --- /dev/null +++ b/baselines/fedpara/pyproject.toml @@ -0,0 +1,137 @@ +[build-system] +requires = ["poetry-core>=1.4.0"] +build-backend = "poetry.masonry.api" + +[tool.poetry] +name = "fedpara" # <----- Ensure it matches the name of your baseline directory containing all the source code +version = "1.0.0" +description = "Flower Baselines" +license = "Apache-2.0" +authors = ["The Flower Authors "] +readme = "README.md" +homepage = "https://flower.dev" +repository = "https://github.com/adap/flower" +documentation = "https://flower.dev" +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: MacOS :: MacOS X", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Scientific/Engineering :: Mathematics", + "Topic :: Software Development", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] + +[tool.poetry.dependencies] +python = ">=3.8.15, <3.12.0" # don't change this +flwr = { extras = ["simulation"], version = "1.5.0" } +hydra-core = "1.3.2" # don't change this + +[tool.poetry.dev-dependencies] +isort = "==5.11.5" +black = "==23.1.0" +docformatter = "==1.5.1" +mypy = "==1.4.1" +pylint = "==2.8.2" +flake8 = "==3.9.2" +pytest = "==6.2.4" +pytest-watch = "==4.2.0" +ruff = "==0.0.272" +types-requests = "==2.27.7" + +[tool.isort] +line_length = 88 +indent = " " +multi_line_output = 3 +include_trailing_comma = true +force_grid_wrap = 0 +use_parentheses = true + +[tool.black] +line-length = 88 +target-version = ["py38", "py39", "py310", "py311"] + +[tool.pytest.ini_options] +minversion = "6.2" +addopts = "-qq" +testpaths = [ + "flwr_baselines", +] + +[tool.mypy] +ignore_missing_imports = true +strict = false +plugins = "numpy.typing.mypy_plugin" + +[tool.pylint."MESSAGES CONTROL"] +disable = "bad-continuation,duplicate-code,too-few-public-methods,useless-import-alias" +good-names = "i,j,k,_,x,y,X,Y" +signature-mutators="hydra.main.main" + +[tool.pylint.typecheck] +generated-members="numpy.*, torch.*, tensorflow.*" + +[[tool.mypy.overrides]] +module = [ + "importlib.metadata.*", + "importlib_metadata.*", +] +follow_imports = "skip" +follow_imports_for_stubs = true +disallow_untyped_calls = false + +[[tool.mypy.overrides]] +module = "torch.*" +follow_imports = "skip" +follow_imports_for_stubs = true + +[tool.docformatter] +wrap-summaries = 88 +wrap-descriptions = 88 + +[tool.ruff] +target-version = "py38" +line-length = 88 +select = ["D", "E", "F", "W", "B", "ISC", "C4"] +fixable = ["D", "E", "F", "W", "B", "ISC", "C4"] +ignore = ["B024", "B027"] +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".hg", + ".mypy_cache", + ".nox", + ".pants.d", + ".pytype", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + "__pypackages__", + "_build", + "buck-out", + "build", + "dist", + "node_modules", + "venv", + "proto", +] + +[tool.ruff.pydocstyle] +convention = "numpy" diff --git a/baselines/fedpara/run.sh b/baselines/fedpara/run.sh new file mode 100644 index 000000000000..9ac265afdbed --- /dev/null +++ b/baselines/fedpara/run.sh @@ -0,0 +1,4 @@ + poetry run python -m fedpara.main > "cifar10noniidaug.txt" 2>&1 & + poetry run python -m fedpara.main --config-name cifar100 > "cifar100noniidaug.txt" 2>&1 & + +wait \ No newline at end of file