File size: 5,226 Bytes
29d330e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | 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
|