Skip to content

Federated Learning

This section shows you a simple, complete application to run a Federated Learning (FL) experiment with the dAIEdge-VLab Python API. If you are not yet familiar with the FL concepts and classes used below (FlConfig, FlModel, ClientConfig, …), have a look at the Federated Learning section first.

What does this application do ?

In this application example, we train a small CNN to recognize handwritten digits (MNIST) across 3 heterogeneous clients, without ever centralizing their data. Each client only holds a private, non-overlapping subset of the dataset. The dAIEdge-VLab orchestrates the rounds : it sends the current global model to the clients, the clients train it locally, and their updates are aggregated into a new global model, which is evaluated on a server-side evaluation set.

    sequenceDiagram
    participant User
    participant dAIEdge-VLab
    participant Client 0..2 (rpi5)
    User->>User: Prepare the model artifacts and the client/server datasets
    User->>dAIEdge-VLab: FlExperiment
    loop For 10 rounds
        dAIEdge-VLab->>Client 0..2 (rpi5): Global model
        Client 0..2 (rpi5)->>Client 0..2 (rpi5): Train locally on its own MNIST partition
        Client 0..2 (rpi5)->>dAIEdge-VLab: Updated weights, metrics
        dAIEdge-VLab->>dAIEdge-VLab: Aggregate & evaluate the global model
    end
    dAIEdge-VLab->>User: Trained global model, report, logs
    User->>User: Track progress with the FL Viewer
  

Main actions :

  • Split the MNIST dataset into 3 client partitions and a server evaluation set
  • Prepare an ONNX Runtime Training model
  • Describe the FL experiment (server strategy, clients, objectives)
  • Start the experiment and track it live with the FL Viewer
  • Retrieve and evaluate the trained global model

Prepare the environment

The client/server datasets and the initial model are provided ready to use below, so running this example only requires a Python 3.11 environment with daiedge-vlab and numpy installed, no torch or onnxruntime-training needed. Use the step-by-step user guide to install and setup the daiedge-vlab package. Use the following requirements.txt file to install the other dependencies :

pip install -r requirements.txt

Then, create your setup.yaml file with your dAIEdge-VLab credentials, as described in the step-by-step user guide.

Get the model and the datasets

To keep this example self-contained, the client/server datasets and the initial (untrained) model are provided ready to use :

Unzip fl_dataset_mnist.zip in your working directory. It contains a fl_dataset_mnist folder with one sub-folder per client (client_0, client_1, client_2) and a server folder, each holding pre-processed .bin files, following the same naming convention described in Federated Learning. artifacts-mnist-fl.zip is the initial ORT training artifacts bundle for the model described below, ready to be used as model_path in FlModel.

Info : You do not need to run the data/model preparation script below to follow this example, it is only provided so you understand how the downloadable files were built and can adapt it to your own data and model.

How the model and datasets were prepared

Regenerating fl_dataset_mnist.zip and artifacts-mnist-fl.zip (or adapting the script to your own data/model) additionally requires torch, torchvision, onnx and onnxruntime-training. This script only needs the CPU, but a plain pip install torch pulls a large CUDA-enabled build by default, so install torch/torchvision from the CPU wheel index first, then the rest of the dependencies from prepare_data_requirements.txt :

pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
pip install -r prepare_data_requirements.txt

The model is the same CNN architecture used in the ORT On-Device Training example : two convolutional blocks followed by two dense layers, with a Linear(128, 10) classifier head.

import torch.nn as nn
import torch.nn.functional as F

class CNNModel(nn.Module):
    def __init__(self):
        super(CNNModel, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
        self.pool1 = nn.MaxPool2d(kernel_size=2)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
        self.pool2 = nn.MaxPool2d(kernel_size=2)
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(64 * 5 * 5, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool1(x)
        x = F.relu(self.conv2(x))
        x = self.pool2(x)
        x = self.flatten(x)
        x = F.relu(self.fc1(x))
        x = F.softmax(self.fc2(x), dim=1)
        return x

It is exported to ONNX and converted to ORT training artifacts exactly as described in Generates training artifacts, then zipped into artifacts-mnist-fl.zip.

The MNIST dataset is randomly split into 3 non-overlapping client partitions (800 train / 200 test samples each) and a separate 400-sample server evaluation set, saved as .bin files following the client_{id}_train_input_<tag>.bin naming convention expected by the FL tools :

import numpy as np
import torchvision.datasets as datasets

NB_CLIENTS = 3
TRAIN_PER_CLIENT = 800
TEST_PER_CLIENT = 200
SERVER_EVAL = 400

train_dataset = datasets.MNIST(root="./mnist_raw", train=True, download=True, transform=None)
test_dataset = datasets.MNIST(root="./mnist_raw", train=False, download=True, transform=None)

x_train_full = (np.stack([np.array(img) for img, _ in train_dataset]).astype(np.float32) / 255.0)[:, None, :, :]
y_train_full = np.array([label for _, label in train_dataset]).astype(np.int64)
x_test_full = (np.stack([np.array(img) for img, _ in test_dataset]).astype(np.float32) / 255.0)[:, None, :, :]
y_test_full = np.array([label for _, label in test_dataset]).astype(np.int64)

# Client i gets a distinct slice of the (shuffled) train/test sets ...
# ... and the server gets a separate slice of the test set.

The full, runnable preparation script is available for download below : prepare_data.py.

Build and run the FL experiment

Load the client and server datasets

import os
import numpy as np

DATA_DIR = "./fl_dataset_mnist"

def load_data_client(id):
    client_dir = os.path.join(DATA_DIR, f"client_{id}")
    train_input_file  = [f for f in os.listdir(client_dir) if f.startswith(f"client_{id}_train_input_")][0]
    train_target_file = [f for f in os.listdir(client_dir) if f.startswith(f"client_{id}_train_target_")][0]
    test_input_file    = [f for f in os.listdir(client_dir) if f.startswith(f"client_{id}_test_input_")][0]
    test_target_file   = [f for f in os.listdir(client_dir) if f.startswith(f"client_{id}_test_target_")][0]

    dataset_id = train_input_file.split("_")[-1].replace(".bin", "")

    train_inputs  = np.fromfile(os.path.join(client_dir, train_input_file),  dtype=np.float32).reshape(-1, 1, 28, 28)
    train_targets = np.fromfile(os.path.join(client_dir, train_target_file), dtype=np.int64)
    test_inputs   = np.fromfile(os.path.join(client_dir, test_input_file),   dtype=np.float32).reshape(-1, 1, 28, 28)
    test_targets  = np.fromfile(os.path.join(client_dir, test_target_file),  dtype=np.int64)
    return train_inputs, train_targets, test_inputs, test_targets, dataset_id


def load_data_server():
    server_dir = os.path.join(DATA_DIR, "server")
    eval_input_file  = [f for f in os.listdir(server_dir) if f.startswith("server_eval_input_")][0]
    eval_target_file = [f for f in os.listdir(server_dir) if f.startswith("server_eval_target_")][0]

    eval_inputs  = np.fromfile(os.path.join(server_dir, eval_input_file),  dtype=np.float32).reshape(-1, 1, 28, 28)
    eval_targets = np.fromfile(os.path.join(server_dir, eval_target_file), dtype=np.int64)
    return eval_inputs, eval_targets

Configure the server strategy

We use RowWiseClassFedAvg to aggregate the classifier layer (Linear(128, 10), hence classifier_shape_hint=(10, 128)), a single global model (Single), all 3 clients selected at each round (All), and an adaptive number of local epochs (AdaptiveEpochs) :

from daiedge_vlab import dAIEdgeVLabAPI
from daiedge_vlab.fl import *

NUM_CLASSES = 10

eval_inputs, eval_targets = load_data_server()
eval_dataset = ServerDataset((eval_inputs, eval_targets), "server_eval_mnist")

fl_config = FlConfig(
    rounds=10,
    aggregator="RowWiseClassFedAvg",
    model_controller="Single",
    selection_strategy="All",
    client_config_provider="AdaptiveEpochs",
    server_dataset=eval_dataset,
    round_timeout_s=180
)

fl_config.set_min_clients(min_fit=3, min_available=3, min_eval=1)

fl_config.add_parameters_aggregator(
    eta=0.01,
    beta_1=0.9,
    beta_2=0.99,
    num_classes=NUM_CLASSES,
    classifier_shape_hint=(NUM_CLASSES, 128),
    ema_tau=0.0,
    ema_alpha_max=1.0,
)

fl_config.add_parameters_config_provider(
    base_epochs=1,
    min_epochs=1,
    max_epochs=5,
    target_round_time_s=30,
    sensitivity=2.5
)

Define the model and the experiment container

fl_experiment = FlExperiment(
    fl_model=FlModel(
        runtime="ort",
        model_path="./artifacts-mnist-fl.zip",
        input_shape=(1, 28, 28),
        output_shape=(NUM_CLASSES,),
    ),
    fl_config=fl_config,
    output_path="./fl_experiment_mnist/"
)

Add the 3 clients

training_config = TrainingConfig(
    epochs=1,
    batch_size=32,
    learning_rate=0.001,
)

for client_id, target in [(0, "rpi5"), (1, "rpi5"), (2, "rpi5")]:
    train_inputs, train_targets, test_inputs, test_targets, dataset_id = load_data_client(client_id)
    dataset = ClientDataset(
        (train_inputs, train_targets),
        (test_inputs, test_targets),
        dataset_id
    )

    client_config = ClientConfig(
        target=target,
        dataset=dataset,
        training_config=training_config,
    )

    fl_experiment.add_client(client_config)

Add experiment objectives

fl_experiment.add_experiment_objective(FLTargetAccuracyObjective(target_accuracy=0.90))
fl_experiment.add_experiment_objective(FLTargetAccuracyObjective(target_accuracy=0.80))
fl_experiment.add_experiment_objective(FLTargetLossObjective(target_loss=0.3))

Start the experiment

api = dAIEdgeVLabAPI("setup.yaml", auto_refresh=True)

id = api.startFLExperiment(fl_experiment)
print(f"Federated Learning Experiment started with ID: {id}")

# save_path must exist beforehand, the client does not create it for you
RESULTS_DIR = "./results/"
os.makedirs(RESULTS_DIR, exist_ok=True)

# Blocking method - wait for the results
result = api.waitFLExperimentResult(id, save_path=RESULTS_DIR, verbose=True)
print("Experiment result:", result)
Info : Once the experiment is started, go to https://vlab.daiedge.eu/fl-viewer/ and paste the printed experiment ID to follow the rounds, the global model metrics and the per-client status live.

Expected output

Once the experiment finishes, result and the ./results/ folder contain the report, the logs and the final trained global model. You should see the training and evaluation loss decrease round after round in the FL Viewer, as the 3 clients collaboratively improve the shared digit classifier without ever sharing their raw MNIST partitions.

Downloads

  • requirements.txt : the Python dependencies to run main.py (daiedge-vlab and numpy only).
  • fl_dataset_mnist.zip : the ready-to-use client and server datasets.
  • artifacts-mnist-fl.zip : the ready-to-use initial ORT training artifacts (the “model”).
  • main.py : the full script that builds and starts the FL experiment described on this page.
  • prepare_data.py : the script used to build the two files above (optional, for reference).
  • prepare_data_requirements.txt : the extra dependencies needed only if you run prepare_data.py yourself.

To run the full example, unzip fl_dataset_mnist.zip and place artifacts-mnist-fl.zip (unmodified, it is used directly as the model file) next to main.py, fill your setup.yaml, and run :

python main.py