|
| 1 | +import argparse |
| 2 | +from collections import OrderedDict |
| 3 | +from logging import INFO |
| 4 | +from pathlib import Path |
| 5 | +from typing import Dict, Tuple |
| 6 | + |
| 7 | +import flwr as fl |
| 8 | +import numpy as np |
| 9 | +import torch |
| 10 | +import torch.nn as nn |
| 11 | +from flwr.common.logger import log |
| 12 | +from flwr.common.typing import Config, NDArrays, Scalar |
| 13 | +from torch.utils.data import DataLoader |
| 14 | + |
| 15 | +from examples.dp_fed_examples.client_level_dp_weighted.data import load_data |
| 16 | +from examples.models.logistic_regression import LogisticRegression |
| 17 | +from fl4health.clients.clipping_client import NumpyClippingClient |
| 18 | + |
| 19 | + |
| 20 | +def train(net: nn.Module, train_loader: DataLoader, epochs: int, device: torch.device = torch.device("cpu")) -> float: |
| 21 | + |
| 22 | + criterion = torch.nn.BCELoss() |
| 23 | + optimizer = torch.optim.SGD(net.parameters(), lr=0.01, weight_decay=1e-4) |
| 24 | + |
| 25 | + for epoch in range(epochs): |
| 26 | + correct, total, running_loss = 0, 0, 0.0 |
| 27 | + n_batches = len(train_loader) |
| 28 | + for features, labels in train_loader: |
| 29 | + features, labels = features.to(device), labels.to(device) |
| 30 | + optimizer.zero_grad() |
| 31 | + preds = net(features) |
| 32 | + loss = criterion(preds, labels) |
| 33 | + loss.backward() |
| 34 | + optimizer.step() |
| 35 | + |
| 36 | + running_loss += loss.item() |
| 37 | + predicted = preds.data >= 0.5 |
| 38 | + |
| 39 | + total += labels.size(0) |
| 40 | + correct += (predicted.int() == labels.int()).sum().item() |
| 41 | + |
| 42 | + accuracy = correct / total |
| 43 | + # Local client logging. |
| 44 | + log( |
| 45 | + INFO, |
| 46 | + f"Epoch: {epoch}, Client Training Loss: {running_loss/n_batches}," |
| 47 | + f" Client Training Accuracy: {accuracy}", |
| 48 | + ) |
| 49 | + return accuracy |
| 50 | + |
| 51 | + |
| 52 | +def validate( |
| 53 | + net: nn.Module, |
| 54 | + validation_loader: DataLoader, |
| 55 | + device: torch.device = torch.device("cpu"), |
| 56 | +) -> Tuple[float, float]: |
| 57 | + """Validate the network on the entire validation set.""" |
| 58 | + criterion = torch.nn.BCELoss() |
| 59 | + correct, total, loss = 0, 0, 0.0 |
| 60 | + with torch.no_grad(): |
| 61 | + n_batches = len(validation_loader) |
| 62 | + for features, labels in validation_loader: |
| 63 | + features, labels = features.to(device), labels.to(device) |
| 64 | + preds = net(features) |
| 65 | + loss += criterion(preds, labels).item() |
| 66 | + predicted = preds.data >= 0.5 |
| 67 | + total += labels.size(0) |
| 68 | + correct += (predicted.int() == labels.int()).sum().item() |
| 69 | + accuracy = correct / total |
| 70 | + # Local client logging. |
| 71 | + log(INFO, f"Client Validation Loss: {loss/n_batches} Client Validation Accuracy: {accuracy}") |
| 72 | + return loss / n_batches, accuracy |
| 73 | + |
| 74 | + |
| 75 | +class HospitalClient(NumpyClippingClient): |
| 76 | + def __init__( |
| 77 | + self, |
| 78 | + data_path: Path, |
| 79 | + device: torch.device, |
| 80 | + ) -> None: |
| 81 | + super().__init__() |
| 82 | + self.device = device |
| 83 | + self.data_path = data_path |
| 84 | + self.initialized = False |
| 85 | + self.train_loader: DataLoader |
| 86 | + |
| 87 | + def get_parameters(self, config: Config) -> NDArrays: |
| 88 | + # Determines which weights are sent back to the server for aggregation. |
| 89 | + # Currently sending all of them ordered by state_dict keys |
| 90 | + # NOTE: Order matters, because it is relied upon by set_parameters below |
| 91 | + model_weights = [val.cpu().numpy() for _, val in self.model.state_dict().items()] |
| 92 | + # Clipped the weights and store clipping information in parameters |
| 93 | + clipped_weight_update, clipping_bit = self.compute_weight_update_and_clip(model_weights) |
| 94 | + return clipped_weight_update + [np.array([clipping_bit])] |
| 95 | + |
| 96 | + def set_parameters(self, parameters: NDArrays, config: Config) -> None: |
| 97 | + # Sets the local model parameters transfered from the server. The state_dict is |
| 98 | + # reconstituted because parameters is simply a list of bytes |
| 99 | + # The last entry in the parameters list is assumed to be a clipping bound (even if we're evaluating) |
| 100 | + server_model_parameters = parameters[:-1] |
| 101 | + params_dict = zip(self.model.state_dict().keys(), server_model_parameters) |
| 102 | + state_dict = OrderedDict({k: torch.tensor(v) for k, v in params_dict}) |
| 103 | + self.model.load_state_dict(state_dict, strict=True) |
| 104 | + |
| 105 | + # Store the starting parameters without clipping bound before client optimization steps |
| 106 | + self.current_weights = server_model_parameters |
| 107 | + |
| 108 | + clipping_bound = parameters[-1] |
| 109 | + self.clipping_bound = float(clipping_bound) |
| 110 | + |
| 111 | + def setup_client(self, config: Config) -> None: |
| 112 | + self.batch_size = config["batch_size"] |
| 113 | + self.local_epochs = config["local_epochs"] |
| 114 | + self.adaptive_clipping = config["adaptive_clipping"] |
| 115 | + self.scaler_bytes = config["scaler"] |
| 116 | + |
| 117 | + train_loader, validation_loader, num_examples = load_data(self.data_path, self.batch_size, self.scaler_bytes) |
| 118 | + |
| 119 | + self.train_loader = train_loader |
| 120 | + self.validation_loader = validation_loader |
| 121 | + self.num_examples = num_examples |
| 122 | + self.model = LogisticRegression(input_dim=31, output_dim=1).to(self.device) |
| 123 | + self.initialized = True |
| 124 | + |
| 125 | + def fit(self, parameters: NDArrays, config: Config) -> Tuple[NDArrays, int, Dict[str, Scalar]]: |
| 126 | + # Expectation is that the last entry in the parameters NDArrays is a clipping bound |
| 127 | + if not self.initialized: |
| 128 | + self.setup_client(config) |
| 129 | + self.set_parameters(parameters, config) |
| 130 | + accuracy = train( |
| 131 | + self.model, |
| 132 | + self.train_loader, |
| 133 | + self.local_epochs, |
| 134 | + self.device, |
| 135 | + ) |
| 136 | + # FitRes should contain local parameters, number of examples on client, and a dictionary holding metrics |
| 137 | + # calculation results. |
| 138 | + return ( |
| 139 | + self.get_parameters(config), |
| 140 | + self.num_examples["train_set"], |
| 141 | + {"accuracy": accuracy}, |
| 142 | + ) |
| 143 | + |
| 144 | + def evaluate(self, parameters: NDArrays, config: Config) -> Tuple[float, int, Dict[str, Scalar]]: |
| 145 | + # Expectation is that the last entry in the parameters NDArrays is a clipping bound (even if it isn't used |
| 146 | + # for evaluation) |
| 147 | + if not self.initialized: |
| 148 | + self.setup_client(config) |
| 149 | + self.set_parameters(parameters, config) |
| 150 | + loss, accuracy = validate(self.model, self.validation_loader, device=self.device) |
| 151 | + # EvaluateRes should return the loss, number of examples on client, and a dictionary holding metrics |
| 152 | + # calculation results. |
| 153 | + return ( |
| 154 | + loss, |
| 155 | + self.num_examples["validation_set"], |
| 156 | + {"accuracy": accuracy}, |
| 157 | + ) |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + parser = argparse.ArgumentParser(description="FL Client Main") |
| 162 | + parser.add_argument("--dataset_path", action="store", type=str, help="Path to the local dataset") |
| 163 | + args = parser.parse_args() |
| 164 | + |
| 165 | + # Load model and data |
| 166 | + DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") |
| 167 | + data_path = Path(args.dataset_path) |
| 168 | + client = HospitalClient(data_path, DEVICE) |
| 169 | + fl.client.start_numpy_client(server_address="0.0.0.0:8080", client=client) |
0 commit comments