-
Notifications
You must be signed in to change notification settings - Fork 11
/
training.py
286 lines (209 loc) · 10.3 KB
/
training.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def run_selftrain_GC(clients, server, local_epoch):
# all clients are initialized with the same weights
for client in clients:
client.download_from_server(server)
allAccs = {}
for client in clients:
client.local_train(local_epoch)
loss, acc = client.evaluate()
allAccs[client.name] = [client.train_stats['trainingAccs'][-1], client.train_stats['valAccs'][-1], acc]
print(" > {} done.".format(client.name))
return allAccs
def run_fedavg(clients, server, COMMUNICATION_ROUNDS, local_epoch, samp=None, frac=1.0):
for client in clients:
client.download_from_server(server)
if samp is None:
sampling_fn = server.randomSample_clients
frac = 1.0
for c_round in range(1, COMMUNICATION_ROUNDS + 1):
if (c_round) % 50 == 0:
print(f" > round {c_round}")
if c_round == 1:
selected_clients = clients
else:
selected_clients = sampling_fn(clients, frac)
for client in selected_clients:
# only get weights of graphconv layers
client.local_train(local_epoch)
server.aggregate_weights(selected_clients)
for client in selected_clients:
client.download_from_server(server)
frame = pd.DataFrame()
for client in clients:
loss, acc = client.evaluate()
frame.loc[client.name, 'test_acc'] = acc
def highlight_max(s):
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
fs = frame.style.apply(highlight_max).data
print(fs)
return frame
def run_fedprox(clients, server, COMMUNICATION_ROUNDS, local_epoch, mu, samp=None, frac=1.0):
for client in clients:
client.download_from_server(server)
if samp is None:
sampling_fn = server.randomSample_clients
frac = 1.0
if samp == 'random':
sampling_fn = server.randomSample_clients
for c_round in range(1, COMMUNICATION_ROUNDS + 1):
if (c_round) % 50 == 0:
print(f" > round {c_round}")
if c_round == 1:
selected_clients = clients
else:
selected_clients = sampling_fn(clients, frac)
for client in selected_clients:
client.local_train_prox(local_epoch, mu)
server.aggregate_weights(selected_clients)
for client in selected_clients:
client.download_from_server(server)
# cache the aggregated weights for next round
client.cache_weights()
frame = pd.DataFrame()
for client in clients:
loss, acc = client.evaluate()
frame.loc[client.name, 'test_acc'] = acc
def highlight_max(s):
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
fs = frame.style.apply(highlight_max).data
print(fs)
return frame
def run_gcfl(clients, server, COMMUNICATION_ROUNDS, local_epoch, EPS_1, EPS_2):
cluster_indices = [np.arange(len(clients)).astype("int")]
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices]
for c_round in range(1, COMMUNICATION_ROUNDS + 1):
if (c_round) % 50 == 0:
print(f" > round {c_round}")
if c_round == 1:
for client in clients:
client.download_from_server(server)
participating_clients = server.randomSample_clients(clients, frac=1.0)
for client in participating_clients:
client.compute_weight_update(local_epoch)
client.reset()
similarities = server.compute_pairwise_similarities(clients)
cluster_indices_new = []
for idc in cluster_indices:
max_norm = server.compute_max_update_norm([clients[i] for i in idc])
mean_norm = server.compute_mean_update_norm([clients[i] for i in idc])
if mean_norm < EPS_1 and max_norm > EPS_2 and len(idc) > 2 and c_round > 20:
server.cache_model(idc, clients[idc[0]].W, acc_clients)
c1, c2 = server.min_cut(similarities[idc][:, idc], idc)
cluster_indices_new += [c1, c2]
else:
cluster_indices_new += [idc]
cluster_indices = cluster_indices_new
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices] # initial: [[0, 1, ...]]
server.aggregate_clusterwise(client_clusters)
acc_clients = [client.evaluate()[1] for client in clients]
for idc in cluster_indices:
server.cache_model(idc, clients[idc[0]].W, acc_clients)
results = np.zeros([len(clients), len(server.model_cache)])
for i, (idcs, W, accs) in enumerate(server.model_cache):
results[idcs, i] = np.array(accs)
frame = pd.DataFrame(results, columns=["FL Model"] + ["Model {}".format(i)
for i in range(results.shape[1] - 1)],
index=["{}".format(clients[i].name) for i in range(results.shape[0])])
frame = pd.DataFrame(frame.max(axis=1))
frame.columns = ['test_acc']
print(frame)
return frame
def run_gcflplus(clients, server, COMMUNICATION_ROUNDS, local_epoch, EPS_1, EPS_2, seq_length, standardize):
cluster_indices = [np.arange(len(clients)).astype("int")]
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices]
seqs_grads = {c.id:[] for c in clients}
for client in clients:
client.download_from_server(server)
for c_round in range(1, COMMUNICATION_ROUNDS + 1):
if (c_round) % 50 == 0:
print(f" > round {c_round}")
if c_round == 1:
for client in clients:
client.download_from_server(server)
participating_clients = server.randomSample_clients(clients, frac=1.0)
for client in participating_clients:
client.compute_weight_update(local_epoch)
client.reset()
seqs_grads[client.id].append(client.convGradsNorm)
cluster_indices_new = []
for idc in cluster_indices:
max_norm = server.compute_max_update_norm([clients[i] for i in idc])
mean_norm = server.compute_mean_update_norm([clients[i] for i in idc])
if mean_norm < EPS_1 and max_norm > EPS_2 and len(idc) > 2 and c_round > 20 \
and all(len(value) >= seq_length for value in seqs_grads.values()):
server.cache_model(idc, clients[idc[0]].W, acc_clients)
tmp = [seqs_grads[id][-seq_length:] for id in idc]
dtw_distances = server.compute_pairwise_distances(tmp, standardize)
c1, c2 = server.min_cut(np.max(dtw_distances)-dtw_distances, idc)
cluster_indices_new += [c1, c2]
seqs_grads = {c.id: [] for c in clients}
else:
cluster_indices_new += [idc]
cluster_indices = cluster_indices_new
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices]
server.aggregate_clusterwise(client_clusters)
acc_clients = [client.evaluate()[1] for client in clients]
for idc in cluster_indices:
server.cache_model(idc, clients[idc[0]].W, acc_clients)
results = np.zeros([len(clients), len(server.model_cache)])
for i, (idcs, W, accs) in enumerate(server.model_cache):
results[idcs, i] = np.array(accs)
frame = pd.DataFrame(results, columns=["FL Model"] + ["Model {}".format(i)
for i in range(results.shape[1] - 1)],
index=["{}".format(clients[i].name) for i in range(results.shape[0])])
frame = pd.DataFrame(frame.max(axis=1))
frame.columns = ['test_acc']
print(frame)
return frame
def run_gcflplus_dWs(clients, server, COMMUNICATION_ROUNDS, local_epoch, EPS_1, EPS_2, seq_length, standardize):
cluster_indices = [np.arange(len(clients)).astype("int")]
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices]
seqs_grads = {c.id:[] for c in clients}
for client in clients:
client.download_from_server(server)
for c_round in range(1, COMMUNICATION_ROUNDS + 1):
if (c_round) % 50 == 0:
print(f" > round {c_round}")
if c_round == 1:
for client in clients:
client.download_from_server(server)
participating_clients = server.randomSample_clients(clients, frac=1.0)
for client in participating_clients:
client.compute_weight_update(local_epoch)
client.reset()
seqs_grads[client.id].append(client.convDWsNorm)
cluster_indices_new = []
for idc in cluster_indices:
max_norm = server.compute_max_update_norm([clients[i] for i in idc])
mean_norm = server.compute_mean_update_norm([clients[i] for i in idc])
if mean_norm < EPS_1 and max_norm > EPS_2 and len(idc) > 2 and c_round > 20 \
and all(len(value) >= seq_length for value in seqs_grads.values()):
server.cache_model(idc, clients[idc[0]].W, acc_clients)
tmp = [seqs_grads[id][-seq_length:] for id in idc]
dtw_distances = server.compute_pairwise_distances(tmp, standardize)
c1, c2 = server.min_cut(np.max(dtw_distances)-dtw_distances, idc)
cluster_indices_new += [c1, c2]
seqs_grads = {c.id: [] for c in clients}
else:
cluster_indices_new += [idc]
cluster_indices = cluster_indices_new
client_clusters = [[clients[i] for i in idcs] for idcs in cluster_indices]
server.aggregate_clusterwise(client_clusters)
acc_clients = [client.evaluate()[1] for client in clients]
for idc in cluster_indices:
server.cache_model(idc, clients[idc[0]].W, acc_clients)
results = np.zeros([len(clients), len(server.model_cache)])
for i, (idcs, W, accs) in enumerate(server.model_cache):
results[idcs, i] = np.array(accs)
frame = pd.DataFrame(results, columns=["FL Model"] + ["Model {}".format(i)
for i in range(results.shape[1] - 1)],
index=["{}".format(clients[i].name) for i in range(results.shape[0])])
frame = pd.DataFrame(frame.max(axis=1))
frame.columns = ['test_acc']
print(frame)
return frame