-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_fl.py
More file actions
188 lines (160 loc) · 8.94 KB
/
start_fl.py
File metadata and controls
188 lines (160 loc) · 8.94 KB
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
import asyncio
import os
import websockets
import json
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import yaml
async def start_fl():
with open('network_config.yml', 'r') as file:
network_data = yaml.safe_load(file)
host_ip = network_data['host']
algo = input("Please select algorithm,\n1.Classic Federated Learning\n2.V-FL Games\n:")
if int(algo) == 1:
uri = "ws://"+str(host_ip)+"/job_receive"
else:
uri = "ws://"+str(host_ip)+"/job_receive_hetero"
async with websockets.connect(uri) as websocket:
task_name = input("Please enter task name: ")
# algo = input("Please select algorithm,\n1.Classic Federated Learning\n2.V-FL Games\n:")
minibatch = input("Please enter local minibatch size: ")
if int(algo) == 1:
lr = input("Please enter the learning rate: ")
elif int(algo) ==2:
rep_lr = input("Please enter representation learner learning rate: ")
pred_lr = input("Please enter Predictor learning rate: ")
if int(algo) == 1:
epochs = input("Please enter number of local epochs: ")
else:
epochs = 1
client_fraction = input("Please enter client fraction: ")
minibatch_test = input("Please enter test minibatch size: ")
comm_rounds = input("Please enter number of communication rounds: ")
optimizer_no = input("Please select a optimizer: \n1.Adam\n2.SGD\n3.RMSProp\n4.AdaGrad\n:")
if int(optimizer_no) == 1:
optimizer = 'Adam'
elif int(optimizer_no) == 2:
optimizer = 'SGD'
elif int(optimizer_no) == 3:
optimizer = 'RMSProp'
elif int(optimizer_no) == 4:
optimizer = 'AdaGrad'
loss_no = input("Please select a loss function: \n1.Cross entropy Loss\n2.BCE loss\n3.MSE loss\n:")
if int(loss_no) == 1:
loss = 'CrossEntropyLoss'
elif int(loss_no) == 2:
loss = 'BCELoss'
elif int(loss_no) == 3:
loss = 'MSELoss'
folder = input("Please enter dataset folder: ")
if int(algo) == 1:
job_data = {"jobData": {
"general": {"task": str(task_name), "method": str(algo), "algo": "Classification",
"host": str(host_ip),
"clients": network_data['clients'],
"plots": [None]},
"scheme": {"minibatch": str(minibatch), "epoch": str(epochs),
"lr": str(lr), "scheduler": "random", "clientFraction": str(client_fraction),
"minibatchtest": str(minibatch_test),
"comRounds": str(comm_rounds)},
"modelParam": {"optimizer": str(optimizer), "loss": str(loss), "compress": False},
"preprocessing": {"dtype": "img", "folder": str(folder), "testfolder": str(folder), "normalize": False}}}
else:
job_data = {"jobData": {
"general": {"task": str(task_name), "method": str(algo), "algo": "Classification",
"host": str(host_ip),
"clients": network_data['clients'],
"plots": [None]},
"scheme": {"batch_size": str(minibatch), "epoch": str(epochs),
"rep_lr": str(rep_lr),"pred_lr": str(pred_lr), "scheduler": "random", "clientFraction": str(client_fraction),
"minibatchtest": str(minibatch_test),
"comRounds": str(comm_rounds)},
"modelParam": {"optimizer": str(optimizer), "loss": str(loss), "compress": False},
"preprocessing": {"dtype": "img", "folder": str(folder), "testfolder": str(folder),
"normalize": False}}}
job_data = json.dumps(job_data)
await websocket.send(job_data)
test_accuracy = []
train_loss = []
test_loss = []
round_time = []
total_bytes = []
final_round = False
while not final_round:
async for message in websocket:
# print(f"<<< {message}")
message = json.loads(message)
if message['status'] == 'training':
print('Training epoch ' + str(message['epoch']) + ' completed at ' + str(message['client_id']))
elif message['status'] == 'results':
if not message['final']:
print('Communication round ' + str(message['round']) + ' completed with accuracy ' + str(
message['accuracy']))
else:
print('Final communication round completed with accuracy ' + str(message['accuracy']))
if message['status'] == 'results':
test_accuracy.append(float(message['accuracy']))
train_loss.append(float(message['train_loss']))
test_loss.append(float(message['test_loss']))
if len(round_time) == 0:
round_time.append(float(message['round_time']))
total_bytes.append(float(message['total_bytes']))
else:
r_time = round_time[-1] + float(message['round_time'])
t_bytes = total_bytes[-1] + float(message['total_bytes'])
round_time.append(r_time)
total_bytes.append(t_bytes)
final_round = message['final']
if final_round:
rounds = np.array([i for i in range(1, len(test_accuracy) + 1)])
font = {
'weight': 'bold',
'size': 20}
matplotlib.rc('font', **font)
# print('Current test accuracy ' + str(test_accuracy))
fig, axs = plt.subplots(2, figsize=(30, 20))
axs[0].plot(rounds, np.array(test_accuracy), label='test accuracy')
axs[0].set_title('Number of rounds vs Test Accuracy')
axs[0].set(xlabel='Number of Rounds', ylabel='Test Accuracy')
axs[1].plot(rounds, np.array(train_loss), label='train loss')
axs[1].set_title('Number of rounds vs Train Loss')
axs[1].set(xlabel='Number of Rounds', ylabel='Train Loss')
# axs[1, 0].plot(rounds, round_time, label='elapsed time')
# axs[1, 0].set_title('Number of rounds vs Elapsed time')
# axs[1, 0].set(xlabel='Number of Rounds', ylabel='Elapsed time(s)')
#
# axs[1, 1].plot(rounds, total_bytes, label='total bytes')
# axs[1, 1].set_title('Number of rounds vs bytes transferred')
# axs[1, 1].set(xlabel='Number of Rounds', ylabel='Total bytes')
job_data = json.loads(job_data)
task_n = job_data['jobData']['general']['task']
os.makedirs(os.path.dirname('results/' + str(task_n)), exist_ok=True)
plt.savefig('results/results.png')
if int(algo) == 1:
np.save('results/classic_test_acc.npy', np.array(test_accuracy))
np.save('results/classic_train_loss.npy', np.array(train_loss))
if int(algo) == 2:
rounds = np.array([i for i in range(1, len(test_accuracy) + 1)])
np.save('results/vfl_test_acc.npy', np.array(test_accuracy))
np.save('results/vfl_train_loss.npy', np.array(train_loss))
classic_acc = np.load('results/classic_test_acc.npy')
classic_loss = np.load('results/classic_train_loss.npy')
font = {
'weight': 'bold',
'size': 20}
matplotlib.rc('font', **font)
# print('Current test accuracy ' + str(test_accuracy))
fig, axs = plt.subplots(2, figsize=(30, 20))
axs[0].plot(rounds, np.array(test_accuracy), label='V-FL')
axs[0].plot(rounds, np.array(classic_acc), label='Classic FL')
axs[0].set_title('Number of rounds vs Test Accuracy')
axs[0].set(xlabel='Number of Rounds', ylabel='Test Accuracy')
axs[1].plot(rounds, np.array(train_loss), label='V-FL')
axs[1].plot(rounds, np.array(classic_loss), label='Classic FL')
axs[1].set_title('Number of rounds vs Train Loss')
axs[1].set(xlabel='Number of Rounds', ylabel='Train Loss')
plt.legend(loc="lower right")
plt.savefig('results/results_combined.png')
if __name__ == "__main__":
asyncio.run(start_fl())