-
Notifications
You must be signed in to change notification settings - Fork 119
/
executor.py
executable file
·481 lines (393 loc) · 16.3 KB
/
executor.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# -*- coding: utf-8 -*-
import collections
import gc
import pickle
import random
import time
from argparse import Namespace
import numpy as np
import torch
import wandb
import fedscale.cloud.channels.job_api_pb2 as job_api_pb2
import fedscale.cloud.logger.executor_logging as logger
from fedscale.cloud.channels.channel_context import ClientConnections
from fedscale.cloud.execution.tensorflow_client import TensorflowClient
from fedscale.cloud.execution.torch_client import TorchClient
from fedscale.cloud.execution.data_processor import collate, voice_collate_fn
from fedscale.cloud.execution.rl_client import RLClient
from fedscale.cloud.fllibs import *
from fedscale.dataloaders.divide_data import DataPartitioner, select_dataset
class Executor(object):
"""Abstract class for FedScale executor.
Args:
args (dictionary): Variable arguments for fedscale runtime config. defaults to the setup in arg_parser.py
"""
def __init__(self, args):
# initiate the executor log path, and executor ips
logger.initiate_client_setting()
self.model_adapter = self.get_client_trainer(args).get_model_adapter(
init_model()
)
self.args = args
self.num_executors = args.num_executors
# ======== env information ========
self.this_rank = args.this_rank
self.executor_id = str(self.this_rank)
# ======== model and data ========
self.training_sets = self.test_dataset = None
# ======== channels ========
self.aggregator_communicator = ClientConnections(args.ps_ip, args.ps_port)
# ======== runtime information ========
self.collate_fn = None
self.round = 0
self.start_run_time = time.time()
self.received_stop_request = False
self.event_queue = collections.deque()
if args.wandb_token != "":
os.environ["WANDB_API_KEY"] = args.wandb_token
self.wandb = wandb
if self.wandb.run is None:
self.wandb.init(
project=f"fedscale-{args.job_name}",
name=f"executor{args.this_rank}-{args.time_stamp}",
group=f"{args.time_stamp}",
)
else:
logging.error("Warning: wandb has already been initialized")
else:
self.wandb = None
super(Executor, self).__init__()
def setup_env(self):
"""Set up experiments environment"""
logging.info(f"(EXECUTOR:{self.this_rank}) is setting up environ ...")
self.setup_seed(seed=1)
def setup_communication(self):
"""Set up grpc connection"""
self.init_control_communication()
self.init_data_communication()
def setup_seed(self, seed=1):
"""Set random seed for reproducibility
Args:
seed (int): random seed
"""
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
def init_control_communication(self):
"""Create communication channel between coordinator and executor.
This channel serves control messages.
"""
self.aggregator_communicator.connect_to_server()
def init_data_communication(self):
"""In charge of jumbo data traffics (e.g., fetch training result)"""
pass
def init_data(self):
"""Return the training and testing dataset
Returns:
Tuple of DataPartitioner class: The partioned dataset class for training and testing
"""
train_dataset, test_dataset = init_dataset()
if self.args.task == "rl":
return train_dataset, test_dataset
if self.args.task == "nlp":
self.collate_fn = collate
elif self.args.task == "voice":
self.collate_fn = voice_collate_fn
# load data partitionxr (entire_train_data)
logging.info("Data partitioner starts ...")
training_sets = DataPartitioner(
data=train_dataset, args=self.args, numOfClass=self.args.num_class
)
training_sets.partition_data_helper(
num_clients=self.args.num_participants,
data_map_file=self.args.data_map_file,
)
testing_sets = DataPartitioner(
data=test_dataset,
args=self.args,
numOfClass=self.args.num_class,
isTest=True,
)
testing_sets.partition_data_helper(num_clients=self.num_executors)
logging.info("Data partitioner completes ...")
return training_sets, testing_sets
def run(self):
"""Start running the executor by setting up execution and communication environment, and monitoring the grpc message."""
self.setup_env()
self.training_sets, self.testing_sets = self.init_data()
self.setup_communication()
self.event_monitor()
def dispatch_worker_events(self, request):
"""Add new events to worker queues
Args:
request (string): Add grpc request from server (e.g. MODEL_TEST, MODEL_TRAIN) to event_queue.
"""
self.event_queue.append(request)
def deserialize_response(self, responses):
"""Deserialize the response from server
Args:
responses (byte stream): Serialized response from server.
Returns:
ServerResponse defined at job_api.proto: The deserialized response object from server.
"""
return pickle.loads(responses)
def serialize_response(self, responses):
"""Serialize the response to send to server upon assigned job completion
Args:
responses (string, bool, or bytes): TorchClient responses after job completion.
Returns:
bytes stream: The serialized response object to server.
"""
return pickle.dumps(responses)
def UpdateModel(self, model_weights):
"""Receive the broadcasted global model for current round
Args:
config (PyTorch or TensorFlow model): The broadcasted global model config
"""
self.round += 1
self.model_adapter.set_weights(model_weights, is_aggregator=False)
def Train(self, config):
"""Load train config and data to start training on that client
Args:
config (dictionary): The client training config.
Returns:
tuple (int, dictionary): The client id and train result
"""
client_id, train_config = config["client_id"], config["task_config"]
if "model" not in config or not config["model"]:
raise "The 'model' object must be a non-null value in the training config."
client_conf = self.override_conf(train_config)
train_res = self.training_handler(
client_id=client_id, conf=client_conf, model=config["model"]
)
# Report execution completion meta information
response = self.aggregator_communicator.stub.CLIENT_EXECUTE_COMPLETION(
job_api_pb2.CompleteRequest(
client_id=str(client_id),
executor_id=self.executor_id,
event=commons.CLIENT_TRAIN,
status=True,
msg=None,
meta_result=None,
data_result=None,
)
)
self.dispatch_worker_events(response)
return client_id, train_res
def Test(self, config):
"""Model Testing. By default, we test the accuracy on all data of clients in the test group
Args:
config (dictionary): The client testing config.
"""
test_res = self.testing_handler(model=config["model"])
test_res = {"executorId": self.this_rank, "results": test_res}
# Report execution completion information
response = self.aggregator_communicator.stub.CLIENT_EXECUTE_COMPLETION(
job_api_pb2.CompleteRequest(
client_id=self.executor_id,
executor_id=self.executor_id,
event=commons.MODEL_TEST,
status=True,
msg=None,
meta_result=None,
data_result=self.serialize_response(test_res),
)
)
self.dispatch_worker_events(response)
def Stop(self):
"""Stop the current executor"""
logging.info(f"Terminating the executor ...")
self.aggregator_communicator.close_sever_connection()
self.received_stop_request = True
if self.wandb != None:
self.wandb.finish()
def report_executor_info_handler(self):
"""Return the statistics of training dataset
Returns:
int: Return the statistics of training dataset, in simulation return the number of clients
"""
return self.training_sets.getSize()
def override_conf(self, config):
"""Override the variable arguments for different client
Args:
config (dictionary): The client runtime config.
Returns:
dictionary: Variable arguments for client runtime config.
"""
default_conf = vars(self.args).copy()
for key in config:
default_conf[key] = config[key]
return Namespace(**default_conf)
def get_client_trainer(self, conf):
"""
Returns a framework-specific client that handles training and evaluation.
:param conf: job config
:return: framework-specific client instance
"""
if conf.engine == commons.TENSORFLOW:
return TensorflowClient(conf)
elif conf.engine == commons.PYTORCH:
if conf.task == "rl":
return RLClient(conf)
else:
return TorchClient(conf)
raise "Currently, FedScale supports tensorflow and pytorch."
def training_handler(self, client_id, conf, model):
"""Train model given client id
Args:
client_id (int): The client id.
conf (dictionary): The client runtime config.
Returns:
dictionary: The train result
"""
self.model_adapter.set_weights(model, is_aggregator=False)
conf.client_id = client_id
conf.tokenizer = tokenizer
client_data = (
self.training_sets
if self.args.task == "rl"
else select_dataset(
client_id,
self.training_sets,
batch_size=conf.batch_size,
args=self.args,
collate_fn=self.collate_fn,
)
)
client = self.get_client_trainer(self.args)
train_res = client.train(
client_data=client_data, model=self.model_adapter.get_model(), conf=conf
)
return train_res
def testing_handler(self, model):
"""Test model
Args:
args (dictionary): Variable arguments for fedscale runtime config. defaults to the setup in arg_parser.py
config (dictionary): Variable arguments from coordinator.
Returns:
dictionary: The test result
"""
self.model_adapter.set_weights(model, is_aggregator=False)
test_config = self.override_conf(
{
"rank": self.this_rank,
"memory_capacity": self.args.memory_capacity,
"tokenizer": tokenizer,
}
)
client = self.get_client_trainer(test_config)
data_loader = select_dataset(
self.this_rank,
self.testing_sets,
batch_size=self.args.test_bsz,
args=self.args,
isTest=True,
collate_fn=self.collate_fn,
)
test_results = client.test(
data_loader, model=self.model_adapter.get_model(), conf=test_config
)
self.log_test_result(test_results)
gc.collect()
return test_results
def client_register(self):
"""Register the executor information to the aggregator"""
start_time = time.time()
while time.time() - start_time < 180:
try:
response = self.aggregator_communicator.stub.CLIENT_REGISTER(
job_api_pb2.RegisterRequest(
client_id=self.executor_id,
executor_id=self.executor_id,
executor_info=self.serialize_response(
self.report_executor_info_handler()
),
)
)
self.dispatch_worker_events(response)
break
except Exception as e:
logging.warning(
f"Failed to connect to aggregator {e}. Will retry in 5 sec."
)
time.sleep(5)
def client_ping(self):
"""Ping the aggregator for new task"""
response = self.aggregator_communicator.stub.CLIENT_PING(
job_api_pb2.PingRequest(
client_id=self.executor_id, executor_id=self.executor_id
)
)
self.dispatch_worker_events(response)
def event_monitor(self):
"""Activate event handler once receiving new message"""
logging.info("Start monitoring events ...")
self.client_register()
while not self.received_stop_request:
if len(self.event_queue) > 0:
request = self.event_queue.popleft()
current_event = request.event
if current_event == commons.CLIENT_TRAIN:
train_config = self.deserialize_response(request.meta)
train_model = self.deserialize_response(request.data)
train_config["model"] = train_model
train_config["client_id"] = int(train_config["client_id"])
client_id, train_res = self.Train(train_config)
# Upload model updates
future_call = self.aggregator_communicator.stub.CLIENT_EXECUTE_COMPLETION.future(
job_api_pb2.CompleteRequest(
client_id=str(client_id),
executor_id=self.executor_id,
event=commons.UPLOAD_MODEL,
status=True,
msg=None,
meta_result=None,
data_result=self.serialize_response(train_res),
)
)
future_call.add_done_callback(
lambda _response: self.dispatch_worker_events(
_response.result()
)
)
elif current_event == commons.MODEL_TEST:
test_config = self.deserialize_response(request.meta)
test_model = self.deserialize_response(request.data)
test_config["model"] = test_model
test_config["client_id"] = int(test_config["client_id"])
self.Test(test_config)
elif current_event == commons.UPDATE_MODEL:
model_weights = self.deserialize_response(request.data)
self.UpdateModel(model_weights)
elif current_event == commons.SHUT_DOWN:
self.Stop()
elif current_event == commons.DUMMY_EVENT:
pass
else:
time.sleep(1)
try:
self.client_ping()
except Exception as e:
logging.info(
f"Caught exception {e} from aggregator, terminating executor {self.this_rank} ..."
)
self.Stop()
def log_test_result(self, test_res):
"""Log test results to wandb server if enabled"""
acc = round(test_res["top_1"] / test_res["test_len"], 4)
acc_5 = round(test_res["top_5"] / test_res["test_len"], 4)
test_loss = test_res["test_loss"] / test_res["test_len"]
if self.wandb != None:
self.wandb.log(
{
"Test/round_to_top1_accuracy": acc,
"Test/round_to_top5_accuracy": acc_5,
"Test/round_to_loss": test_loss,
},
step=self.round,
)
if __name__ == "__main__":
executor = Executor(parser.args)
executor.run()