MEDfl.rw package

Submodules

class MEDfl.rw.client.DPConfig(noise_multiplier=1.0, max_grad_norm=1.0, batch_size=32, secure_rng=False)[source]

Bases: object

Configuration for differential privacy.

noise_multiplier

Noise multiplier for DP.

Type:

float

max_grad_norm

Maximum gradient norm for clipping.

Type:

float

batch_size

Batch size for training.

Type:

int

secure_rng

Use a secure random generator.

Type:

bool

class MEDfl.rw.client.FlowerClient(server_address, data_path='data/data.csv', dp_config=None, val_frac=None, test_frac=None, id_col=None, test_ids=None, seed=42)[source]

Bases: NumPyClient

Federated learning client for MEDfl real-world pipelines.

This client:
  • connects to a Flower server,

  • loads local CSV data,

  • applies server-provided schema (features/target),

  • handles train/val/test splits (fractions or test_ids),

  • optionally enables differential privacy with Opacus.

Parameters:
  • server_address (str) – Address of the Flower server, e.g. "127.0.0.1:8080".

  • data_path (str, optional) – Path to the local CSV file. Default is "data/data.csv".

  • dp_config (DPConfig, optional) – Differential privacy configuration. If None, DP is disabled.

  • val_frac (float, optional) – Client-side validation fraction override. If None, use server value.

  • test_frac (float, optional) – Client-side test fraction override. If None, use server value.

  • id_col (str, optional) – Name of the ID column used when selecting test samples via test_ids.

  • test_ids (str, optional) – Comma-separated list of IDs (or line numbers) to use as test set.

  • seed (int, optional) – Random seed used for splits. Default is 42.

_lazy_init_from_server_config(config)[source]
Build model and (train, val, test) loaders once, using:
  • Server-enforced schema: config[‘features’] (comma-separated), config[‘target’]

  • Split fractions: client overrides win; else use server’s val_fraction/test_fraction

  • NEW: if config[‘test_ids’] is set (per-client from strategy), use ID-based split

evaluate(parameters, config)[source]

Evaluate the provided parameters using the locally held dataset.

Parameters:
  • parameters (NDArrays) – The current (global) model parameters.

  • config (Dict[str, Scalar]) – Configuration parameters which allow the server to influence evaluation on the client. It can be used to communicate arbitrary values from the server to the client, for example, to influence the number of examples used for evaluation.

Returns:

  • loss (float) – The evaluation loss of the model on the local dataset.

  • num_examples (int) – The number of examples used for evaluation.

  • metrics (Dict[str, Scalar]) – A dictionary mapping arbitrary string keys to values of type bool, bytes, float, int, or str. It can be used to communicate arbitrary values back to the server.

Warning

The previous return type format (int, float, float) and the extended format (int, float, float, Dict[str, Scalar]) have been deprecated and removed since Flower 0.19.

fit(parameters, config)[source]

Train the provided parameters using the locally held dataset.

Parameters:
  • parameters (NDArrays) – The current (global) model parameters.

  • config (Dict[str, Scalar]) – Configuration parameters which allow the server to influence training on the client. It can be used to communicate arbitrary values from the server to the client, for example, to set the number of (local) training epochs.

Returns:

  • parameters (NDArrays) – The locally updated model parameters.

  • num_examples (int) – The number of examples used for training.

  • metrics (Dict[str, Scalar]) – A dictionary mapping arbitrary string keys to values of type bool, bytes, float, int, or str. It can be used to communicate arbitrary values back to the server.

get_parameters(config)[source]

Return the current local model parameters.

Parameters:

config (Config) – Configuration parameters requested by the server. This can be used to tell the client which parameters are needed along with some Scalar attributes.

Returns:

parameters – The local model parameters as a list of NumPy ndarrays.

Return type:

NDArrays

get_properties(config)[source]

Return a client’s set of properties.

Parameters:

config (Config) – Configuration parameters requested by the server. This can be used to tell the client which properties are needed along with some Scalar attributes.

Returns:

properties – A dictionary mapping arbitrary string keys to values of type bool, bytes, float, int, or str. It can be used to communicate arbitrary property values back to the server.

Return type:

Dict[str, Scalar]

set_parameters(parameters)[source]
start()[source]
class MEDfl.rw.server.FederatedServer(host='0.0.0.0', port=8080, num_rounds=3, strategy=None, certificates=None)[source]

Bases: object

FederatedServer wraps the launch and configuration of a Flower federated learning server.

server_address

Server host and port in the format “host:port”.

Type:

str

server_config

Configuration for the Flower server.

Type:

ServerConfig

strategy_wrapper

Wrapper around the actual Flower strategy.

Type:

Strategy

strategy

Actual Flower strategy instance.

Type:

flwr.server.Strategy

certificates

Optional TLS certificates.

Type:

Any

connected_clients

List of connected client IDs.

Type:

list

start()[source]

Launch the Flower server with the specified strategy and log client connections.

__init__(host='0.0.0.0', port=8080, num_rounds=3, strategy=None, certificates=None)[source]

Initialize the FederatedServer.

Parameters:
  • host (str) – Hostname or IP to bind the server to.

  • port (int) – Port to listen on.

  • num_rounds (int) – Number of federated learning rounds to execute.

  • strategy (Optional[Strategy]) – Optional custom strategy wrapper.

  • certificates (Optional[Any]) – Optional TLS certificates.

start()[source]

Start the Flower server with the configured strategy and track client connections.

class MEDfl.rw.server.TrackingClientManager(server)[source]

Bases: SimpleClientManager

TrackingClientManager extends the default SimpleClientManager to log client connections.

server

The FederatedServer instance this manager belongs to.

Type:

FederatedServer

client_properties

Placeholder for storing client-specific properties.

Type:

dict

__init__(server)[source]

Initialize the TrackingClientManager.

Parameters:

server (FederatedServer) – Reference to the FederatedServer.

async _fetch_and_log_hostname(client)[source]

Asynchronously fetch and log the client’s hostname or CID.

Parameters:

client (ClientProxy) – The client proxy.

register(client)[source]

Register a client and log its connection.

Parameters:

client (ClientProxy) – The client proxy being registered.

Returns:

True if the client was registered successfully.

Return type:

bool

class MEDfl.rw.model.Net(input_dim, hidden_dims=[64, 32], activation='relu', batchnorm=True, dropout=0.0, task='binary', num_classes=None, output_bias=True, return_logits=True, weight_init='kaiming')[source]

Bases: Module

Flexible MLP with task-aware output. - hidden_dims: e.g., [128, 64, 32] - activation: ‘relu’ | ‘gelu’ | ‘leaky_relu’ | … - batchnorm: apply BatchNorm1d after each linear (except output) - dropout: float in [0,1] or list per hidden layer - task: ‘binary’ | ‘multiclass’ | ‘multilabel’ | ‘regression’ - num_classes: required for ‘multiclass’; for ‘binary’ ignore; for ‘multilabel’ set to label count - return_logits: always True for training (recommended). Use .predict() for post-activation outputs.

forward(x)[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

predict(x)[source]
training: bool
class MEDfl.rw.strategy.Strategy(name='FedAvg', fraction_fit=1.0, fraction_evaluate=1.0, min_fit_clients=2, min_evaluate_clients=2, min_available_clients=2, initial_parameters=None, evaluate_fn=None, fit_metrics_aggregation_fn=None, evaluate_metrics_aggregation_fn=None, local_epochs=1, threshold=0.5, learning_rate=0.01, optimizer_name='SGD', savingPath='', saveOnRounds=3, total_rounds=3, features='', target='', val_fraction=0.1, test_fraction=0.1, split_mode='global', client_fractions=None, id_col='id')[source]

Bases: object

Flower Strategy wrapper:
  • Dynamic hyperparameters via on_fit_config_fn

  • Custom metric aggregation

  • Per-client & aggregated metric logging

  • Synchronous get_properties() inspection in configure_fit()

  • Saving global parameters every saveOnRounds to savingPath

Extended: - split_mode:

  • “global”: use global val_fraction/test_fraction for all clients

  • “per_client”: use client_fractions[hostname] if present

  • client_fractions:
    {
    “HOSTNAME_1”: {

    “val_fraction”: float (optional), “test_fraction”: float (optional), “test_ids”: [..] or “id1,id2” (optional)

    }

  • In per_client mode:
    • if test_ids is present for a client:

      -> send test_ids -> do NOT use that client’s test_fraction

    • otherwise:
      -> use that client’s val_fraction/test_fraction if provided,

      else fall back to global val_fraction/test_fraction

  • client id in this mapping = hostname from client.get_properties()

  • id_col:
    • column name used on clients to match test_ids (default “id”)

create_strategy()[source]
MEDfl.rw.strategy.aggregate_eval_metrics(results)[source]
MEDfl.rw.strategy.aggregate_fit_metrics(results)[source]