from typing import List, Tuple, Callable, Dict, Optional, Union, cast import numpy as np import flwr as fl import pickle from flwr.common import Metrics, Scalar, EvaluateIns, EvaluateRes, FitIns, FitRes, MetricsAggregationFn, NDArray, NDArrays, Parameters, ndarrays_to_parameters, parameters_to_ndarrays import argparse from torchvision import models import torch import torch.nn as nn from easyfsl.methods import PrototypicalNetworks from easyfsl.utils import evaluate import os from utils.Dataloader import create_datasets_and_loaders from utils.create_dataset import create_data_set from flwr.common.logger import log from flwr.server.client_manager import ClientManager from flwr.server.client_proxy import ClientProxy from epoch_scheuler import EpochScheduler from flwr.server.strategy.aggregate import aggregate from collections import OrderedDict from utils.utils import get_parameters from config import * from logging import WARNING import socket # Required positional argument parser = argparse.ArgumentParser(description="Flower Server Configuration") parser.add_argument( "--host", type=str, default="0.0.0.0", help="Host address to bind the Flower server (default: 0.0.0.0)", ) parser.add_argument( "--port", type=int, default=8080, help="Port number to bind the Flower server (default: 8080)", ) parser.add_argument( "--strategy", type=str, default="FedAvg", choices=[ "FaultTolerantFedAvg", "FedAdagrad", "FedAdam", "FedAvg", "FedXgbNnAvg", "FedAvgAndroid", "FedAvgM", "FedOpt", "FedProx", "FedYogi", "QFedAvg", "FedMedian", "FedTrimmedAvg", ], help="Federated learning strategy to use (default: FedAvg)", ) parser.add_argument( "--run_name", type=str, default="3", help="Method for aggregation", ) parser.add_argument( "--loss_fn", type=str, default="MSE", help="loss function", ) parser.add_argument( "--num_clients", type=int, default=2, help="Number of clients", ) parser.add_argument( "--min_epochs", type=int, default=2, help="Minimum number of epochs", ) parser.add_argument( "--max_epochs", type=int, default=7, help="Maximum number of epochs", ) parser.add_argument( "--mode", type=str, default="Normal", help="Set mode for earlystopping Normal/earlystopping", ) WEIGHT_COUNTER = 0 def server_run(server_address, fed_method, run_name,num_clients,min_epochs,max_epochs,loss_fn,mode): print("port for server is -----------------------------------", server_address) #########start global model print("Configuration Settings:") print(f"train_test_spl: {train_test_spl}") print(f"root_dir: {root_dir}") print(f"global_model_path: {global_model_path}") print(f"n_validation_tasks: {n_validation_tasks}") print(f"n_way: {n_way}") print(f"n_shot: {n_shot}") print(f"n_query: {n_query}") print(f"n_workers: {n_workers}") print(f"n_epochs: {n_epochs}") print(f"scheduler_milestones: {scheduler_milestones}") print(f"scheduler_gamma: {scheduler_gamma}") print(f"learning_rate: {learning_rate}") print(f"loss function is : {loss_fn}") print(f"sipv4 is {socket.gethostbyname(socket.gethostname())}") total_clients = num_clients Emin = min_epochs Emax = max_epochs mode = mode DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = models.resnet18(pretrained=False) model.fc = nn.Identity() globel_model = PrototypicalNetworks(model) model = globel_model.to(DEVICE) # root_folder = fed_method + run_name root_folder = fed_method + run_name root_folder = os.path.join("../Output", root_folder) os.makedirs(root_folder, exist_ok=True) os.makedirs(root_folder, exist_ok=True) LOG_DIR = os.path.join(root_folder, "logs") os.makedirs(LOG_DIR, exist_ok=True) LOG_FILE = os.path.join(LOG_DIR, "training_eval_logs_Global_model.txt") model_dir = os.path.join(root_folder, "model") os.makedirs(model_dir, exist_ok=True) ###########################please change these settings############# n_tasks_per_epoch = 1 permutation = [0, 1, 2, 5] env_list = [2, 3, 11, 4, 5, 6, 7, 8, 9, 10] weight_path = "./workspace/Jammer_detection/Src/Linkhalle_federated/Src/outputs/2024-04-10/trained_0123/trained_0123/model_weights0epoch100.h5" ###################################################################### env_str = "_".join(map(str, env_list)) permutations_str = "_".join(map(str, permutation)) file_name = f"train_data_{permutations_str}_env{env_str}.csv" print(file_name) if not os.path.exists(file_name): create_data_set( root_dir=root_dir, train_test_split_dir=train_test_spl, label_list=permutation, n_way=n_way, n_shot=n_shot, n_query=n_query, env_no=env_list ) testloader, stationvalid_loaders = create_datasets_and_loaders( root_dir, train_test_spl, permutation, n_way, n_shot, n_query, n_tasks_per_epoch, n_validation_tasks, n_workers, env_no=env_list ) def test(net, remote_valid_dataset, device=DEVICE): """Evaluate the network on the entire test set.""" net.to(DEVICE) net.eval() validation_accuracy = evaluate(net, remote_valid_dataset, device, tqdm_prefix="Validation") return validation_accuracy def get_eval_fn( testloader: torch.utils.data.DataLoader, ) -> Callable[[fl.common.NDArrays], Optional[Tuple[float, Dict[str, Scalar]]]]: """Return an evaluation function for centralized evaluation.""" DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def evaluate(server_round: int, parameters_ndarrays: fl.common.NDArrays, dictionary: dict) -> Optional[Tuple[float, float]]: model = models.resnet18() model.fc = nn.Identity() globel_model = PrototypicalNetworks(model) state_dict = dict() for idx, param_tensor in enumerate(globel_model.state_dict()): state_dict[param_tensor] = torch.from_numpy(parameters_ndarrays[idx]) print("im saving model under following folder -----------------------------------------------------------------------") model_dir = os.path.join(root_folder, "model") model_file = os.path.join(model_dir, f"round--{WEIGHT_COUNTER}_weights.h5") globel_model.load_state_dict(state_dict, strict=False) torch.save(globel_model.state_dict(), model_file) accuracy = test(globel_model, testloader, DEVICE) with open(LOG_FILE, "a") as file: file.write(f"Epoch: accuracy: {accuracy}\n") loss = 0 # Define your loss calculation here metrics = {"accuracy": accuracy} return loss, metrics return evaluate weights = torch.load(weight_path, map_location=DEVICE) model.load_state_dict(weights) weights = get_parameters(model) parameters = fl.common.ndarrays_to_parameters(weights) strategy_class = getattr(fl.server.strategy, fed_method, None) if strategy_class is None or not issubclass(strategy_class, fl.server.strategy.Strategy): raise ValueError(f"Invalid strategy: {parser.strategy}") print(f"strategy class is ----------------------------------------{strategy_class}") class SaveModelStrategy(strategy_class): def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) if issubclass(strategy_class, fl.server.strategy.fedprox.FedProx): # Set proximal_mu if not provided in kwargs kwargs.setdefault('proximal_mu', 1) # Set default value for proximal_mu super().__init__(*args, **kwargs) self.client_ids = [] self.embedding_diffs = [] # List of embedding differences self.prev_rn_diff = None self.epoch_scheduler = EpochScheduler( num_clients=total_clients, initial_epochs=Emax, min_epochs=Emin, max_epochs=Emax, ) def aggregate_fit(self, rnd: int, results, failures) -> Optional[fl.common.NDArrays]: if use_custom_aggregation: print("Im using weight difference based aggregation method") custom_weights, custom_aggregated_metrics = self.aggregate_fit_custom(rnd, results, failures) return custom_weights, custom_aggregated_metrics elif emb_diff_to_server: print("Im using embeddings difference based aggregation method") custom_weights, custom_aggregated_metrics = self.aggregate_emb_diff(rnd, results, failures) return custom_weights, custom_aggregated_metrics else: print("Im using original based aggregation method") weights, aggregated_metrics = super().aggregate_fit(rnd, results, failures) global WEIGHT_COUNTER if weights is not None: try: model_dir = os.path.join(root_folder, "model") os.makedirs(model_dir, exist_ok=True) except Exception as e: print(f"Error saving weights for round {rnd}: {e}") WEIGHT_COUNTER += 1 self.client_ids = [fit_res.metrics.get("client_id") for _, fit_res in results] self.embedding_diffs = [fit_res.metrics.get("embedding_diff") for _, fit_res in results] self.client_ids = [int(x) for x in self.client_ids] return weights, aggregated_metrics def aggregate_fit_custom( self, server_round: int, results: List[Tuple[ClientProxy, FitRes]], failures: List[Union[Tuple[ClientProxy, FitRes], BaseException]], ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]: """Aggregate fit results using weighted average.""" if not results: return None, {} if not self.accept_failures and failures: return None, {} weights_results = [ (parameters_to_ndarrays(fit_res.parameters), fit_res.num_examples) for _, fit_res in results ] initial_ndarry = parameters_to_ndarrays(parameters) actual_weights = [weights[0] for weights in weights_results] weight_vector = [1.5, 1.5, 0.25, 0.25] revised_weights_ndarrays = [ [array * weight for array in aggregated] for aggregated, weight in zip(actual_weights, weight_vector) ] new_weights = [(param, fit_ins[1]) for param, fit_ins in zip(revised_weights_ndarrays, weights_results)] parameters_aggregated = ndarrays_to_parameters(aggregate(new_weights)) metrics_aggregated = {} if self.fit_metrics_aggregation_fn: fit_metrics = [(res.num_examples, res.metrics) for _, res in results] metrics_aggregated = self.fit_metrics_aggregation_fn(fit_metrics) elif server_round == 1: log(WARNING, "No fit_metrics_aggregation_fn provided") global WEIGHT_COUNTER if weights is not None: try: model_dir = os.path.join(root_folder, "model") os.makedirs(model_dir, exist_ok=True) except Exception as e: print(f"Error saving weights for round {server_round}: {e}") WEIGHT_COUNTER += 1 return parameters_aggregated, metrics_aggregated def aggregate_emb_diff( self, server_round: int, results: List[Tuple[ClientProxy, FitRes]], failures: List[Union[Tuple[ClientProxy, FitRes], BaseException]], ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]: """Aggregate fit results using weighted average.""" if not results: return None, {} if not self.accept_failures and failures: return None, {} weights_results = [ (parameters_to_ndarrays(fit_res.parameters), fit_res.num_examples, fit_res.metrics["embedding_diff"]) for _, fit_res in results ] actual_weights = [weights[0] for weights in weights_results] emb_difference = [weights[2] for weights in weights_results] abs_difference = [abs(val) for val in emb_difference] max_difference = max(abs_difference) if max(emb_difference) == 0.0: weight_vector = [1, 1, 1, 1] else: weight_vector = [i / max_difference for i in abs_difference] revised_weights_ndarrays = [ [array * weight for array in aggregated] for aggregated, weight in zip(actual_weights, weight_vector) ] new_weights = [(param, fit_ins[1]) for param, fit_ins in zip(revised_weights_ndarrays, weights_results)] parameters_aggregated = ndarrays_to_parameters(aggregate(new_weights)) metrics_aggregated = {} if self.fit_metrics_aggregation_fn: fit_metrics = [(res.num_examples, res.metrics) for _, res in results] metrics_aggregated = self.fit_metrics_aggregation_fn(fit_metrics) elif server_round == 1: log(WARNING, "No fit_metrics_aggregation_fn provided") global WEIGHT_COUNTER if weights is not None: try: model_dir = os.path.join(root_folder, "model") os.makedirs(model_dir, exist_ok=True) except Exception as e: print(f"Error saving weights for round {server_round}: {e}") WEIGHT_COUNTER += 1 return parameters_aggregated, metrics_aggregated def configure_fit( self, server_round: int, parameters: Parameters, client_manager: ClientManager ) -> List[Tuple[ClientProxy, FitIns]]: """Configure the next round of training.""" # config = {} if self.on_fit_config_fn is not None: config = self.on_fit_config_fn(server_round) if mode != "Normal": config = self.epoch_scheduler.fit_config(server_round, self.embedding_diffs, self.client_ids, self.prev_rn_diff) else: config = {} self.prev_rn_diff = self.embedding_diffs fit_ins = FitIns(parameters, config) sample_size, min_num_clients = self.num_fit_clients(client_manager.num_available()) clients = client_manager.sample(num_clients=sample_size, min_num_clients=min_num_clients) selected_clients = [client.cid for client in clients] log_file_path = os.path.join(root_folder, "selected_clients.log") with open(log_file_path, "a") as log_file: log_file.write(f"Round: {server_round}, Selected Clients: {selected_clients}\n") return [(client, fit_ins) for client in clients] strategy = SaveModelStrategy( initial_parameters=parameters, min_fit_clients=2, min_available_clients=2, min_evaluate_clients=2, evaluate_fn=get_eval_fn(testloader), ) fl.server.start_server( server_address=server_address, config=fl.server.ServerConfig(num_rounds=10), strategy=strategy, grpc_max_message_length=1024*1024*1024, ) if __name__ == "__main__": args = parser.parse_args() host = args.host port = args.port server_address = f"{host}:{port}" run_name = args.run_name fed_method = args.strategy num_clients = args.num_clients min_epochs = args.min_epochs max_epochs = args.max_epochs loss_fn = args.loss_fn mode = args.mode WEIGHT_COUNTER = 0 server_run(server_address, fed_method, run_name,num_clients,min_epochs,max_epochs,loss_fn,mode)