This example demonstrates how an already existing centralized PyTorch-based machine learning project can be federated with Flower.
Start by cloning the example project. We prepared a single-line command that you can copy into your shell which will checkout the example for you:
git clone git@github.com:anaskalt/anomaly-fl.git
cd anomaly-fl/
This will create a new directory called anomaly-fl
containing the following files:
-- requirements.txt
-- data/
-- cell_data.py
-- anomaly.py
-- client.py
-- server.py
-- README.md
Project dependencies (such as torch
and flwr
) are defined in pyproject.toml
and requirements.txt
. We recommend Poetry to install those dependencies and manage your virtual environment (Poetry installation) or pip, but feel free to use a different way of installing dependencies and managing virtual environments if you have other preferences.
poetry install
poetry shell
Poetry will install all your dependencies in a newly created virtual environment. To verify that everything works correctly you can run the following command:
poetry run python3 -c "import flwr"
If you don't see any errors you're good to go!
Write the command below in your terminal to install the dependencies according to the configuration file requirements.txt.
pip install -r requirements.txt
You can simply start the centralized training as described in the tutorial by running anomaly.py
:
python3 anomaly.py
The next step is to use our existing project code in anomaly.py
and build a federated learning system based on it. The only things we need are a simple Flower server (in server.py
) and a Flower client that connects Flower to our existing model and data (in client.py
). The Flower client basically takes the already defined model and training code and tells Flower how to call it.
Start the server in a terminal as follows:
python3 server.py
Now that the server is running and waiting for clients, we can start two clients that will participate in the federated learning process. To do so simply open two more terminal windows and run the following commands.
Start client 1 in the first terminal:
python3 client.py
Start client 2 in the second terminal:
python3 client.py
Start client 3 in the third terminal:
python3 client.py
Start client 4 in the fourth terminal:
python3 client.py
Start client 5 in the fifth terminal:
python3 client.py
You are now training a PyTorch-based NN anomaly detection model, federated across five clients. Each client has a different part of Dataset.