Download Pytorch_federated/utils_aggregation.py from FelixOtt/gnss_federated_learning: direct link, hf CLI and curl.
- Browser
- Download file 5.23 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Pytorch_federated/utils_aggregation.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_federated_learning/Pytorch_federated/utils_aggregation.py
-
curl -L -o utils_aggregation.py https://huggingface.co/datasets/FelixOtt/gnss_federated_learning/resolve/main/Pytorch_federated/utils_aggregation.py
5.23 kB
| import numpy as np | |
| import torch | |
| from typing import List, Tuple,Dict | |
| def aggregate(results: List[Tuple[torch.Tensor, int, Dict]]) -> torch.Tensor: | |
| """Compute weighted average of model parameters.""" | |
| # Calculate the total number of examples used during training | |
| num_examples_total = sum([num_examples for _, num_examples, _ in results]) | |
| # Create a list of weights, each multiplied by the related number of examples | |
| weighted_weights = [ | |
| [layer * num_examples for layer in weights] for weights, num_examples, _ in results | |
| ] | |
| weights_prime = [ | |
| torch.sum(torch.stack([torch.tensor(arr) for arr in layer_updates]), dim=0) / num_examples_total | |
| for layer_updates in zip(*weighted_weights) | |
| ] | |
| return weights_prime | |
| def aggregate_median(results: List[Tuple[torch.Tensor, int,Dict]]) -> torch.Tensor: | |
| """Compute median of model parameters.""" | |
| # Create a list of weights and ignore the number of examples | |
| weights = [weights for weights, _, _ in results] | |
| # Compute median weight of each layer | |
| median_weights = [ | |
| torch.median(torch.stack(layer), dim=0).values for layer in zip(*weights) | |
| ] | |
| return median_weights | |
| def aggregate_krum( | |
| results: List[Tuple[torch.Tensor, int,Dict]], num_malicious: int, to_keep: int | |
| ) -> torch.Tensor: | |
| """Choose one parameter vector according to the Krum function. | |
| If to_keep is not None, then MultiKrum is applied. | |
| """ | |
| # Create a list of weights and ignore the number of examples | |
| weights = [weights for weights, _,_ in results] | |
| # Compute distances between vectors | |
| distance_matrix = _compute_distances(weights) | |
| # For each client, take the n-f-2 closest parameters vectors | |
| num_closest = max(1, len(weights) - num_malicious - 2) | |
| closest_indices = [] | |
| for i in range(len(distance_matrix)): | |
| closest_indices.append( | |
| np.argsort(distance_matrix[i])[1 : num_closest + 1].tolist() | |
| ) | |
| # Compute the score for each client, that is the sum of the distances | |
| # of the n-f-2 closest parameters vectors | |
| scores = [ | |
| np.sum(distance_matrix[i, closest_indices[i]]) | |
| for i in range(len(distance_matrix)) | |
| ] | |
| if to_keep > 0: | |
| # Choose to_keep clients and return their average (MultiKrum) | |
| best_indices = np.argsort(scores)[::-1][len(scores) - to_keep :] | |
| best_results = [results[i] for i in best_indices] | |
| return aggregate(best_results) | |
| # Return the model parameters that minimize the score (Krum) | |
| return weights[np.argmin(scores)] | |
| def _compute_distances(weights: List[torch.Tensor]) -> torch.Tensor: | |
| """Compute pairwise distances between vectors. | |
| Args: | |
| weights: List of tensors representing weight vectors. | |
| Returns: | |
| distance_matrix: Matrix of squared distances between the vectors. | |
| """ | |
| num_weights = len(weights) | |
| flat_w = torch.stack([weight.view(-1) for weight in weights]) | |
| distance_matrix = torch.zeros(num_weights, num_weights) | |
| for i in range(num_weights): | |
| for j in range(num_weights): | |
| delta = flat_w[i] - flat_w[j] | |
| norm = torch.norm(delta) | |
| distance_matrix[i, j] = norm**2 | |
| return distance_matrix | |
| def weighted_loss_avg(results: List[Tuple[int, float]]) -> float: | |
| """Compute weighted average loss from evaluation results obtained from multiple clients.""" | |
| num_total_evaluation_examples = sum([num_examples for num_examples, _ in results]) | |
| weighted_losses = [num_examples * loss for num_examples, loss in results] | |
| return sum(weighted_losses) / num_total_evaluation_examples | |
| def aggregate_qffl( | |
| parameters: List[torch.Tensor], deltas: List[List[torch.Tensor]], hs_fll: List[torch.Tensor] | |
| ) -> List[torch.Tensor]: | |
| """Compute weighted average based on Q-FFL paper.""" | |
| denominator = sum(hs_fll) | |
| scaled_deltas = [[layer * 1.0 / denominator for layer in client_delta] for client_delta in deltas] | |
| updates = [sum(layer[i] for layer in scaled_deltas) for i in range(len(deltas[0]))] | |
| new_parameters = [(u - v) * 1.0 for u, v in zip(parameters, updates)] | |
| return new_parameters | |
| import torch | |
| from typing import List, Tuple | |
| def aggregate_trimmed_avg( | |
| results: List[Tuple[List[torch.Tensor], int,Dict]], proportiontocut: float | |
| ) -> List[torch.Tensor]: | |
| """Compute trimmed average.""" | |
| # Extract weights and ignore the number of examples | |
| weights = [weights for weights, _,_ in results] | |
| # Compute trimmed average for each layer | |
| trimmed_w = [ | |
| _trim_mean(weights, proportiontocut=proportiontocut) | |
| for weights in zip(*weights) | |
| ] | |
| return trimmed_w | |
| def _trim_mean(array: List[torch.Tensor], proportiontocut: float) -> torch.Tensor: | |
| """Compute trimmed mean along axis=0.""" | |
| axis = 0 | |
| nobs = array[0].shape[axis] | |
| lowercut = int(proportiontocut * nobs) | |
| uppercut = nobs - lowercut | |
| if lowercut > uppercut: | |
| raise ValueError("Proportion too big.") | |
| atmp = torch.partition(array, (lowercut, uppercut - 1), dim=axis) | |
| slice_list = [slice(None)] * atmp.dim() | |
| slice_list[axis] = slice(lowercut, uppercut) | |
| result = torch.mean(atmp[tuple(slice_list)], dim=axis) | |
| return result | |