diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 016c12af2426..61c8d14039db 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -24,8 +24,8 @@ RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhisto && echo $SNIPPET >> "/home/$USERNAME/.bashrc" # Install system dependencies -RUN apt update -RUN apt install -y curl wget gnupg python3 python-is-python3 python3-pip git \ +RUN apt-get update +RUN apt-get install -y curl wget gnupg python3 python-is-python3 python3-pip git \ build-essential tmux vim RUN python -m pip install \ diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index a4a2d37c2cb1..8ba9269ed8a4 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,11 +1,15 @@ { "dockerFile": "Dockerfile", - "postCreateCommand": "poetry install --extras \"simulation\"", - "extensions": ["ms-python.python"], - "settings": { - "files.watcherExclude": {}, - "search.exclude": {}, - "terminal.integrated.defaultProfile.linux": "bash" + "postCreateCommand": "sudo poetry install --extras \"simulation\"", + "customizations": { + "vscode": { + "settings": { + "files.watcherExclude": { }, + "search.exclude": { }, + "terminal.integrated.defaultProfile.linux": "bash" + }, + "extensions": [ "ms-python.python" ] + } }, "remoteUser": "flwr-vscode", "containerEnv": { diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a5eadadf8604..71a8aea59859 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -5,3 +5,9 @@ # Flower Baselines /baselines @jafermarq @tanertopal @danieljanes + +# Flower Examples +/examples @jafermarq @tanertopal @danieljanes + +# Changelog +/doc/source/ref-changelog.md @jafermarq @tanertopal @danieljanes diff --git a/.github/ISSUE_TEMPLATE/baseline_request.yml b/.github/ISSUE_TEMPLATE/baseline_request.yml index ec4b1e8a9898..49ae922a94ad 100644 --- a/.github/ISSUE_TEMPLATE/baseline_request.yml +++ b/.github/ISSUE_TEMPLATE/baseline_request.yml @@ -41,32 +41,22 @@ body: - [ ] Read the [`first contribution` doc](https://flower.dev/docs/first-time-contributors.html) - [ ] Complete the Flower tutorial - [ ] Read the Flower Baselines docs to get an overview: - - [ ] [https://flower.dev/docs/using-baselines.html](https://flower.dev/docs/using-baselines.html) - - [ ] [https://flower.dev/docs/contributing-baselines.html](https://flower.dev/docs/contributing-baselines.html) + - [ ] [How to use Flower Baselines](https://flower.dev/docs/baselines/how-to-use-baselines.html) + - [ ] [How to contribute a Flower Baseline](https://flower.dev/docs/baselines/how-to-contribute-baselines.html) - type: checkboxes attributes: label: Prepare - understand the scope options: - label: Read the paper linked above - - label: Create the directory structure in Flower Baselines (just the `__init__.py` files and a `README.md`) - - label: Before starting to write code, write down all of the specs of this experiment in a README (dataset, partitioning, model, number of clients, all hyperparameters, …) - - label: Open a draft PR + - label: Decide which experiments you'd like to reproduce. The more the better! + - label: Follow the steps outlined in [Add a new Flower Baseline](https://flower.dev/docs/baselines/how-to-contribute-baselines.html#add-a-new-flower-baseline). + - label: You can use as reference [other baselines](https://github.com/adap/flower/tree/main/baselines) that the community merged following those steps. - type: checkboxes attributes: - label: Implement - make it work + label: Verify your implementation options: - - label: Implement some form of dataset loading and partitioning in a separate `dataset.py` (doesn’t have to match the paper exactly) - - label: Implement the model in PyTorch - - label: Write a test that shows that the model has the number of parameters mentioned in the paper - - label: Implement the federated learning setup outlined in the paper, maybe starting with fewer clients - - label: Plot accuracy and loss - - label: Run it and check if the model starts to converge - - type: checkboxes - attributes: - label: Align - make it converge - options: - - label: Implement the exact data partitioning outlined in the paper - - label: Use the exact hyperparameters outlined in the paper - - label: Make it converge to roughly the same accuracy that the paper states - - label: Commit the final hyperparameters and plots - - label: Mark the PR as ready + - label: Follow the steps indicated in the `EXTENDED_README.md` that was created in your baseline directory + - label: Ensure your code reproduces the results for the experiments you chose + - label: Ensure your `README.md` is ready to be run by someone that is no familiar with your code. Are all step-by-step instructions clear? + - label: Ensure running the formatting and typing tests for your baseline runs without errors. + - label: Clone your repo on a new directory, follow the guide on your own `README.md` and verify everything runs. diff --git a/.github/actions/bootstrap/action.yml b/.github/actions/bootstrap/action.yml index 584ae2634d9e..bab5113bc567 100644 --- a/.github/actions/bootstrap/action.yml +++ b/.github/actions/bootstrap/action.yml @@ -4,7 +4,7 @@ inputs: python-version: description: "Version range or exact version of Python or PyPy to use, using SemVer's version range syntax." default: 3.8 - pip-version: + pip-version: description: "Version of pip to be installed using pip" default: 23.3.1 setuptools-version: @@ -13,6 +13,19 @@ inputs: poetry-version: description: "Version of poetry to be installed using pip" default: 1.5.1 +outputs: + python-version: + description: "Version range or exact version of Python or PyPy" + value: ${{ steps.versions.outputs.python-version }} + pip-version: + description: "Installed version of pip" + value: ${{ steps.versions.outputs.pip-version }} + setuptools-version: + description: "Installed version of setuptools" + value: ${{ steps.versions.outputs.setuptools-version }} + poetry-version: + description: "Installed version of poetry" + value: ${{ steps.versions.outputs.poetry-version }} runs: using: "composite" steps: @@ -27,3 +40,10 @@ runs: python -m pip install -U poetry==${{ inputs.poetry-version }} python -m poetry config virtualenvs.create false shell: bash + - id: versions + shell: bash + run: | + echo "python-version=$(echo ${{ inputs.python-version }})" >> $GITHUB_OUTPUT + echo "pip-version=$(echo ${{ inputs.pip-version }})" >> $GITHUB_OUTPUT + echo "setuptools-version=$(echo ${{ inputs.setuptools-version }})" >> $GITHUB_OUTPUT + echo "poetry-version=$(echo ${{ inputs.poetry-version }})" >> $GITHUB_OUTPUT diff --git a/.github/workflows/_docker-build.yml b/.github/workflows/_docker-build.yml new file mode 100644 index 000000000000..19dfc210bae6 --- /dev/null +++ b/.github/workflows/_docker-build.yml @@ -0,0 +1,144 @@ +name: Reusable docker server image build workflow + +on: + workflow_call: + inputs: + namespace-repository: + description: "The namespace and repository in the following format `namespace/repository` e.g. (flwr/base)." + required: true + type: string + file-dir: + description: "Path of the directory that contains the Dockerfile." + required: true + type: string + build-args: + description: "List of build-time variables." + required: false + type: string + tags: + description: "List of tags." + required: true + type: string + secrets: + dockerhub-user: + required: true + dockerhub-token: + required: true + outputs: + metadata: + description: "Metadata of the docker image." + value: ${{ jobs.build-manifest.outputs.metadata }} + +permissions: + contents: read + +# based on https://docs.docker.com/build/ci/github-actions/multi-platform/#distribute-build-across-multiple-runners +jobs: + build: + name: Build server image + runs-on: ubuntu-22.04 + timeout-minutes: 60 + outputs: + build-id: ${{ steps.build-id.outputs.id }} + strategy: + fail-fast: true + matrix: + platform: [ + # build-push action and qemu use different platform names + # therefore we create a map + { qemu: "", docker: "linux/amd64" }, + { qemu: "arm64", docker: "linux/arm64" }, + ] + steps: + - name: Create build id + id: build-id + shell: python + run: | + import hashlib + import os + + hash = hashlib.sha256('''${{ inputs.build-args }}'''.encode()) + with open(os.environ['GITHUB_OUTPUT'], 'a') as fh: + print(f"id={hash.hexdigest()}", file=fh) + + - name: Set up QEMU + if: matrix.platform.qemu != '' + uses: docker/setup-qemu-action@68827325e0b33c7199eb31dd4e31fbe9023e06e3 # v3.0.0 + with: + platforms: ${{ matrix.platform.qemu }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@31cebacef4805868f9ce9a0cb03ee36c32df2ac4 # v5.3.0 + with: + images: ${{ inputs.namespace-repository }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 + + - name: Login to Docker Hub + uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + with: + username: ${{ secrets.dockerhub-user }} + password: ${{ secrets.dockerhub-token }} + + - name: Build and push + id: build + uses: docker/build-push-action@4a13e500e55cf31b7a5d59a38ab2040ab0f42f56 # v5.1.0 + with: + platforms: ${{ matrix.platform.docker }} + context: "{{defaultContext}}:${{ inputs.file-dir }}" + build-args: ${{ inputs.build-args }} + outputs: type=image,name=${{ inputs.namespace-repository }},push-by-digest=true,name-canonical=true,push=true + + - name: Export digest + run: | + mkdir -p /tmp/digests + digest="${{ steps.build.outputs.digest }}" + touch "/tmp/digests/${digest#sha256:}" + + - name: Upload digest + uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3 + with: + name: digests-${{ steps.build-id.outputs.id }} + path: /tmp/digests/* + if-no-files-found: error + retention-days: 1 + + build-manifest: + name: Build and push docker manifest for all platforms + runs-on: ubuntu-22.04 + timeout-minutes: 10 + needs: build + outputs: + metadata: ${{ steps.meta.outputs.json }} + steps: + - name: Download digests + uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 + with: + name: digests-${{ needs.build.outputs.build-id }} + path: /tmp/digests + + - name: Docker meta + id: meta + uses: docker/metadata-action@31cebacef4805868f9ce9a0cb03ee36c32df2ac4 # v5.3.0 + with: + images: ${{ inputs.namespace-repository }} + tags: ${{ inputs.tags }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 + + - name: Login to Docker Hub + uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 + with: + username: ${{ secrets.dockerhub-user }} + password: ${{ secrets.dockerhub-token }} + + - name: Create manifest list and push + working-directory: /tmp/digests + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf '${{ inputs.namespace-repository }}@sha256:%s ' *) + - name: Inspect image + run: docker buildx imagetools inspect ${{ inputs.namespace-repository }}:${{ steps.meta.outputs.version }} diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml index ba11e1ee85e7..b08d2bb66863 100644 --- a/.github/workflows/android-release.yml +++ b/.github/workflows/android-release.yml @@ -16,7 +16,7 @@ jobs: working-directory: src/kotlin name: Release build and publish if: github.repository == 'adap/flower' - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Check out code uses: actions/checkout@v4 diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml index 7b8656497bf5..a1d918aa5b29 100644 --- a/.github/workflows/cpp.yml +++ b/.github/workflows/cpp.yml @@ -11,7 +11,7 @@ on: jobs: build_and_test: name: Build and test - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/docker-base.yml b/.github/workflows/docker-base.yml new file mode 100644 index 000000000000..fe276585a3bd --- /dev/null +++ b/.github/workflows/docker-base.yml @@ -0,0 +1,60 @@ +name: Build docker base image + +on: + push: + branches: ["main"] + paths: + - "src/docker/base/**" + - ".github/workflows/docker-base.yml" + # re-run if something chnages in the bootstrap action (e.g. version of the dependencies) + - ".github/actions/bootstrap/action.yml" + - ".github/workflows/_docker-build.yml" + +permissions: + contents: read + +env: + DEFAULT_UBUNTU: 22.04 + +jobs: + parameters: + name: Collect build parameters + runs-on: ubuntu-22.04 + timeout-minutes: 10 + outputs: + pip-version: ${{ steps.versions.outputs.pip-version }} + setuptools-version: ${{ steps.versions.outputs.setuptools-version }} + ubuntu-version: ${{ steps.versions.outputs.ubuntu-version }} + + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + + - uses: ./.github/actions/bootstrap + id: bootstrap + + - id: versions + run: | + echo "pip-version=${{ steps.bootstrap.outputs.pip-version }}" >> "$GITHUB_OUTPUT" + echo "setuptools-version=${{ steps.bootstrap.outputs.setuptools-version }}" >> "$GITHUB_OUTPUT" + echo "ubuntu-version=${{ env.DEFAULT_UBUNTU }}" >> "$GITHUB_OUTPUT" + + build-base-images: + name: Build images + uses: ./.github/workflows/_docker-build.yml + needs: parameters + strategy: + fail-fast: false + matrix: + python-version: ["3.8", "3.9", "3.10", "3.11"] + with: + namespace-repository: flwr/base + file-dir: src/docker/base + build-args: | + PYTHON_VERSION=${{ matrix.python-version }} + PIP_VERSION=${{ needs.parameters.outputs.pip-version }} + SETUPTOOLS_VERSION=${{ needs.parameters.outputs.setuptools-version }} + UBUNTU_VERSION=${{ needs.parameters.outputs.ubuntu-version }} + tags: py${{ matrix.python-version }}-ubuntu${{ needs.parameters.outputs.ubuntu-version }} + secrets: + dockerhub-user: ${{ secrets.DOCKERHUB_USERNAME }} + dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/docker-server.yml b/.github/workflows/docker-server.yml new file mode 100644 index 000000000000..f580a8e9a280 --- /dev/null +++ b/.github/workflows/docker-server.yml @@ -0,0 +1,50 @@ +name: Build docker server image + +on: + workflow_dispatch: + inputs: + flwr-version: + description: "Version of Flower e.g. (1.6.0)." + required: true + type: string + base-image-tag: + description: "The tag of the Flower base image." + required: false + type: string + default: "py3.11-ubuntu22.04" + +permissions: + contents: read + +jobs: + build-server-images: + name: Build images + uses: ./.github/workflows/_docker-build.yml + # run only on default branch when using it with workflow_dispatch + if: github.ref_name == github.event.repository.default_branch + with: + namespace-repository: flwr/server + file-dir: src/docker/server + build-args: | + FLWR_VERSION=${{ github.event.inputs.flwr-version }} + BASE_IMAGE_TAG=${{ github.event.inputs.base-image-tag }} + tags: | + ${{ github.event.inputs.flwr-version }}-${{ github.event.inputs.base-image-tag }} + ${{ github.event.inputs.flwr-version }} + latest + secrets: + dockerhub-user: ${{ secrets.DOCKERHUB_USERNAME }} + dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} + + summary: + name: Build images + runs-on: ubuntu-22.04 + needs: build-server-images + timeout-minutes: 10 + steps: + - run: | + echo "### Images" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + for IMAGE in $(echo ${{ toJson(needs.build-server-images.outputs.metadata) }} | jq -r '.tags[]' ); do + echo "- $IMAGE" >> $GITHUB_STEP_SUMMARY + done diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 52944ffecf70..94f3495a20ef 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -23,6 +23,8 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 + - name: Check copyright line + run: ./dev/test-copyright.sh - name: Bootstrap uses: ./.github/actions/bootstrap - name: Install pandoc diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 6189794e8f69..ed7535409fa4 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -30,12 +30,12 @@ jobs: - name: Test wheel run: ./dev/test-wheel.sh - name: Upload wheel - if: ${{ github.repository == 'adap/flower' && !github.event.pull_request.head.repo.fork }} + if: ${{ github.repository == 'adap/flower' && !github.event.pull_request.head.repo.fork && github.actor != 'dependabot[bot]' }} id: upload env: - AWS_DEFAULT_REGION: ${{ secrets. AWS_DEFAULT_REGION }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets. AWS_SECRET_ACCESS_KEY }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} run: | cd ./dist echo "WHL_PATH=$(ls *.whl)" >> "$GITHUB_OUTPUT" @@ -60,6 +60,8 @@ jobs: include: - directory: bare + - directory: bare-https + - directory: jax - directory: pytorch @@ -71,7 +73,7 @@ jobs: dataset: | import tensorflow as tf tf.keras.datasets.cifar10.load_data() - + - directory: tabnet dataset: | import tensorflow_datasets as tfds @@ -81,7 +83,7 @@ jobs: dataset: | from torchvision.datasets import CIFAR10 CIFAR10('./data', download=True) - + - directory: pytorch-lightning dataset: | from torchvision.datasets import MNIST @@ -100,7 +102,7 @@ jobs: - directory: fastai dataset: | from fastai.vision.all import untar_data, URLs - untar_data(URLs.MNIST) + untar_data(URLs.MNIST) - directory: pandas dataset: | @@ -135,7 +137,7 @@ jobs: - name: Run virtual client test run: python simulation.py - name: Run driver test - run: ./../test_driver.sh + run: ./../test_driver.sh "${{ matrix.directory }}" strategies: runs-on: ubuntu-22.04 diff --git a/.github/workflows/framework-release.yml b/.github/workflows/framework-release.yml index 2d2b7d8a4c4f..eab15a51d217 100644 --- a/.github/workflows/framework-release.yml +++ b/.github/workflows/framework-release.yml @@ -9,7 +9,7 @@ jobs: publish: if: ${{ github.repository == 'adap/flower' }} name: Publish draft - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Checkout uses: actions/checkout@v4 @@ -53,7 +53,7 @@ jobs: cat body.md - name: Release - uses: softprops/action-gh-release@de2c0eb + uses: softprops/action-gh-release@v1 with: body_path: ./body.md draft: true diff --git a/.github/workflows/update-pr.yml b/.github/workflows/update-pr.yml index 5ffcf0c13694..64b16aeabebf 100644 --- a/.github/workflows/update-pr.yml +++ b/.github/workflows/update-pr.yml @@ -6,10 +6,10 @@ on: - 'main' jobs: autoupdate: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - name: Automatically update mergeable PRs - uses: adRise/update-pr-branch@v0.7.0 + uses: adRise/update-pr-branch@cd305ecbd76bf63056c9400ce2c725293fc3e0c0 # v0.7.0 with: token: ${{ secrets.FLWRMACHINE_TOKEN }} base: 'main' diff --git a/README.md b/README.md index 002d16066e78..b8b62e8c0c43 100644 --- a/README.md +++ b/README.md @@ -91,20 +91,26 @@ Stay tuned, more tutorials are coming soon. Topics include **Privacy and Securit ## Flower Baselines -Flower Baselines is a collection of community-contributed experiments that reproduce the experiments performed in popular federated learning publications. Researchers can build on Flower Baselines to quickly evaluate new ideas: - -- [FedAvg](https://arxiv.org/abs/1602.05629): - - [MNIST](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedavg_mnist) -- [FedProx](https://arxiv.org/abs/1812.06127): - - [MNIST](https://github.com/adap/flower/tree/main/baselines/fedprox/) -- [FedBN: Federated Learning on non-IID Features via Local Batch Normalization](https://arxiv.org/abs/2102.07623): - - [Convergence Rate](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedbn/convergence_rate) -- [Adaptive Federated Optimization](https://arxiv.org/abs/2003.00295): - - [CIFAR-10/100](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/adaptive_federated_optimization) - -Check the Flower documentation to learn more: [Using Baselines](https://flower.dev/docs/baselines/how-to-use-baselines.html) - -The Flower community loves contributions! Make your work more visible and enable others to build on it by contributing it as a baseline: [Contributing Baselines](https://flower.dev/docs/baselines/how-to-contribute-baselines.html) +Flower Baselines is a collection of community-contributed projects that reproduce the experiments performed in popular federated learning publications. Researchers can build on Flower Baselines to quickly evaluate new ideas. The Flower community loves contributions! Make your work more visible and enable others to build on it by contributing it as a baseline! + +- [DASHA](https://github.com/adap/flower/tree/main/baselines/dasha) +- [DepthFL](https://github.com/adap/flower/tree/main/baselines/depthfl) +- [FedBN](https://github.com/adap/flower/tree/main/baselines/fedbn) +- [FedMeta](https://github.com/adap/flower/tree/main/baselines/fedmeta) +- [FedMLB](https://github.com/adap/flower/tree/main/baselines/fedmlb) +- [FedPer](https://github.com/adap/flower/tree/main/baselines/fedper) +- [FedProx](https://github.com/adap/flower/tree/main/baselines/fedprox) +- [FedWav2vec2](https://github.com/adap/flower/tree/main/baselines/fedwav2vec2) +- [FjORD](https://github.com/adap/flower/tree/main/baselines/fjord) +- [MOON](https://github.com/adap/flower/tree/main/baselines/moon) +- [niid-Bench](https://github.com/adap/flower/tree/main/baselines/niid_bench) +- [TAMUNA](https://github.com/adap/flower/tree/main/baselines/tamuna) +- [FedAvg](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedavg_mnist) +- [FedOpt](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/adaptive_federated_optimization) + +Please refer to the [Flower Baselines Documentation](https://flower.dev/docs/baselines/) for a detailed categorization of baselines and for additional info including: +* [How to use Flower Baselines](https://flower.dev/docs/baselines/how-to-use-baselines.html) +* [How to contribute a new Flower Baseline](https://flower.dev/docs/baselines/how-to-contribute-baselines.html) ## Flower Usage Examples diff --git a/baselines/README.md b/baselines/README.md index 3b30ff1a9eaf..a18c0553b2b4 100644 --- a/baselines/README.md +++ b/baselines/README.md @@ -1,14 +1,14 @@ # Flower Baselines -> We are changing the way we structure the Flower baselines. While we complete the transition to the new format, you can still find the existing baselines in the `flwr_baselines` directory. Currently, you can make use of baselines for [FedAvg](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedavg_mnist), [FedProx](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedprox_mnist), [FedOpt](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/adaptive_federated_optimization), [FedBN](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedbn/convergence_rate), and [LEAF-FEMNIST](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/leaf/femnist). +> We are changing the way we structure the Flower baselines. While we complete the transition to the new format, you can still find the existing baselines in the `flwr_baselines` directory. Currently, you can make use of baselines for [FedAvg](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/fedavg_mnist), [FedOpt](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/adaptive_federated_optimization), and [LEAF-FEMNIST](https://github.com/adap/flower/tree/main/baselines/flwr_baselines/flwr_baselines/publications/leaf/femnist). > The documentation below has been updated to reflect the new way of using Flower baselines. ## Structure -Each baseline in this directory is fully self-contained in terms of source code it its own directory. In addition, each baseline uses its very own Python environment as designed by the contributors of such baseline in order to replicate the experiments in the paper. Each baseline directory contains the following structure: +Each baseline in this directory is fully self-contained in terms of source code in its own directory. In addition, each baseline uses its very own Python environment as designed by the contributors of such baseline in order to replicate the experiments in the paper. Each baseline directory contains the following structure: ```bash baselines// diff --git a/baselines/baseline_template/README.md b/baselines/baseline_template/README.md index 682952717426..ee6e1e96976f 100644 --- a/baselines/baseline_template/README.md +++ b/baselines/baseline_template/README.md @@ -1,11 +1,11 @@ --- 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 +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). Do not use "" +dataset: [dataset1, dataset2] # list of datasets you include in your baseline. Do not use "" --- -# :warning:*_Title of 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. @@ -15,33 +15,33 @@ dataset: [dataset1, dataset2] # list of datasets you include in your baseline > :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._* +**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_* +**Authors:** :warning: *_list authors of the paper_* -****Abstract:**** :warning: *_add here the abstract of the paper you are implementing_* +**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 …”_* +**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)._* +**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?_* +**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_* +**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_* +**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._* +**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._* +**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._* +**Training Hyperparameters:** :warning: *_Include a table with all the main hyperparameters in your baseline. Please show them with their default value._* ## Environment Setup diff --git a/baselines/baseline_template/baseline_template/main.py b/baselines/baseline_template/baseline_template/main.py index 795800c64e21..25ae1bec6a10 100644 --- a/baselines/baseline_template/baseline_template/main.py +++ b/baselines/baseline_template/baseline_template/main.py @@ -51,3 +51,7 @@ def main(cfg: DictConfig) -> None: # Hydra will generate for you a directory each time you run the code. You # can retrieve the path to that directory with this: # save_path = HydraConfig.get().runtime.output_dir + + +if __name__ == "__main__": + main() diff --git a/baselines/doc/source/conf.py b/baselines/doc/source/conf.py index dd43080f299e..dabd421c61cf 100644 --- a/baselines/doc/source/conf.py +++ b/baselines/doc/source/conf.py @@ -14,6 +14,7 @@ # ============================================================================== +import datetime import os import sys from sphinx.application import ConfigError @@ -32,11 +33,11 @@ # -- Project information ----------------------------------------------------- project = "Flower" -copyright = "2022 Flower Labs GmbH" +copyright = f"{datetime.date.today().year} Flower Labs GmbH" author = "The Flower Authors" # The full version, including alpha/beta/rc tags -release = "1.6.0" +release = "1.7.0" # -- General configuration --------------------------------------------------- diff --git a/baselines/doc/source/how-to-use-baselines.rst b/baselines/doc/source/how-to-use-baselines.rst index b89c17b17a98..ed47438ad5a9 100644 --- a/baselines/doc/source/how-to-use-baselines.rst +++ b/baselines/doc/source/how-to-use-baselines.rst @@ -3,7 +3,7 @@ Use Baselines .. warning:: We are changing the way we structure the Flower baselines. While we complete the transition to the new format, you can still find the existing baselines and use them: `baselines (old) `_. - Currently, you can make use of baselines for `FedAvg `_, `FedProx `_, `FedOpt `_, `FedBN `_, and `LEAF-FEMNIST `_. + Currently, you can make use of baselines for `FedAvg `_, `FedOpt `_, and `LEAF-FEMNIST `_. The documentation below has been updated to reflect the new way of using Flower baselines. diff --git a/baselines/fedbn/.gitignore b/baselines/fedbn/.gitignore new file mode 100644 index 000000000000..de1e160448e5 --- /dev/null +++ b/baselines/fedbn/.gitignore @@ -0,0 +1,2 @@ +outputs/ +multirun/ diff --git a/baselines/fedbn/LICENSE b/baselines/fedbn/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/baselines/fedbn/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/fedbn/README.md b/baselines/fedbn/README.md new file mode 100644 index 000000000000..4b271bd49851 --- /dev/null +++ b/baselines/fedbn/README.md @@ -0,0 +1,159 @@ +--- +title: "FedBN: Federated Learning on Non-IID Features via Local Batch Normalization" +url: https://arxiv.org/abs/2102.07623 +labels: [data heterogeneity, feature shift, cross-silo] +dataset: [MNIST, MNIST-M, SVHN, USPS, SynthDigits] +--- + +# FedBN: Federated Learning on Non-IID Features via Local Batch Normalization + +> 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. + + +**Paper:** [arxiv.org/abs/2102.07623](https://arxiv.org/abs/2102.07623) + +**Authors:** Xiaoxiao Li, Meirui Jiang, Xiaofei Zhang, Michael Kamp, Qi Dou + +**Abstract:** The emerging paradigm of federated learning (FL) strives to enable collaborative training of deep models on the network edge without centrally aggregating raw data and hence improving data privacy. In most cases, the assumption of independent and identically distributed samples across local clients does not hold for federated learning setups. Under this setting, neural network training performance may vary significantly according to the data distribution and even hurt training convergence. Most of the previous work has focused on a difference in the distribution of labels or client shifts. Unlike those settings, we address an important problem of FL, e.g., different scanners/sensors in medical imaging, different scenery distribution in autonomous driving (highway vs. city), where local clients store examples with different distributions compared to other clients, which we denote as feature shift non-iid. In this work, we propose an effective method that uses local batch normalization to alleviate the feature shift before averaging models. The resulting scheme, called FedBN, outperforms both classical FedAvg, as well as the state-of-the-art for non-iid data (FedProx) on our extensive experiments. These empirical results are supported by a convergence analysis that shows in a simplified setting that FedBN has a faster convergence rate than FedAvg. + + +## About this baseline + +**What’s implemented:** Figure 3 in the paper: convergence in training loss comparing `FedBN` to `FedAvg` for five datasets. + +**Datasets:** Vision datasets including digits 0-9. These datasets are: [MNIST](https://ieeexplore.ieee.org/document/726791), [MNIST-M](https://arxiv.org/pdf/1505.07818.pdf), [SVHN](http://ufldl.stanford.edu/housenumbers/nips2011_housenumbers.pdf), [USPS](https://ieeexplore.ieee.org/document/291440), and [SynthDigits](https://arxiv.org/pdf/1505.07818.pdf). + +**Hardware Setup:** Using the default configurations, any machine with 8 CPU cores should be capable to run 100 rounds of FedAvg or FedBN in under 5 minutes. Therefore a GPU is not needed if you stick to the small model used in the paper and you limit clients to use a 10% of the data in each dataset (these are the default settings) + +**Contributors:** Meirui Jiang, Maria Boerner, Javier Fernandez-Marques + + +## Experimental Setup + +**Task:** Image classification + +**Model:** A six-layer CNN with 14,219,210 parameters following the structure described in appendix D.2. + +**Dataset:** This baseline makes use of the pre-processed partitions created and open source by the authors of the FedBN paper. You can read more about how those were created [here](https://github.com/med-air/FedBN). Follow the steps below in the `Environment Setup` section to download them. + + +A more detailed explanation of the datasets is given in the following table. + +| | MNIST | MNIST-M | SVHN | USPS | SynthDigits | +|--- |--- |--- |--- |--- |--- | +| data type| handwritten digits| MNIST modification randomly colored with colored patches| Street view house numbers | handwritten digits from envelopes by the U.S. Postal Service | Syntehtic digits Windows TM font varying the orientation, blur and stroke colors | +| color | greyscale | RGB | RGB | greyscale | RGB | +| pixelsize | 28x28 | 28 x 28 | 32 x32 | 16 x16 | 32 x32 | +| labels | 0-9 | 0-9 | 1-10 | 0-9 | 1-10 | +| number of trainset | 60.000 | 60.000 | 73.257 | 9,298 | 50.000 | +| number of testset| 10.000 | 10.000 | 26.032 | - | - | +| image shape | (28,28) | (28,28,3) | (32,32,3) | (16,16) | (32,32,3) | + + +**Training Hyperparameters:** By default (i.e. if you don't override anything in the config) these main hyperparameters used are shown in the table below. For a complete list of hyperparameters, please refer to the config files in `fedbn/conf`. + +| Description | Value | +| ----------- | ----- | +| rounds | 10 | +| num_clients | 5 | +| strategy_fraction_fit | 1.0 | +| strategy.fraction_evaluate | 0.0 | +| training samples per client| 743 | +| client.l_r | 10E-2 | +| local epochs | 1 | +| loss | cross entropy loss | +| optimizer | SGD | +| client_resources.num_cpu | 2 | +| client_resources.num_gpus | 0.0 | + +## Environment Setup + +To construct the Python environment, simply run: + +```bash +# Set directory to use python 3.10 (install with `pyenv install ` if you don't have it) +pyenv local 3.10.6 + +# Tell poetry to use python3.10 +poetry env use 3.10.6 + +# Install +poetry install +``` + +Before running the experiments you'll need to download the five datasets for this baseline. We'll be using the pre-processed datasets created by the `FedBN` authors. Download the dataset from [here](https://mycuhk-my.sharepoint.com/:u:/g/personal/1155149226_link_cuhk_edu_hk/EV1YgHfFC4RKjw06NL4JMdgBMU21CegM12SpXrSmGjt3XA?e=XK2rFs) and move the file into a new directory named `data`. +```bash +mkdir data +mv data/ + +# now uncompress the zipfile +cd data && unzip digit_dataset.zip +cd data .. +``` + +## Running the Experiments + +First, activate your environment via `poetry shell`. The commands below show how to run the experiments and modify some of its key hyperparameters via the cli. Each time you run an experiment, the log and results will be stored inside `outputs//