Skip to content

Federated Learning

This section describes how to use the daiedge-vlab Python client to declaratively describe and run Federated Learning (FL) experiments on the dAIEdge-VLab platform.

What is a Federated Learning experiment ?

A Federated Learning experiment trains a single global model across several heterogeneous edge devices (the clients) without centralizing their data. At each round, the server sends the current global model to the participating clients, the clients train it locally on their own dataset, and the server aggregates the resulting updates into a new global model. This process is repeated for a given number of rounds, while the global model is regularly evaluated on a server-side evaluation dataset.

The daiedge-vlab package provides a set of Python classes, available under daiedge_vlab.fl, to describe this kind of experiment : the model, the server strategy, the clients (datasets, training parameters, target hardware) and, optionally, time-varying client behaviors (battery level, connectivity issues, …). This description is then submitted to the dAIEdge-VLab, which takes care of orchestrating the clients and running the experiment.

The following diagram shows the pipeline of a Federated Learning experiment :

    sequenceDiagram
    participant User
    participant dAIEdge-VLab
    participant Clients
    User->>User: Prepare model, client datasets, server evaluation dataset
    User->>User: Describe FlModel, FlConfig, ClientConfig(s), objectives
    User->>dAIEdge-VLab: FlExperiment
    loop For each round
        dAIEdge-VLab->>Clients: Global model, per-client training config
        Clients->>Clients: Train locally on their own dataset
        Clients->>dAIEdge-VLab: Updated weights, metrics
        dAIEdge-VLab->>dAIEdge-VLab: Aggregate the client updates
        dAIEdge-VLab->>dAIEdge-VLab: Evaluate the global model
    end
    dAIEdge-VLab->>User: Trained global model, report, logs
    User->>User: Track progress with the FL Viewer
  

Main actions :

  • Prepare a training and evaluation dataset for each client, and an evaluation dataset for the server
  • Prepare a trainable model
  • Describe the server strategy and the participating clients
  • Optionally, describe experiment objectives and time-varying client behaviors
  • Start the experiment on the dAIEdge-VLab
  • Follow its progress with the FL Viewer
  • Retrieve the trained global model, the report and the logs

Prepare the environment

For a Federated Learning experiment you will need a Python 3.11 environment with daiedge-vlab, numpy and, if you use ort as runtime, onnxruntime-training, torch and torchvision installed. Use the step-by-step user guide to install and setup the daiedge-vlab package.

pip install daiedge-vlab numpy onnxruntime-training torch torchvision

All the Federated Learning classes are available from the daiedge_vlab.fl submodule :

from daiedge_vlab import dAIEdgeVLabAPI
from daiedge_vlab.fl import *
Info : Only the ort (ONNX Runtime Training) runtime is currently supported for Federated Learning experiments. The model artifacts are prepared exactly the same way as for the TYPE3 - On Device Training benchmark : export your model to ONNX, generate the training artifacts with onnxruntime.training.artifacts, and zip them into a single archive (e.g. artifacts.zip).

Core concepts

A Federated Learning experiment is described by assembling a small number of objects. The typical usage follows this hierarchy :

  1. Prepare the trainable model and define it with FlModel.
  2. Prepare the datasets and wrap them with ServerDataset and ClientDataset.
  3. Create the server strategy with FlConfig.
  4. Create the experiment container with FlExperiment.
  5. Add one or more ClientConfig objects, each built from a TrainingConfig.
  6. Optionally, add experiment objectives.
  7. Start the experiment with the dAIEdgeVLabAPI.

Datasets: ServerDataset and ClientDataset

The dataset wrapper classes take pre-processed numpy.ndarray objects as input. The dAIEdge-VLab does not perform any data transformation : normalization, reshaping or class filtering must be done by the user beforehand, exactly as described in Provide a Dataset.

  • ServerDataset(data, dataset_id) : used exclusively for server-side evaluation of the global model. It only needs an evaluation set (x_eval, y_eval) and is passed to FlConfig(server_dataset=...).
  • ClientDataset(train_data, test_data, dataset_id) : used for client-side training and evaluation. It wraps both a train set (x_train, y_train) and a test set (x_test, y_test). Each ClientConfig references exactly one ClientDataset.

Both wrappers take a dataset_id used to track the provenance of the data, and are stored on disk when the experiment is exported/started.

Server Configuration: FlConfig

FlConfig defines the FL strategy and the server-side parameters :

  • rounds : the total number of FL rounds.
  • aggregator : the aggregation policy (see below).
  • model_controller : the global model split policy (see below).
  • selection_strategy : the client selection policy (see below).
  • client_config_provider : the client configuration policy (see below).
  • server_dataset : the ServerDataset used to evaluate the global model.
  • round_timeout_s : the per-round timeout, in seconds.
fl_config = FlConfig(
    rounds=20,
    aggregator="RowWiseClassFedAvg",
    model_controller="Single",
    selection_strategy="All",
    client_config_provider="AdaptiveEpochs",
    server_dataset=eval_dataset,
    round_timeout_s=300
)

The minimum number of clients required to fit and evaluate a round is set separately :

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

Client selection policies

  • All : select all available clients at each round.
  • BatteryAware : prioritize clients with sufficient battery to complete the round.
  • MaxTimeRoundSelector : prioritize clients that can complete the round within a given time limit.
  • GreenEnergyAware : prioritize clients powered by renewable energy sources.

Global model split policies

  • Single : no model splitting, a single global model is trained by all clients.
  • ModkMeanSplit : clients are clustered into k groups based on their dataset distribution (k-means), each group trains a separate model.
  • PerClients : each client trains its own model, no aggregation is performed on the server.

Client configuration policies

  • None : the server does not adapt the client-side training configuration.
  • AdaptiveEpochs : dynamically adjusts the number of local epochs of each client based on their average round time, so that all clients take approximately the same time to complete a round.
  • ReducedEpochsBattery : reduces the number of local epochs for clients with low battery to conserve power.

Aggregator policies

  • Any Flower built-in aggregator (e.g. FedAvg, FedAvgM, FedOpt with the Adam, SGD or Yogi optimizers, …).
  • RowWiseClassFedAvg : class-based weighted averaging of the classifier layer, where each client contributes to the global model proportionally to its representation in the clients’ datasets.

Parameter blocks

Each policy above can take extra hyperparameters through one of the following methods :

  • add_parameters_aggregator(...) : hyperparameters of the aggregation algorithm (e.g. eta, beta_1, beta_2 for FedOpt-like optimizers, num_classes and classifier_shape_hint for RowWiseClassFedAvg).
  • add_parameters_selector(...) : parameters of the client selector (e.g. battery_threshold, time_fit_threshold, time_eval_threshold, start_at_round).
  • add_parameters_model_controller(...) : parameters of the model split policy (e.g. the number of clusters for ModkMeanSplit).
  • add_parameters_config_provider(...) : parameters of the client configuration policy (e.g. base_epochs, min_epochs, max_epochs, target_round_time_s, sensitivity).
fl_config.add_parameters_selector(
    battery_threshold=30.0,
    time_fit_threshold=30.0,
    time_eval_threshold=20.0,
    start_at_round=3,
)

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

fl_config.add_parameters_config_provider(
    base_epochs=2,
    min_epochs=1,
    max_epochs=10,
    target_round_time_s=45,
    sensitivity=2.5
)

Model description: FlModel

FlModel describes the trainable model and its expected input/output shapes :

  • runtime : the execution backend of the model (currently only ort is supported).
  • model_path : path to the model/artifacts bundle (see Prepare the environment).
  • input_shape, output_shape : the expected input and output tensor shapes.
fl_model = FlModel(
    runtime="ort",
    model_path="./artifacts.zip",
    input_shape=(3, 224, 224),
    output_shape=(40,),
)

Client Training Description: TrainingConfig

TrainingConfig stores the baseline learning parameters used by a client : epochs, batch_size and learning_rate. It is embedded inside a ClientConfig, and the same instance can be shared by several clients if they share the same baseline training parameters.

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

Client Configuration: ClientConfig

ClientConfig describes a single participating device :

  • target : the hardware/target identifier (e.g. rpi5, rpi4b, jetsonorinnano). See the available targets for the complete list.
  • dataset : the client’s ClientDataset.
  • training_config : the client’s baseline TrainingConfig.
  • join_at_round (optional) : delays the participation of the client to a later round.
client_config = ClientConfig(
    target="rpi5",
    dataset=dataset,
    training_config=training_config,
)

A client is added to the experiment with fl_experiment.add_client(client_config). A client that should not participate in the experiment can simply be left out.

ClientConfig also provides methods to add status profiles and discrete events, used to model time-varying client behaviors such as battery level or network issues.

Experiment Container: FlExperiment

FlExperiment is the top-level container that combines the model, the server configuration, the clients and the experiment objectives :

fl_experiment = FlExperiment(
    fl_model=fl_model,
    fl_config=fl_config,
    output_path="./fl_experiment/"
)

Experiment objectives

By default, an experiment always includes a maximum-round objective bounding its execution. Additional objectives can be appended to stop the experiment early once a target is reached, or to record checkpoints at given points in time :

  • FLTargetAccuracyObjective(target_accuracy=...) : stop once the global model reaches the target accuracy.
  • FLTargetLossObjective(target_loss=...) : stop once the global model reaches the target loss.
  • FLLossAtTimeObjective(time_seconds=...) : record the loss at a given point in time.
  • FLAccAtTimeObjective(time_seconds=...) : record the accuracy at a given point in time.
fl_experiment.add_experiment_objective(FLTargetAccuracyObjective(target_accuracy=0.90))
fl_experiment.add_experiment_objective(FLTargetLossObjective(target_loss=0.2))
fl_experiment.add_experiment_objective(FLAccAtTimeObjective(time_seconds=250))

Status profiles and events (optional)

ClientConfig can be enriched with declarative status profiles and discrete events, to model realistic constraints and disturbances over the course of the experiment. They are stored as a per-round mapping and replayed deterministically by the experiment runner.

Status profiles

Status profiles expand into a sequence of per-round status updates, and are used to model slowly varying conditions :

  • add_battery_profile(...) : models the battery level of a client over a round window, either with a per-round discharge (discharge_pct_per_round) or a per-time discharge rate (discharge_pct_per_minute). Set is_charging=True to model charging instead.
  • add_solar_profile(...) : models varying solar intensity, useful for energy-harvesting scenarios.
  • add_ac_profile(...) : models plugged-in (mains) power availability.
  • add_temperature_profile(...) : models the ambient temperature of a client over a round window.
client_config.add_battery_profile(
    start_round=1,
    stop_round=20,
    initial_level_pct=45.0,
    discharge_pct_per_minute=0.8,
    is_charging=False,
)

Several profiles can be applied over different round windows to represent complex trajectories. A client can switch power source several times during the experiment (e.g. unplugging from AC to run on battery), the only constraint being that two power source profiles cannot overlap in time.

Discrete events

Discrete events model punctual or periodic perturbations, added with add_event(...) :

  • FLEventNetworkIssue(start_round, round_interval) : intermittent network failures.
  • FLEventDelayedResponse(start_round, round_interval, delay_seconds) : delayed client responses.
  • FLEventSlowResponse(start_round, round_interval, slow_factor) : slows down the client’s response time by a given factor.
  • FLEventEpochCompletion(start_round, epoch_number) : forces an epoch-related milestone/event.
  • FLEventFailure(round) : the client leaves the training process at the given round and does not participate in any subsequent round.

Events can overlap with status profiles and several events of different types can be scheduled for the same round, except FLEventFailure which overrides all other events and profiles scheduled for that round.

Build and run a Federated Learning experiment

The following example builds a complete Federated Learning experiment with 3 clients, using pre-processed data stored as .bin files (see Provide a Dataset) and an ONNX Runtime Training model. The full listing is available at the bottom of this section.

1. Load the client and server datasets

Each client owns its own train and test set, while the server only holds an evaluation set used to monitor the global model :

import os
import numpy as np

DATA_DIR = "./fl_exp_faces"

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, 3, 224, 224)
    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, 3, 224, 224)
    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, 3, 224, 224)
    eval_targets = np.fromfile(os.path.join(server_dir, eval_target_file), dtype=np.int64)
    return eval_inputs, eval_targets

2. Configure the server strategy

The server evaluation dataset is wrapped in a ServerDataset and passed to FlConfig, together with the chosen policies and their parameters :

from daiedge_vlab.fl import *

NUM_CLASSES = 40

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

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

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

fl_config.add_parameters_selector(
    battery_threshold=30.0,
    time_fit_threshold=30.0,
    time_eval_threshold=20.0,
    start_at_round=3,
)

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, 512),
    ema_tau=0.0,
    ema_alpha_max=1.0,
)

fl_config.add_parameters_config_provider(
    base_epochs=2,
    min_epochs=1,
    max_epochs=10,
    target_round_time_s=45,
    sensitivity=2.5
)

3. Define the model and the experiment container

fl_experiment = FlExperiment(
    fl_model=FlModel(
        runtime="ort",
        model_path="./artifacts.zip",
        input_shape=(3, 224, 224),
        output_shape=(NUM_CLASSES,),
    ),
    fl_config=fl_config,
    output_path="./fl_experiment/"
)

4. Add the clients

Each client is built from its own ClientDataset and a TrainingConfig, and assigned to a target device :

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

for client_id, target in [(0, "rpi5"), (1, "rpi5"), (2, "rpi4b")]:
    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)

5. Add experiment objectives

for target_accuracy in (1.0, 0.95, 0.90, 0.85, 0.80, 0.60):
    fl_experiment.add_experiment_objective(FLTargetAccuracyObjective(target_accuracy=target_accuracy))

for target_loss in (0.3, 0.2):
    fl_experiment.add_experiment_objective(FLTargetLossObjective(target_loss=target_loss))

for time_seconds in (500, 250):
    fl_experiment.add_experiment_objective(FLLossAtTimeObjective(time_seconds=time_seconds))
    fl_experiment.add_experiment_objective(FLAccAtTimeObjective(time_seconds=time_seconds))

6. Start the experiment and retrieve the results

Finally, authenticate to the dAIEdge-VLab and start the experiment. waitFLExperimentResult blocks until the experiment finishes, and saves the resulting global model, report and logs to save_path :

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

# Optional: inspect your previous FL experiments
history = api.getFLExperimentHistory()
for exp in history:
    print(exp)

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

# You can retrieve the submitted experiment description at any time
print("Definition:", api.getFLExperimentDefinition(id))

# Blocking method - wait for the results
result = api.waitFLExperimentResult(id, save_path="./results/", verbose=True)
print("Experiment results:", result)
Info : Preparing the model artifacts (exporting to ONNX and generating the ORT training artifacts) is identical to the TYPE3 - On Device Training experiment.

Track your experiment with the FL Viewer

Once the experiment is started, you can follow its progress live with the FL Viewer. Go to https://vlab.daiedge.eu/fl-viewer/ and paste the experiment ID returned by startFLExperiment to track its rounds, the global model metrics and the per-client status as the experiment runs.