├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── async_client_manager.py ├── async_history.py ├── async_server.py ├── async_strategy.py └── async_visualizer.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Flower 3 | .flower_ops 4 | data/ 5 | doc/source/api_documentation 6 | doc/source/_build 7 | flwr_logs 8 | .cache 9 | 10 | # Node.js 11 | node_modules 12 | 13 | # Flower Examples 14 | examples/**/dataset/** 15 | #examples/**/dev/*.sh 16 | 17 | # Flower Baselines 18 | baselines/datasets/leaf 19 | 20 | # macOS 21 | .DS_Store 22 | 23 | # Editor 24 | .vscode 25 | 26 | # Byte-compiled / optimized / DLL files 27 | __pycache__/ 28 | *.py[cod] 29 | *$py.class 30 | 31 | # C extensions 32 | *.so 33 | 34 | # Distribution / packaging 35 | .Python 36 | build/ 37 | develop-eggs/ 38 | dist/ 39 | downloads/ 40 | eggs/ 41 | .eggs/ 42 | lib/ 43 | lib64/ 44 | parts/ 45 | sdist/ 46 | var/ 47 | wheels/ 48 | pip-wheel-metadata/ 49 | share/python-wheels/ 50 | *.egg-info/ 51 | .installed.cfg 52 | *.egg 53 | MANIFEST 54 | .srl 55 | 56 | # PyInstaller 57 | # Usually these files are written by a python script from a template 58 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 59 | *.manifest 60 | *.spec 61 | 62 | # Installer logs 63 | pip-log.txt 64 | pip-delete-this-directory.txt 65 | 66 | # Unit test / coverage reports 67 | htmlcov/ 68 | .tox/ 69 | .nox/ 70 | .coverage 71 | .coverage.* 72 | .cache 73 | nosetests.xml 74 | coverage.xml 75 | *.cover 76 | *.py,cover 77 | .hypothesis/ 78 | .pytest_cache/ 79 | 80 | # Translations 81 | *.mo 82 | *.pot 83 | 84 | # Django stuff: 85 | *.log 86 | local_settings.py 87 | db.sqlite3 88 | db.sqlite3-journal 89 | 90 | # Flask stuff: 91 | instance/ 92 | .webassets-cache 93 | 94 | # Scrapy stuff: 95 | .scrapy 96 | 97 | # Sphinx documentation 98 | docs/_build/ 99 | 100 | # PyBuilder 101 | target/ 102 | 103 | # Jupyter Notebook 104 | .ipynb_checkpoints 105 | 106 | # IPython 107 | profile_default/ 108 | ipython_config.py 109 | 110 | # pyenv 111 | # For a library or package, you might want to ignore these files since the code is 112 | # intended to run in multiple environments; otherwise, check them in: 113 | .python-version 114 | 115 | # pipenv 116 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 117 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 118 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 119 | # install all needed dependencies. 120 | #Pipfile.lock 121 | 122 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 123 | __pypackages__/ 124 | 125 | # Celery stuff 126 | celerybeat-schedule 127 | celerybeat.pid 128 | 129 | # SageMath parsed files 130 | *.sage.py 131 | 132 | # Environments 133 | .env 134 | .venv 135 | env/ 136 | venv/ 137 | ENV/ 138 | env.bak/ 139 | venv.bak/ 140 | 141 | # Spyder project settings 142 | .spyderproject 143 | .spyproject 144 | 145 | # Rope project settings 146 | .ropeproject 147 | 148 | # mkdocs documentation 149 | /site 150 | 151 | # mypy 152 | .mypy_cache/ 153 | .dmypy.json 154 | dmypy.json 155 | 156 | # Pyre type checker 157 | .pyre/ 158 | 159 | # pytype static type analyzer 160 | .pytype/ 161 | 162 | # Poetry 163 | poetry.lock 164 | *.pkl 165 | 166 | # iOS 167 | xcuserdata/ 168 | 169 | # Android 170 | .gradle 171 | .idea 172 | local.properties 173 | app/src/main/assets 174 | /build 175 | *.iml 176 | /.idea/caches 177 | /.idea/libraries 178 | /.idea/modules.xml 179 | /.idea/workspace.xml 180 | /.idea/navEditor.xml 181 | /.idea/assetWizardSettings.xml 182 | .DS_Store 183 | /captures 184 | .externalNativeBuild 185 | .cxx 186 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flower-async 2 | Implementation of asynchronous federated learning in flower currently being developed as a part of my master's thesis. 3 | 4 | Currently offers the following modes of operation: 5 | - Unweighted - Upon each merge into the global model, the local updates and global model are weighted equally. 6 | - FedAsync - global_new = (1-alpha) * global_old + alpha * local_new 7 | - Where alpha depends on the staleness and/or number of samples used 8 | - AsyncFedED - global_new = global_old + $\eta$ * (local_new - global_old) 9 | - $\eta$ again depends on staleness and/or number of samples 10 | 11 | # Implementation 12 | 13 | The implementation consists of a modified server, strategy and client manager. 14 | 15 | The inspiration of this work stems from the following papers: 16 | - [Privacy-Preserving Asynchronous Federated Learning Mechanism for Edge Network Computing - ](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9022982) 17 | - [Asynchronous Federated Optimization ~ FedAsync](https://arxiv.org/pdf/1903.03934.pdf) 18 | - [AsyncFedED: Asynchronous Federated Learning with Euclidean Distance based Adaptive Weight Aggregation](https://arxiv.org/pdf/2205.13797.pdf) 19 | - [Federated Learning on Non-IID Data Silos: An Experimental Study](https://arxiv.org/abs/2102.02079) 20 | 21 | # Usage 22 | 23 | Use the server as typical flower server with one additional argument: 24 | - async_strategy - currently only responsible for aggregating the models. 25 | 26 | Moreover the async client manager should be used instead of the SimpleClientManager. 27 | 28 | The server instantiation would hence look something like this: 29 | ``` 30 | server = AsyncServer( 31 | strategy=FedAvg(), 32 | client_manager=AsyncClientManager(), 33 | async_strategy=AsynchronousStrategy()) 34 | ``` 35 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/r-gg/flower-async/35328b0651b6a67ff3cc0a6d8667425962912b6f/__init__.py -------------------------------------------------------------------------------- /async_client_manager.py: -------------------------------------------------------------------------------- 1 | 2 | from typing import List, Dict, Optional 3 | from flwr.server.client_manager import SimpleClientManager 4 | from flwr.server.client_proxy import ClientProxy 5 | from flwr.server.criterion import Criterion 6 | import threading 7 | from flwr.common.logger import log 8 | from logging import INFO, ERROR 9 | import random 10 | import time 11 | 12 | class AsyncClientManager(SimpleClientManager): 13 | 14 | def __init__(self) -> None: 15 | super().__init__() 16 | self.free_clients = {} 17 | self._cv_free = threading.Condition() 18 | 19 | def set_client_to_busy(self, client_id: str): 20 | if client_id not in self.free_clients.keys() or client_id not in self.clients.keys(): 21 | log(ERROR, "Client not found in free_clients") 22 | return False 23 | else: 24 | with self._cv_free: 25 | self.free_clients.pop(client_id) 26 | self._cv_free.notify_all() 27 | return True 28 | 29 | def set_client_to_free(self, client_id): 30 | if client_id not in self.clients.keys(): 31 | log(ERROR, "Client not found in clients") 32 | return False 33 | else: 34 | with self._cv_free: 35 | self.free_clients[client_id] = self.clients[client_id] 36 | self._cv_free.notify_all() 37 | return True 38 | 39 | # waits for `num_free_clients` to be free 40 | def wait_for_free(self, num_free_clients: int, timeout: int = 86400) -> bool: 41 | with self._cv_free: 42 | return self._cv_free.wait_for( 43 | lambda: len(self.free_clients) >= num_free_clients, timeout=5 44 | ) 45 | 46 | def register(self, client: ClientProxy) -> bool: 47 | log(INFO, "Registering client with id: %s", client.cid) 48 | if super().register(client): 49 | self.set_client_to_free(client.cid) 50 | return True 51 | else: 52 | return False 53 | 54 | def unregister(self, client: ClientProxy) -> None: 55 | log(INFO, "Unregistering client with id: %s", client.cid) 56 | if client.cid in self.free_clients: 57 | self.set_client_to_busy(client.cid) 58 | else: 59 | return super().unregister(client) 60 | 61 | 62 | def num_free(self) -> int: 63 | return len(self.free_clients) 64 | 65 | def all_free(self) -> Dict[str, ClientProxy]: 66 | return list(self.free_clients) 67 | 68 | def sample_free( 69 | self, 70 | num_free_clients: int, 71 | min_num_free_clients: int = 0, 72 | criterion: Criterion = None, 73 | ) -> List[ClientProxy]: 74 | log(INFO, "Sampling %s clients, min %s", num_free_clients, min_num_free_clients) 75 | """Sample a number of Flower ClientProxy instances.""" 76 | # Block until at least num_clients are free. # It always samples from all clients. 77 | if min_num_free_clients is None: 78 | min_num_free_clients = num_free_clients 79 | self.wait_for_free(min_num_free_clients) 80 | 81 | # Sample clients which meet the criterion 82 | available_cids = list(self.free_clients) 83 | if criterion is not None: 84 | available_cids = [ 85 | cid for cid in available_cids if criterion.select(self.free_clients[cid]) 86 | ] 87 | 88 | if num_free_clients > len(available_cids): 89 | log( 90 | INFO, 91 | "Sampling failed: number of available free clients" 92 | " (%s) is less than number of requested free clients (%s).", 93 | len(available_cids), 94 | num_free_clients, 95 | ) 96 | return [] 97 | 98 | sampled_cids = random.sample(available_cids, num_free_clients) 99 | ret_list = [self.free_clients[cid] for cid in sampled_cids] 100 | for cid in sampled_cids: 101 | self.set_client_to_busy(cid) 102 | return ret_list 103 | 104 | 105 | def sample( 106 | self, 107 | num_clients: int, 108 | min_num_clients: Optional[int] = None, 109 | criterion: Optional[Criterion] = None, 110 | ) -> List[ClientProxy]: 111 | return self.sample_free(num_clients, min_num_clients, criterion) -------------------------------------------------------------------------------- /async_history.py: -------------------------------------------------------------------------------- 1 | """ 2 | A wrapper around the flower History class that offers centralized and distributed metrics per timestamp instead of per round. 3 | It also groups distributed_fit metrics per client instead of per client instead of per round. 4 | 5 | losses_centralized: [ (timestamp1, value1) , .... ] 6 | 7 | metrics_centralized: { 8 | "accuracy": [ (timestamp1, value1) , .... ] 9 | } 10 | metrics_distributed: { 11 | "client_ids": [ (timestamp1, [cid1, cid2, cid3]) ... ] 12 | "accuracy": [ (timestamp1, [value1, value2, value3]) , .... ] 13 | } 14 | metrics_distributed_fit_async: { 15 | "accuracy": { 16 | cid1: [ 17 | (timestamp1, value1), 18 | (timestamp2, value2), 19 | (timestamp3, value3) 20 | ... 21 | ], 22 | ... 23 | } 24 | ... 25 | } 26 | # Metrics collected after each merge into the global model. (Global model evaluated centrally after merge.) 27 | 28 | DEPRECATED: This takes too much time and serializes the training process. Will be removed in the future. 29 | 30 | metrics_centralized_async: { 31 | "accuracy": [ (timestamp1, value1) , .... ] 32 | } 33 | Note: value1 is collected at timestamp1 in metrics_distributed_fit. 34 | """ 35 | from flwr.server.history import History 36 | from typing import Dict 37 | from flwr.common.typing import Scalar 38 | from threading import Lock 39 | 40 | class AsyncHistory(History): 41 | 42 | def __init__(self) -> None: 43 | self.metrics_distributed_fit_async = {} 44 | self.metrics_centralized_async = {} # metrics aggregated after each merge into the global model. 45 | self.losses_centralized_async = [] 46 | super().__init__() 47 | 48 | def add_metrics_distributed_fit_async( 49 | self, client_id: str, metrics: Dict[str, Scalar], timestamp: float 50 | ) -> None: 51 | """Add metrics entries (from distributed fit).""" 52 | # lock = Lock() 53 | # with lock: 54 | for key in metrics: 55 | if key not in self.metrics_distributed_fit_async: 56 | self.metrics_distributed_fit_async[key] = {} 57 | if client_id not in self.metrics_distributed_fit_async[key]: 58 | self.metrics_distributed_fit_async[key][client_id] = [] 59 | self.metrics_distributed_fit_async[key][client_id].append((timestamp, metrics[key])) 60 | 61 | def add_metrics_centralized_async(self, metrics: Dict[str, Scalar], timestamp: float) -> None: 62 | """Add metrics entries (from centralized evaluation).""" 63 | # lock = Lock() 64 | # with lock: 65 | for metric in metrics: 66 | if metric not in self.metrics_centralized_async: 67 | self.metrics_centralized_async[metric] = [] 68 | self.metrics_centralized_async[metric].append((timestamp, metrics[metric])) 69 | 70 | def add_loss_centralized_async(self, timestamp: float, loss: float) -> None: 71 | """Add loss entries (from centralized evaluation).""" 72 | # lock = Lock() 73 | # with lock: 74 | self.losses_centralized_async.append((timestamp, loss)) 75 | 76 | def add_loss_centralized(self, timestamp: float, loss: float) -> None: 77 | return super().add_loss_centralized(timestamp, loss) 78 | 79 | def add_loss_distributed(self, timestamp: float, loss: float) -> None: 80 | return super().add_loss_distributed(timestamp, loss) 81 | 82 | def add_metrics_centralized(self, timestamp: float, metrics: Dict[str, bool | bytes | float | int | str]) -> None: 83 | return super().add_metrics_centralized(timestamp, metrics) 84 | 85 | def add_metrics_distributed(self, timestamp: float, metrics: Dict[str, bool | bytes | float | int | str]) -> None: 86 | return super().add_metrics_distributed(timestamp, metrics) -------------------------------------------------------------------------------- /async_server.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Flower Labs GmbH. 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 | """Flower server.""" 16 | 17 | import os 18 | import pickle 19 | from datetime import datetime 20 | import concurrent.futures 21 | from concurrent.futures import ThreadPoolExecutor 22 | from threading import Lock, Thread, Timer 23 | from logging import DEBUG, INFO, WARNING 24 | from typing import Dict, List, Optional, Tuple, Union 25 | from time import sleep, time 26 | import numpy as np 27 | 28 | from flwr.common import ( 29 | Code, 30 | DisconnectRes, 31 | EvaluateIns, 32 | EvaluateRes, 33 | FitIns, 34 | FitRes, 35 | Parameters, 36 | ReconnectIns, 37 | Scalar, 38 | ) 39 | from flwr.common.logger import log 40 | from flwr.common.typing import GetParametersIns, FitIns 41 | from flwr.common import parameters_to_ndarrays, ndarrays_to_parameters 42 | from flwr.server.client_manager import ClientManager 43 | from flwr.server.client_proxy import ClientProxy 44 | from flwr.server.history import History 45 | from flwr.server.strategy import FedAvg, Strategy 46 | import flwr.server.strategy.aggregate as agg 47 | from flwr.server.server import Server 48 | from flower_async.async_history import AsyncHistory 49 | 50 | from flower_async.async_client_manager import AsyncClientManager 51 | from flower_async.async_strategy import AsynchronousStrategy 52 | 53 | FitResultsAndFailures = Tuple[ 54 | List[Tuple[ClientProxy, FitRes]], 55 | List[Union[Tuple[ClientProxy, FitRes], BaseException]], 56 | ] 57 | EvaluateResultsAndFailures = Tuple[ 58 | List[Tuple[ClientProxy, EvaluateRes]], 59 | List[Union[Tuple[ClientProxy, EvaluateRes], BaseException]], 60 | ] 61 | ReconnectResultsAndFailures = Tuple[ 62 | List[Tuple[ClientProxy, DisconnectRes]], 63 | List[Union[Tuple[ClientProxy, DisconnectRes], BaseException]], 64 | ] 65 | 66 | 67 | class AsyncServer(Server): 68 | """Flower server implementing asynchronous FL.""" 69 | 70 | def __init__( 71 | self, 72 | strategy: Strategy, 73 | client_manager: ClientManager, # AsyncClientManager, 74 | async_strategy: AsynchronousStrategy, 75 | base_conf_dict, 76 | total_train_time: int = 85, 77 | waiting_interval: int = 5, 78 | max_workers: int = 2, 79 | server_artificial_delay: bool = False, 80 | ): 81 | self.async_strategy = async_strategy 82 | self.total_train_time = total_train_time 83 | # number of seconds waited to start a new set of clients (and evaluate the previous ones) 84 | self.waiting_interval = waiting_interval 85 | self.strategy = strategy 86 | self._client_manager = client_manager 87 | self.max_workers = max_workers 88 | self.client_data_percs: Dict[str, List[float]] = {} # dictionary tracking the data percentages sent to the client 89 | for key, value in base_conf_dict.items(): 90 | setattr(self, key, value) 91 | self.start_timestamp = 0.0 92 | self.end_timestamp = 0.0 93 | self.model_param_lock = Lock() 94 | self.server_artificial_delay = server_artificial_delay 95 | 96 | self.client_iters = np.zeros(60) 97 | if self.client_local_delay: 98 | np.random.seed(self.dataset_seed) 99 | n_clients_with_delay = 12 100 | self.clients_with_delay = np.random.choice(n_clients_with_delay, n_clients_with_delay, replace=False) 101 | self.delays_per_iter_per_client = np.random.uniform(0.0, 5.0, (1000, n_clients_with_delay)) 102 | 103 | 104 | 105 | def set_new_params(self, new_params: Parameters): 106 | with self.model_param_lock: 107 | self.parameters = new_params 108 | 109 | # pylint: disable=too-many-locals 110 | 111 | def busy_wait(self, seconds: float) -> None: 112 | """Busy wait for a number of seconds.""" 113 | start_time = time() 114 | while time() - start_time < seconds: 115 | pass 116 | 117 | def fit(self, num_rounds: int, timeout: Optional[float]) -> History: 118 | """Run federated averaging for a number of rounds.""" 119 | history = AsyncHistory() 120 | 121 | # Initialize parameters 122 | log(INFO, "Initializing global parameters") 123 | self.parameters = self._get_initial_parameters(timeout=timeout) 124 | log(INFO, "Evaluating initial parameters") 125 | res = self.strategy.evaluate(0, parameters=self.parameters) 126 | if res is not None: 127 | log( 128 | INFO, 129 | "initial parameters (loss, other metrics): %s, %s", 130 | res[0], 131 | res[1], 132 | ) 133 | history.add_loss_centralized(timestamp=time(), loss=res[0]) 134 | history.add_metrics_centralized(timestamp=time(), metrics=res[1]) 135 | 136 | # Run federated learning for num_rounds 137 | log(INFO, "FL starting") 138 | executor = ThreadPoolExecutor(max_workers=self.max_workers) 139 | start_time = time() 140 | end_timestamp = time() + self.total_train_time 141 | self.end_timestamp = end_timestamp 142 | self.start_timestamp = time() 143 | counter = 1 144 | self.fit_round( 145 | server_round=0, 146 | timeout=timeout, 147 | executor=executor, 148 | end_timestamp=end_timestamp, 149 | history=history 150 | ) 151 | 152 | best_loss = float('inf') 153 | patience_init = 50 # n times the `waiting interval` seconds 154 | patience = patience_init 155 | 156 | while time() - start_time < self.total_train_time: 157 | # If the clients are to be started periodically, move fit_round here and remove the executor.submit lines from _handle_finished_future_after_fit 158 | sleep(self.waiting_interval) 159 | if self.server_artificial_delay: 160 | self.busy_wait(10) 161 | loss = self.evaluate_centralized(counter, history) 162 | if loss is not None: 163 | if loss < best_loss - 1e-4: 164 | best_loss = loss 165 | patience = patience_init 166 | else: 167 | patience -= 1 168 | if patience == 0: 169 | log(INFO, "Early stopping") 170 | break 171 | #self.evaluate_decentralized(counter, history, timeout) 172 | counter += 1 173 | 174 | executor.shutdown(wait=True, cancel_futures=True) 175 | log(INFO, "FL finished") 176 | end_time = time() 177 | self.save_model() 178 | elapsed = end_time - start_time 179 | log(INFO, "FL finished in %s", elapsed) 180 | return history 181 | 182 | def save_model(self): 183 | # Save the model 184 | timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") 185 | 186 | model_path = f"models/model_async_{timestamp}.pkl" 187 | if not os.path.exists("models"): 188 | os.makedirs("models") 189 | with open(model_path, "wb") as f: 190 | log(DEBUG, "Saving model to %s", model_path) 191 | pickle.dump(self.parameters, f) 192 | log(INFO, "Model saved to %s", model_path) 193 | 194 | 195 | 196 | def evaluate_centralized(self, current_round: int, history: History): 197 | res_cen = self.strategy.evaluate( 198 | current_round, parameters=self.parameters) 199 | if res_cen is not None: 200 | loss_cen, metrics_cen = res_cen 201 | metrics_cen['end_timestamp'] = self.end_timestamp 202 | metrics_cen['start_timestamp'] = self.start_timestamp 203 | history.add_loss_centralized( 204 | timestamp=time(), loss=loss_cen) 205 | history.add_metrics_centralized( 206 | timestamp=time(), metrics=metrics_cen 207 | ) 208 | log(INFO, "Centralized evaluation: loss %s, f1=%s", loss_cen, metrics_cen['f1']) 209 | return loss_cen 210 | else: 211 | return None 212 | 213 | 214 | def evaluate_decentralized(self, current_round: int, history: History, timeout: Optional[float]): 215 | """Evaluate model on a sample of available clients 216 | NOTE: Only call this method if clients are started periodically. 217 | This is not to be called if the clients are starting immediately after they finish! This is because the ray actor cannot process 218 | two concurrent requests to the same client. They get mixed up and future.result() in client_fit can return an 219 | EvaluateRes instead of FitRes. 220 | """ 221 | res_fed = self.evaluate_round( 222 | server_round=current_round, timeout=timeout) 223 | if res_fed is not None: 224 | loss_fed, evaluate_metrics_fed, (results, _) = res_fed 225 | if loss_fed is not None: 226 | client_ids = [client.cid for client, _ in results] 227 | evaluate_metrics_fed['client_ids'] = client_ids 228 | history.add_loss_distributed( 229 | timestamp=time(), loss=loss_fed 230 | ) 231 | history.add_metrics_distributed( 232 | timestamp=time(), metrics=evaluate_metrics_fed 233 | ) 234 | 235 | def evaluate_round( 236 | self, 237 | server_round: int, 238 | timeout: Optional[float], 239 | ) -> Optional[ 240 | Tuple[Optional[float], Dict[str, Scalar], EvaluateResultsAndFailures] 241 | ]: 242 | """Validate current global model on a number of clients.""" 243 | # Get clients and their respective instructions from strategy 244 | client_instructions = self.strategy.configure_evaluate( 245 | server_round=server_round, 246 | parameters=self.parameters, 247 | client_manager=self._client_manager, 248 | ) 249 | if not client_instructions: 250 | log(INFO, "evaluate_round %s: no clients selected, cancel", server_round) 251 | return None 252 | log( 253 | DEBUG, 254 | "evaluate_round %s: strategy sampled %s clients (out of %s)", 255 | server_round, 256 | len(client_instructions), 257 | self._client_manager.num_available(), 258 | ) 259 | 260 | # Collect `evaluate` results from all clients participating in this round 261 | results, failures = evaluate_clients( 262 | client_instructions, 263 | max_workers=self.max_workers, 264 | timeout=timeout, 265 | ) 266 | log( 267 | DEBUG, 268 | "evaluate_round %s received %s results and %s failures", 269 | server_round, 270 | len(results), 271 | len(failures), 272 | ) 273 | # log(DEBUG, f"Evaluate results: {results}") 274 | 275 | # Aggregate the evaluation results 276 | aggregated_result: Tuple[ 277 | Optional[float], 278 | Dict[str, Scalar], 279 | ] = self.strategy.aggregate_evaluate(server_round, results, failures) 280 | 281 | loss_aggregated, metrics_aggregated = aggregated_result 282 | return loss_aggregated, metrics_aggregated, (results, failures) 283 | 284 | def fit_round( 285 | self, 286 | server_round: int, 287 | timeout: Optional[float], 288 | executor: ThreadPoolExecutor, 289 | end_timestamp: float, 290 | history: AsyncHistory, 291 | ): # -> Optional[Tuple[Optional[Parameters], Dict[str, Scalar], FitResultsAndFailures]]: 292 | """Perform a single round of federated averaging.""" 293 | # Get clients and their respective instructions from strategy 294 | client_instructions = self.strategy.configure_fit( 295 | server_round=server_round, 296 | parameters=self.parameters, 297 | client_manager=self._client_manager, 298 | ) 299 | for client_proxy, fitins in client_instructions: 300 | fitins.config = { **fitins.config, **self.get_config_for_client_fit(client_proxy.cid) } 301 | 302 | if not client_instructions: 303 | log(INFO, "fit_round %s: no clients selected, cancel", server_round) 304 | return None 305 | log( 306 | DEBUG, 307 | "fit_round %s: strategy sampled %s clients (out of %s)", 308 | server_round, 309 | len(client_instructions), 310 | self._client_manager.num_available(), 311 | ) 312 | 313 | # Collect `fit` results from all clients participating in this round 314 | fit_clients( 315 | client_instructions=client_instructions, 316 | timeout=timeout, 317 | server=self, 318 | executor=executor, 319 | end_timestamp=end_timestamp, 320 | history=history, 321 | ) 322 | 323 | def get_config_for_client_fit(self, client_id, iter=0): 324 | config = {} 325 | 326 | if self.client_local_delay and client_id in self.clients_with_delay: 327 | config['client_delay'] = self.delays_per_iter_per_client[iter, np.where(self.clients_with_delay == client_id)[0][0]] 328 | config['cid'] = client_id 329 | return config 330 | 331 | if not self.is_streaming: 332 | return config 333 | curr_timestamp = time() 334 | if curr_timestamp > self.end_timestamp: 335 | return config 336 | if client_id not in self.client_data_percs: 337 | self.client_data_percs[client_id] = [0.0] # Clients start with 10% of the data (otherwise called with 0 samples) 338 | prev_data_perc = self.client_data_percs[client_id][-1] 339 | start_timestamp = self.end_timestamp - self.total_train_time 340 | data_perc = ( (time() - start_timestamp) / self.total_train_time ) * 0.9 + 0.1 # Linearly increase the data percentage from 10% to 100% over the total_train_time 341 | config['data_percentage'] = data_perc 342 | config['prev_data_percentage'] = prev_data_perc 343 | config['data_loading_strategy'] = self.data_loading_strategy 344 | if self.data_loading_strategy == 'fixed_nr': 345 | config['n_last_samples_for_data_loading_fit'] = self.n_last_samples_for_data_loading_fit 346 | self.client_data_percs[client_id].append(data_perc) 347 | return config 348 | 349 | def disconnect_all_clients(self, timeout: Optional[float]) -> None: 350 | """Send shutdown signal to all clients.""" 351 | all_clients = self._client_manager.all() 352 | clients = [all_clients[k] for k in all_clients.keys()] 353 | instruction = ReconnectIns(seconds=None) 354 | client_instructions = [(client_proxy, instruction) 355 | for client_proxy in clients] 356 | _ = reconnect_clients( 357 | client_instructions=client_instructions, 358 | max_workers=self.max_workers, 359 | timeout=timeout, 360 | ) 361 | 362 | def _get_initial_parameters(self, timeout: Optional[float]) -> Parameters: 363 | """Get initial parameters from one of the available clients.""" 364 | # Server-side parameter initialization 365 | parameters: Optional[Parameters] = self.strategy.initialize_parameters( 366 | client_manager=self._client_manager 367 | ) 368 | if parameters is not None: 369 | log(INFO, "Using initial parameters provided by strategy") 370 | return parameters 371 | 372 | # Get initial parameters from one of the clients 373 | log(INFO, "Requesting initial parameters from one random client") 374 | random_client = self._client_manager.sample(1)[0] 375 | ins = GetParametersIns(config={}) 376 | get_parameters_res = random_client.get_parameters( 377 | ins=ins, timeout=timeout) 378 | log(INFO, "Received initial parameters from one random client") 379 | return get_parameters_res.parameters 380 | 381 | 382 | def reconnect_clients( 383 | client_instructions: List[Tuple[ClientProxy, ReconnectIns]], 384 | max_workers: Optional[int], 385 | timeout: Optional[float], 386 | ) -> ReconnectResultsAndFailures: 387 | """Instruct clients to disconnect and never reconnect.""" 388 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: 389 | 390 | submitted_fs = { 391 | executor.submit(reconnect_client, client_proxy, ins, timeout) 392 | for client_proxy, ins in client_instructions 393 | } 394 | finished_fs, _ = concurrent.futures.wait( 395 | fs=submitted_fs, 396 | timeout=None, # Handled in the respective communication stack 397 | ) 398 | 399 | # Gather results 400 | results: List[Tuple[ClientProxy, DisconnectRes]] = [] 401 | failures: List[Union[Tuple[ClientProxy, 402 | DisconnectRes], BaseException]] = [] 403 | for future in finished_fs: 404 | failure = future.exception() 405 | if failure is not None: 406 | failures.append(failure) 407 | else: 408 | result = future.result() 409 | results.append(result) 410 | return results, failures 411 | 412 | 413 | def reconnect_client( 414 | client: ClientProxy, 415 | reconnect: ReconnectIns, 416 | timeout: Optional[float], 417 | ) -> Tuple[ClientProxy, DisconnectRes]: 418 | """Instruct client to disconnect and (optionally) reconnect later.""" 419 | disconnect = client.reconnect( 420 | reconnect, 421 | timeout=timeout, 422 | ) 423 | return client, disconnect 424 | 425 | 426 | def handle_futures(futures, server): 427 | for future in futures: 428 | _handle_finished_future_after_fit( 429 | future=future, server=server 430 | ) 431 | 432 | 433 | def fit_clients( 434 | client_instructions: List[Tuple[ClientProxy, FitIns]], 435 | timeout: Optional[float], 436 | server: AsyncServer, 437 | executor: ThreadPoolExecutor, 438 | end_timestamp: float, 439 | history: AsyncHistory, 440 | ): 441 | """Refine parameters concurrently on all selected clients.""" 442 | 443 | submitted_fs = { 444 | executor.submit(fit_client, client_proxy, ins, timeout) 445 | for client_proxy, ins in client_instructions 446 | } 447 | for f in submitted_fs: 448 | f.add_done_callback( 449 | lambda ftr: _handle_finished_future_after_fit(ftr, server=server, executor=executor, end_timestamp=end_timestamp, history=history), 450 | ) 451 | 452 | 453 | def fit_client( 454 | client: ClientProxy, ins: FitIns, timeout: Optional[float] 455 | ) -> Tuple[ClientProxy, FitRes]: 456 | """Refine parameters on a single client.""" 457 | fit_res = client.fit(ins, timeout=timeout) 458 | return client, fit_res 459 | 460 | 461 | def _handle_finished_future_after_fit( 462 | future: concurrent.futures.Future, 463 | server: AsyncServer, 464 | executor: ThreadPoolExecutor, 465 | end_timestamp: float, 466 | history: AsyncHistory, 467 | ) -> None: 468 | """Update the server parameters, restart the client.""" 469 | 470 | # Check if there was an exception 471 | failure = future.exception() 472 | if failure is not None: 473 | log(WARNING, "Got a failure :(") 474 | return 475 | 476 | # print("Got a result :)") 477 | result: Tuple[ClientProxy, FitRes] = future.result() 478 | clientProxy, res = result 479 | 480 | if res.status.code == Code.OK: 481 | parameters_aggregated = server.async_strategy.average( 482 | server.parameters, res.parameters, res.metrics['t_diff'], res.num_examples) 483 | server.set_new_params(parameters_aggregated) 484 | 485 | history.add_metrics_distributed_fit_async( 486 | clientProxy.cid,{"sample_sizes": res.num_examples, **res.metrics }, timestamp=time() 487 | ) 488 | 489 | if time() < end_timestamp: 490 | # log(DEBUG, f"Yippie! Starting the client {clientProxy.cid} again \U0001f973") 491 | iter = server.client_iters[int(clientProxy.cid)] + 1 492 | server.client_iters[int(clientProxy.cid)] = iter 493 | new_ins = FitIns(server.parameters, server.get_config_for_client_fit(clientProxy.cid, iter=iter)) 494 | ftr = executor.submit(fit_client, client=clientProxy, ins=new_ins, timeout=None) 495 | ftr.add_done_callback(lambda ftr: _handle_finished_future_after_fit(ftr, server, executor, end_timestamp, history)) 496 | 497 | 498 | ############################### FOR EVALUATION #################################### 499 | 500 | def evaluate_clients( 501 | client_instructions: List[Tuple[ClientProxy, EvaluateIns]], 502 | max_workers: Optional[int], 503 | timeout: Optional[float], 504 | ) -> EvaluateResultsAndFailures: 505 | """Evaluate parameters concurrently on all selected clients.""" 506 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: 507 | submitted_fs = { 508 | executor.submit(evaluate_client, client_proxy, ins, timeout) 509 | for client_proxy, ins in client_instructions 510 | } 511 | finished_fs, _ = concurrent.futures.wait( 512 | fs=submitted_fs, 513 | timeout=None, # Handled in the respective communication stack 514 | ) 515 | 516 | # Gather results 517 | results: List[Tuple[ClientProxy, EvaluateRes]] = [] 518 | failures: List[Union[Tuple[ClientProxy, EvaluateRes], BaseException]] = [] 519 | for future in finished_fs: 520 | _handle_finished_future_after_evaluate( 521 | future=future, results=results, failures=failures 522 | ) 523 | return results, failures 524 | 525 | 526 | def evaluate_client( 527 | client: ClientProxy, 528 | ins: EvaluateIns, 529 | timeout: Optional[float], 530 | ) -> Tuple[ClientProxy, EvaluateRes]: 531 | """Evaluate parameters on a single client.""" 532 | evaluate_res = client.evaluate(ins, timeout=timeout) 533 | return client, evaluate_res 534 | 535 | 536 | def _handle_finished_future_after_evaluate( 537 | future: concurrent.futures.Future, # type: ignore 538 | results: List[Tuple[ClientProxy, EvaluateRes]], 539 | failures: List[Union[Tuple[ClientProxy, EvaluateRes], BaseException]], 540 | ) -> None: 541 | """Convert finished future into either a result or a failure.""" 542 | # Check if there was an exception 543 | failure = future.exception() 544 | if failure is not None: 545 | failures.append(failure) 546 | return 547 | 548 | # Successfully received a result from a client 549 | result: Tuple[ClientProxy, EvaluateRes] = future.result() 550 | _, res = result 551 | 552 | # Check result status code 553 | if res.status.code == Code.OK: 554 | results.append(result) 555 | return 556 | 557 | # Not successful, client returned a result where the status code is not OK 558 | failures.append(result) 559 | -------------------------------------------------------------------------------- /async_strategy.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import pickle 4 | import math 5 | from flwr.common import Parameters 6 | import flwr.server.strategy.aggregate as agg 7 | from flwr.common import parameters_to_ndarrays, ndarrays_to_parameters 8 | from typing import List, Tuple 9 | from flwr.common import NDArrays, log 10 | from logging import DEBUG, WARNING 11 | from time import time 12 | 13 | class AsynchronousStrategy: 14 | """Abstract base class for all asynchronous strategies.""" 15 | 16 | def __init__(self, total_samples: int, staleness_alpha: float, fedasync_mixing_alpha: float, fedasync_a: float, num_clients: int, async_aggregation_strategy: str, 17 | use_staleness: bool, use_sample_weighing: bool, send_gradients: bool, server_artificial_delay: bool) -> None: 18 | self.total_samples = total_samples 19 | self.staleness_alpha = staleness_alpha 20 | self.fedasync_a = fedasync_a 21 | self.fedasync_mixing_alpha = fedasync_mixing_alpha 22 | self.num_clients = num_clients 23 | self.async_aggregation_strategy = async_aggregation_strategy 24 | self.use_staleness = use_staleness 25 | self.use_sample_weighing = use_sample_weighing 26 | self.send_gradients = send_gradients 27 | self.server_artificial_delay = server_artificial_delay 28 | 29 | 30 | def average(self, global_parameters: Parameters, model_update_parameters: Parameters, t_diff: float, num_samples: int) -> Parameters: 31 | """Compute the average of the global and client parameters.""" 32 | if self.async_aggregation_strategy == "fedasync": 33 | if self.send_gradients: 34 | return self.weighted_merge_fedasync(global_parameters, model_update_parameters, t_diff, num_samples) 35 | else: 36 | return self.weighted_average_fedasync(global_parameters, model_update_parameters, t_diff, num_samples) 37 | # elif self.async_aggregation_strategy == "asyncfeded": 38 | # return self.weighted_average_asyncfeded(global_parameters, model_update_parameters, t_diff, num_samples) 39 | # elif self.async_aggregation_strategy == "unweighted": 40 | # return self.unweighted_average(global_parameters, model_update_parameters) 41 | else: 42 | raise ValueError( 43 | f"Invalid async aggregation strategy: {self.async_aggregation_strategy}") 44 | 45 | def unweighted_average(self, global_parameters: Parameters, model_update_parameters: Parameters) -> Parameters: 46 | """Compute the unweighted average of the global and client parameters.""" 47 | return ndarrays_to_parameters(agg.aggregate([(parameters_to_ndarrays(global_parameters), 1), 48 | (parameters_to_ndarrays(model_update_parameters), 1)])) 49 | 50 | def weighted_average_asyncfeded(self, global_parameters: Parameters, model_update_parameters: Parameters, t_diff: float, num_samples: int) -> Parameters: 51 | """Compute the weighted average of the global and client parameters. Inspired by the paper asyncFedED : https://arxiv.org/pdf/2205.13797.pdf""" 52 | return ndarrays_to_parameters(self.aggregate_asyncfeded(parameters_to_ndarrays(global_parameters), parameters_to_ndarrays(model_update_parameters), t_diff, num_samples=num_samples)) 53 | 54 | def get_sample_weight_coeff(self, num_samples: int) -> float: 55 | """Compute the sample weight coefficient.""" 56 | return num_samples / self.total_samples 57 | 58 | def weighted_average_fedasync(self, global_parameters: Parameters, model_update_parameters: Parameters, t_diff: float, num_samples: int) -> Parameters: 59 | """Compute the weighted average of the global and client parameters. Inspired by the paper Fedasync : https://arxiv.org/pdf/1903.03934.pdf""" 60 | return ndarrays_to_parameters(self.aggregate_fedasync(parameters_to_ndarrays(global_parameters), parameters_to_ndarrays(model_update_parameters), t_diff, num_samples=num_samples)) 61 | 62 | def busy_wait(self, seconds: float) -> None: 63 | """Busy wait for the specified number of seconds.""" 64 | start = time() 65 | while time() - start < seconds: 66 | pass 67 | 68 | 69 | def aggregate_fedasync(self, global_param_arr: NDArrays, model_update_param_arr: NDArrays, t_diff: float, num_samples: int) -> NDArrays: 70 | """Compute weighted average with the formula params_new = (1-alpha) * params_old + alpha * (model_update_params)""" 71 | # Calculate the total number of examples used during training 72 | alpha_coeff = self.fedasync_mixing_alpha 73 | if self.use_staleness: 74 | alpha_coeff *= self.get_staleness_weight_coeff_fedasync_poly( 75 | t_diff=t_diff) 76 | if self.use_sample_weighing: 77 | alpha_coeff *= self.get_sample_weight_coeff(num_samples) 78 | 79 | if self.server_artificial_delay: 80 | self.busy_wait(0.5) 81 | # log(DEBUG, f"t_diff: {t_diff}\nalpha_coeff: {alpha_coeff}") 82 | 83 | return [(1 - alpha_coeff) * layer_global + alpha_coeff * layer_update for layer_global, layer_update in zip(global_param_arr, model_update_param_arr)] 84 | 85 | def weighted_merge_fedasync(self, global_parameters: Parameters, gradients: Parameters, t_diff: float, num_samples: int) -> Parameters: 86 | """Add gradients to the global model. Inspired by the paper Fedasync : https://arxiv.org/pdf/1903.03934.pdf 87 | It is not however the same procedure as in original paper, because they aggregate MODELS and we aggregate GRADIENTS. 88 | """ 89 | if self.server_artificial_delay: 90 | self.busy_wait(1) 91 | return ndarrays_to_parameters(self.add_grads_fedasync(parameters_to_ndarrays(global_parameters), parameters_to_ndarrays(gradients), t_diff, num_samples=num_samples)) 92 | 93 | def add_grads_fedasync(self, global_param_arr: NDArrays, gradients_arr: NDArrays, t_diff: float, num_samples: int) -> NDArrays: 94 | """Compute weighted average with the formula params_new = (1-alpha) * params_old + alpha * (params_old + update_grads)""" 95 | # Calculate the total number of examples used during training 96 | alpha_coeff = self.fedasync_mixing_alpha 97 | if self.use_staleness: 98 | alpha_coeff *= self.get_staleness_weight_coeff_fedasync_poly( 99 | t_diff=t_diff) 100 | if self.use_sample_weighing: 101 | alpha_coeff *= self.get_sample_weight_coeff(num_samples) 102 | 103 | # log(DEBUG, f"t_diff: {t_diff}\nalpha_coeff: {alpha_coeff}") 104 | 105 | return [(1 - alpha_coeff) * layer_global + alpha_coeff * (layer_global + layer_grad) for layer_global, layer_grad in zip(global_param_arr, gradients_arr)] 106 | 107 | # See paper: https://arxiv.org/pdf/2205.13797.pdf 108 | def aggregate_asyncfeded(self, global_param_arr: NDArrays, model_update_param_arr: NDArrays, t_diff: float, num_samples: int) -> NDArrays: 109 | """Computing the new parameters using the formula params_new = params_old + nu * (model_update_params) 110 | Where nu is influenced by the staleness of the model update and/or the number of samples. 111 | """ 112 | eta = 1 113 | if self.use_staleness: 114 | # Staleness weighted coefficient 115 | eta *= self.get_staleness_weight_coeff_paflm(t_diff=t_diff) 116 | if self.use_sample_weighing: 117 | eta *= self.get_sample_weight_coeff(num_samples) 118 | 119 | log(DEBUG, f"t_diff: {t_diff}\nnu: {eta}") 120 | return [layer_global + eta * (layer_update - layer_global) for layer_global, layer_update in zip(global_param_arr, model_update_param_arr)] 121 | 122 | # See paper for more details : https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9022982 123 | def get_staleness_weight_coeff_paflm(self, t_diff: float) -> float: 124 | mu_staleness = t_diff 125 | exponent = ((1 / float(self.num_clients)) * mu_staleness) - 1 126 | beta_P = math.pow(self.staleness_alpha, exponent) 127 | return beta_P 128 | 129 | # Paper: https://arxiv.org/pdf/1903.03934.pdf 130 | def get_staleness_weight_coeff_fedasync_constant(self) -> float: 131 | return 1.0 132 | 133 | def get_staleness_weight_coeff_fedasync_poly(self, t_diff: float) -> float: 134 | return math.pow(t_diff + 1, -self.fedasync_a) 135 | 136 | def get_staleness_weight_coeff_fedasync_hinge(self, t_diff: float, a: float = 10, b: float = 4) -> float: 137 | return 1 if t_diff <= b else 1 / (a * (t_diff - b) + 1) 138 | -------------------------------------------------------------------------------- /async_visualizer.py: -------------------------------------------------------------------------------- 1 | import math 2 | from monitoring_sync.tracker import Tracker 3 | from typing import List, Tuple, Any, Dict 4 | import matplotlib.pyplot as plt 5 | import pandas as pd 6 | import numpy as np 7 | from flwr.common import log 8 | from logging import DEBUG 9 | from flwr.server.history import History 10 | import seaborn as sns 11 | import glob 12 | 13 | nice_goal_label_names = ['WALKING', 'SITTING', 'STANDING', 'LYING_DOWN', 'RUNNING', 'BICYCLING'] 14 | 15 | 16 | def extract_vals_from_metrics(metrics: List[Tuple[int, Any]]): 17 | return [val for _, val in metrics] 18 | 19 | class AsyncVisualizer: 20 | """Visualize the collected metrics.""" 21 | 22 | def __init__(self, tracker:Tracker) -> None: 23 | self.tracker = tracker 24 | 25 | 26 | def extract_vals_from_metrics(self, metrics: List[Tuple[int, Any]]): 27 | return [val for _, val in metrics] 28 | 29 | def plot(self, folder_name: str): 30 | self.make_config_specific_visualizations(folder_name) 31 | # self.make_global_visualizations(config_specific_folder_name=folder_name) 32 | 33 | def extract_timestamps(self, metric_key): 34 | timestamps = [ts for ts, _ in self.tracker.history.metrics_centralized[metric_key]] 35 | first_ts = timestamps[0] 36 | return [t - first_ts for t in timestamps] 37 | 38 | def plot_metric(self, ax, x_values, y_values, title, xlabel, ylabel): 39 | """Plot a single metric on the provided Axes object.""" 40 | ax.plot(x_values, y_values) 41 | ax.set_title(title) 42 | ax.set_xlabel(xlabel) 43 | ax.set_ylabel(ylabel) 44 | 45 | def plot_final_centralized_confusion_matrix(self, folder_name: str): 46 | # Make a heatmap for the final confusion matrix and save it as a png 47 | fig, ax = plt.subplots(figsize=(10, 8)) 48 | sns.heatmap(self.tracker.history.metrics_centralized['confusion_matrix'][-1][1], annot=True, fmt='d', ax=ax, xticklabels=nice_goal_label_names, yticklabels=nice_goal_label_names) 49 | ax.set_title('Final Confusion Matrix') 50 | plt.savefig('results/' + folder_name + '/final_centralized_confusion_matrix.png') 51 | plt.clf() 52 | 53 | def make_centralized_metrics_plot(self, folder_name: str): 54 | plt.style.use('seaborn-v0_8-whitegrid') 55 | timestamps = self.extract_timestamps('accuracy') # Assuming all metrics share the same timestamps 56 | 57 | metrics = [ 58 | # ('accuracy', 'Accuracy'), 59 | ('loss', 'Loss'), 60 | # ('precision', 'Precision'), 61 | # ('recall', 'Recall'), 62 | ('f1', 'F1'), 63 | ('balanced_accuracy', 'Balanced Accuracy'), 64 | ] 65 | 66 | num_metrics = len(metrics) 67 | grid_size = math.ceil(math.sqrt(num_metrics)) 68 | fig, axs = plt.subplots(grid_size, grid_size, figsize=(5 * grid_size, 5 * grid_size)) 69 | axs = axs.flatten() 70 | 71 | for ax, (metric_key, metric_name) in zip(axs, metrics): 72 | metric_values = extract_vals_from_metrics(self.tracker.history.metrics_centralized.get(metric_key, [])) 73 | self.plot_metric(ax, timestamps, metric_values, f'Centralized {metric_name}', 'Timestamp', metric_name) 74 | 75 | fig.suptitle(f'Centralized Metrics, asynchronous setting:\n{self.tracker.dataset_name}, train_time: {self.tracker.total_train_time},'+ \ 76 | f',\naugmentation:{self.tracker.data_augmentation} ' + \ 77 | f'async_aggregation_strategy:{self.tracker.async_aggregation_strategy}, mixing alpha:{self.tracker.fedasync_mixing_alpha}', 78 | fontsize=12) 79 | plt.savefig(f'results/{folder_name}/centralized_metrics.png') 80 | plt.clf() 81 | 82 | def make_centralized_final_perclass_metrics_plot(self, folder_name: str): 83 | # Make a two subplots for final precision and recall per class and save it as a png 84 | fig, axs = plt.subplots(1, 3, figsize=(20, 5)) 85 | x_axis = range(1, self.tracker.num_classes + 1) 86 | axs[0].bar(x_axis, self.tracker.history.metrics_centralized['precision_perclass'][-1][1]) 87 | axs[0].set_title('Final Precision per class') 88 | axs[0].set_xlabel('Class') 89 | axs[0].set_ylabel('Precision') 90 | axs[1].bar(x_axis, self.tracker.history.metrics_centralized['recall_perclass'][-1][1]) 91 | axs[1].set_title('Final Recall per class') 92 | axs[1].set_xlabel('Class') 93 | axs[1].set_ylabel('Recall') 94 | axs[2].bar(x_axis, self.tracker.history.metrics_centralized['f1_perclass'][-1][1]) 95 | axs[2].set_title('Final F1 per class') 96 | axs[2].set_xlabel('Class') 97 | axs[2].set_ylabel('F1') 98 | fig.suptitle(f'Final Metrics for setting:\n{self.tracker.dataset_name}, train_time: {self.tracker.total_train_time},\n' + \ 99 | f'async_aggregation_strategy:{self.tracker.async_aggregation_strategy}, Mixing_alpha: {self.tracker.fedasync_mixing_alpha}') 100 | plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) 101 | plt.savefig('results/' + folder_name 102 | + '/centralized_final_perclass_metrics.png') 103 | plt.clf() 104 | 105 | def make_target_counts_plot(self, folder_name: str): 106 | # Create a stacked barplot that shows target_counts for each client (one bar = one client) 107 | fig, ax = plt.subplots(figsize=(15, 10)) 108 | df = pd.DataFrame(self.tracker.target_counts) 109 | df.plot(kind='bar', stacked=True, ax=ax) 110 | ax.set_title(f'Target counts for setting:\n{self.tracker.dataset_name}, train_time: {self.tracker.total_train_time},\ndata augmentation:{self.tracker.data_augmentation}' + \ 111 | f'async_aggregation_strategy:{self.tracker.async_aggregation_strategy}, mixing alpha:{self.tracker.fedasync_mixing_alpha}') 112 | ax.set_xlabel('Client') 113 | ax.set_ylabel('Count') 114 | lgd = ax.legend(title='Class', bbox_to_anchor=( 115 | 1.05, 1), loc=2, borderaxespad=0.) 116 | 117 | plt.savefig('results/' + folder_name + '/target_counts.png', 118 | bbox_extra_artists=(lgd,), bbox_inches='tight') 119 | plt.clf() 120 | 121 | 122 | def get_client_metrics(self, metric_name, client_id): 123 | """Extracts and normalizes timestamps and values for a specific client metric.""" 124 | if str(client_id) in self.tracker.history.metrics_distributed_fit_async[metric_name]: 125 | timestamps = [ts for ts, _ in self.tracker.history.metrics_distributed_fit_async[metric_name][str(client_id)]] 126 | first_ts = timestamps[0] 127 | normalized_timestamps = [t - first_ts for t in timestamps] 128 | values = [val for _, val in self.tracker.history.metrics_distributed_fit_async[metric_name][str(client_id)]] 129 | return normalized_timestamps, values 130 | return [], [] 131 | 132 | def count_times_started(self, metric_name): 133 | """Counts the number of times each client has started based on the metric.""" 134 | times_started = np.zeros(self.tracker.num_clients) 135 | for i in range(self.tracker.num_clients): 136 | if str(i) in self.tracker.history.metrics_distributed_fit_async[metric_name]: 137 | times_started[i] = len(self.tracker.history.metrics_distributed_fit_async[metric_name][str(i)]) 138 | return times_started 139 | 140 | def make_metrics_per_client_over_time_plot(self, folder_name: str, metric_name: str, title_suffix: str = ''): 141 | samples_per_client = self.tracker.sample_sizes 142 | times_started = self.count_times_started(metric_name) 143 | n = self.tracker.num_clients 144 | # Calculate number of rows and columns for a square or nearly square configuration 145 | num_cols = int(math.ceil(math.sqrt(n))) 146 | num_rows = int(math.ceil(n / num_cols)) 147 | 148 | fig, axs = plt.subplots(num_rows, num_cols, figsize=(5 * num_cols, 5 * num_rows), constrained_layout=True) 149 | fig.suptitle(f'{metric_name.capitalize()} per client over time (before training) for setting:\n{self.tracker.dataset_name}, train_time: {self.tracker.total_train_time},\nasync_aggregation_strategy:{self.tracker.async_aggregation_strategy}' + title_suffix) 150 | axs = axs.flatten() 151 | 152 | for i in range(n): 153 | timestamps, values = self.get_client_metrics(metric_name, i) 154 | axs[i].plot(timestamps, values) 155 | axs[i].set_title(f'Client: {i+1}, Samples: {samples_per_client[i]}, Times started: {times_started[i]}') 156 | axs[i].set_ylim(0, 1) 157 | axs[i].set_ylabel(metric_name) 158 | axs[i].set_xlabel('time') 159 | 160 | for i in range(n, num_rows * num_cols): 161 | axs[i].axis('off') 162 | 163 | fig.savefig(f'results/{folder_name}/{metric_name.lower()}_per_client_over_time{title_suffix}.png') 164 | plt.clf() 165 | 166 | 167 | def make_interval_plot_async(self, folder_name: str): 168 | times_started = self.tracker.history.metrics_distributed_fit_async['time_started'] 169 | local_train_times = self.tracker.history.metrics_distributed_fit_async['local_train_time'] 170 | 171 | start_timestamp = self.tracker.history.metrics_centralized['start_timestamp'][0][1] 172 | end_timestamp = self.tracker.history.metrics_centralized['end_timestamp'][0][1] 173 | 174 | self.tracker.history.metrics_distributed_fit_async['time_started'] 175 | 176 | df = pd.DataFrame([], columns=['cid', 'start', 'end']) 177 | 178 | appended_data = [] 179 | for cid, lst in times_started.items(): 180 | for i, (_, start_time) in enumerate(lst): 181 | local_train_time = local_train_times[cid][i][1] 182 | new_df = pd.DataFrame([[cid, start_time-start_timestamp, start_time + local_train_time -start_timestamp]] , columns=['cid', 'start', 'end']) 183 | appended_data.append(new_df) 184 | 185 | final_df = pd.concat(appended_data) 186 | df = final_df 187 | fig, ax = plt.subplots(figsize=(10, 8)) 188 | clients = df['cid'].unique() 189 | client_positions = {cid: i for i, cid in enumerate(sorted(clients), start=1)} 190 | for _, row in df.iterrows(): 191 | cid = row['cid'] 192 | start = row['start'] 193 | end = row['end'] 194 | ax.plot([start, end], [client_positions[cid], client_positions[cid]], marker='o') 195 | 196 | ax.axvline(0, color='b', linestyle='--', label='Start Timestamp') 197 | ax.axvline(end_timestamp-start_timestamp, color='r', linestyle='--', label='End Timestamp') 198 | 199 | ax.legend() 200 | plt.yticks(list(client_positions.values()), list(client_positions.keys())) 201 | plt.xlabel('Time') 202 | plt.ylabel('Client ID') 203 | plt.title('Intervals Marked by Start and End Times for Each Client') 204 | plt.grid(True) 205 | plt.savefig('results/' + folder_name + '/intervals.png') 206 | plt.clf() 207 | 208 | def make_f1_over_time_heatmap(self, folder_name: str): 209 | if getattr(self.tracker, 'id', None) is not None: 210 | id = self.tracker.id 211 | # Load all .npy files from a directory 212 | npy_files = glob.glob(f'f1_scores/{id}/*.npy') 213 | npy_files.sort() 214 | f1_scores = np.array([np.array(np.load(file, allow_pickle=True), dtype=np.float32) for file in npy_files]) 215 | plt.figure(figsize=(20,10)) 216 | sns.heatmap(f1_scores) 217 | plt.title('F1_scores over time per client') 218 | plt.ylabel('Time') 219 | plt.xlabel('Client') 220 | plt.savefig(f'results/{folder_name}/f1_over_time_heatmap.png') 221 | plt.clf() 222 | 223 | def make_f1_for_running_class_and_other_classes(self, folder_name: str): 224 | f1_pc = np.array([np.array(f1s) for ts, f1s in self.tracker.history.metrics_centralized['f1_perclass']]) 225 | sns.heatmap(f1_pc) 226 | plt.xticks(np.arange(6)+0.5, nice_goal_label_names, rotation=90) 227 | plt.ylabel('Time') 228 | plt.xlabel('Class') 229 | plt.title('Centralized per-class F1-Scores over time') 230 | plt.savefig(f'results/{folder_name}/f1_perclass_over_time.png') 231 | plt.clf() 232 | 233 | plt.plot(f1_pc[:, 4]) 234 | plt.title('F1 score of the running class over time') 235 | plt.xlabel('Time') 236 | plt.ylabel('F1-Score') 237 | plt.savefig(f'results/{folder_name}/f1_running_class_over_time.png') 238 | plt.clf() 239 | 240 | def make_config_specific_visualizations(self, folder_name: str): 241 | plt.style.use('seaborn-v0_8-whitegrid') 242 | # Make four subplots in one representing centralized accuracy, loss, precision, recall and save it as a png 243 | self.make_centralized_metrics_plot(folder_name) 244 | self.make_metrics_per_client_over_time_plot(folder_name, 'accuracy') 245 | self.make_metrics_per_client_over_time_plot(folder_name, 'precision') 246 | self.make_metrics_per_client_over_time_plot(folder_name, 'f1') 247 | self.make_centralized_final_perclass_metrics_plot(folder_name) 248 | self.make_target_counts_plot(folder_name) 249 | self.make_interval_plot_async(folder_name) 250 | self.plot_final_centralized_confusion_matrix(folder_name) 251 | self.make_f1_over_time_heatmap(folder_name) 252 | self.make_f1_for_running_class_and_other_classes(folder_name) 253 | 254 | 255 | 256 | 257 | 258 | def get_label_from_varied_params(varied_params: Dict[str,str], tracker: Tracker): 259 | if len(varied_params) > 4: 260 | half = len(varied_params.keys()) // 2 261 | res = ', '.join([f'{varied_params[param]}={getattr(tracker, param)}' for param in list(varied_params.keys())[:half]]) 262 | res += '\n' 263 | res += ', '.join([f'{varied_params[param]}={getattr(tracker, param)}' for param in list(varied_params.keys())[half:]]) 264 | else: 265 | res = ', '.join([f'{varied_params[param]}={getattr(tracker, param)}' for param in varied_params.keys()]) 266 | #if 'iid' in res: 267 | # res = re.sub(r"a=[+-]?([0-9]*[.])?[0-9]+", "", res) 268 | return res 269 | 270 | def config_to_str(config: Dict): 271 | return ', '.join([f'{key}={value}' for key, value in config.items()]) 272 | # NOTE: If there are multiple values for the **same label** the plot will be drawn over the previous plot. --------------------------------------------------------------------------------