-
Notifications
You must be signed in to change notification settings - Fork 4
/
rffl_aggregator.py
217 lines (187 loc) · 7.58 KB
/
rffl_aggregator.py
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import copy
import logging
import os
import sys
import time
import numpy as np
import torch
import torch.nn.functional as F
import wandb
from sklearn.metrics import roc_auc_score
from .rffl_utils import mask_grad_update_by_order
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../")))
from core.utils import transform_list_to_grad
from distributed.fedavg.fedavg_gradient_aggregator import FedAVGGradientAggregator
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../FedML/")))
from fedml_api.distributed.fedavg.FedAVGAggregator import FedAVGAggregator
from fedml_api.distributed.fedavg.utils import transform_list_to_tensor
EPS = 1e-8
class RFFLAggregator(FedAVGGradientAggregator):
def __init__(
self,
train_global,
test_global,
all_train_data_num,
train_data_local_dict,
test_data_local_dict,
train_data_local_num_dict,
worker_num,
device,
args,
model_trainer,
adversary_flag=None,
):
super().__init__(
train_global,
test_global,
all_train_data_num,
train_data_local_dict,
test_data_local_dict,
train_data_local_num_dict,
worker_num,
device,
args,
model_trainer,
)
self.adversary_flag = adversary_flag
if adversary_flag is not None:
self.adversary_idx = [i for i, f in enumerate(adversary_flag) if f == 1]
else:
self.adversary_idx = []
self.pred_credibility = np.zeros_like(adversary_flag).astype(float)
self.rs = torch.zeros(args.client_num_in_total, device=device)
if self.args.ignore_adversary == 0:
self.R_set = list(range(args.client_num_in_total))
else:
self.R_set = list(
set(list(range(args.client_num_in_total))) - set(self.adversary_idx)
)
self.relative_size = [0] * args.client_num_in_total
self.threshold = 1 / (3 * args.client_num_in_total)
self.warm_up = self.args.warm_up
self.alpha = self.args.alpha
self.sparcity = self.args.sparcity
self.remove = self.args.remove
def _update_reputations(self, client_index, model_list, averaged_gradient):
# culculate the reputations
flatten_averaged_gradient = torch.cat(
[g.to(self.device).view(-1) for g in averaged_gradient]
)
phis = torch.zeros(self.args.client_num_in_total, device=self.device)
for c_idx, local_gradient in zip(client_index, model_list):
flatten_local_gradient = torch.cat(
[g.to(self.device).view(-1) for g in local_gradient[1]]
)
phis[c_idx] = F.cosine_similarity(
flatten_local_gradient, flatten_averaged_gradient, 0, EPS
)
self.rs[c_idx] = (
self.alpha * self.rs[c_idx] + (1 - self.alpha) * phis[c_idx]
)
print("phis is ", phis)
print("self.rs is ", self.rs)
self.rs = torch.div(self.rs, self.rs.sum())
def _remove(self):
# remove the unuseful cilents
curr_threshold = self.threshold * (1.0 / len(self.R_set))
if self.remove == 1 and self.round_idx > self.warm_up:
for client_idx in self.R_set:
if self.rs[client_idx] < curr_threshold:
self.rs[client_idx] = 0
self.R_set.remove(client_idx)
self.rs = torch.div(self.rs, self.rs.sum())
else:
pass
def _get_reward_gradiets(self, averaged_gradient, sender_id_to_client_index):
client_index_to_sender_id = {
v: k - 1 for k, v in sender_id_to_client_index.items()
}
q_ratios = torch.div(self.rs, torch.max(self.rs))
reward_gradients = {}
for client_idx in self.R_set:
q_ratio = q_ratios[client_idx]
if self.sparcity == 1:
reward_gradients[client_idx] = mask_grad_update_by_order(
copy.deepcopy(averaged_gradient),
mask_percentile=q_ratio,
mode="layer",
)
else:
reward_gradients[client_idx] = copy.deepcopy(averaged_gradient)
for grad_idx in range(len(reward_gradients[client_idx])):
if self.round_idx == 0:
w = self.relative_size[client_idx]
else:
w = self.rs[client_idx]
reward_gradients[client_idx][grad_idx].data -= (
self.model_dict[client_index_to_sender_id[client_idx]][
grad_idx
].data.to(self.device)
* w
)
return reward_gradients
def anomalydetection(self, sender_id_to_client_index):
self.pred_credibility = self.rs.detach().cpu().numpy()
auc_crediblity = roc_auc_score(self.adversary_flag, -self.pred_credibility)
wandb.log(
{
"Credibility/Adversary-AUC": auc_crediblity,
"round": self.round_idx,
}
)
wandb.log({"Clients/R_set": len(self.R_set), "round": self.round_idx})
wandb.log(
{
"Clients/Surviving Adversaries": len(
list(set(self.R_set).intersection(self.adversary_idx))
),
"round": self.round_idx,
}
)
def aggregate(self, sender_id_to_client_index):
start_time = time.time()
model_list = []
client_index = []
training_num = 0
for idx in range(self.worker_num):
if self.args.is_mobile == 1:
self.model_dict[idx] = transform_list_to_grad(self.model_dict[idx])
model_list.append((self.sample_num_dict[idx], self.model_dict[idx]))
training_num += self.sample_num_dict[idx]
client_index.append(sender_id_to_client_index[idx + 1])
logging.info("len of self.model_dict[idx] = " + str(len(self.model_dict)))
averaged_gradient = [
torch.zeros(grad.shape).to(self.device) for grad in model_list[0][1]
]
for i in range(0, len(model_list)):
local_sample_number, local_gradient = model_list[i]
# culculate the norm
flatten_local_gradient = torch.cat(
[g.to(self.device).view(-1) for g in local_gradient]
)
norm_value = torch.linalg.norm(flatten_local_gradient) + EPS
# culculate the weight
if self.round_idx == 0:
w = local_sample_number / training_num
self.relative_size[client_index[i]] = w
else:
w = self.rs[client_index[i]]
# aggregation
for grad_idx in range(len(averaged_gradient)):
averaged_gradient[grad_idx].data += (
local_gradient[grad_idx].data.to(self.device)
* w
* self.args.gamma
/ norm_value
)
self._update_reputations(client_index, model_list, averaged_gradient)
self._remove()
reward_gradients = self._get_reward_gradiets(
averaged_gradient, sender_id_to_client_index
)
# update the global model which is cached at the server side
self.set_global_model_gradients(averaged_gradient, self.device, weight=1)
end_time = time.time()
logging.info("aggregate time cost: %d" % (end_time - start_time))
self.round_idx += 1
return reward_gradients