-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdistwq.py
2215 lines (1992 loc) · 78.2 KB
/
distwq.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Distributed work queue operations using mpi4py.
#
# Copyright (C) 2020-2023 Ivan Raikov and distwq authors.
#
# Based on mpi.py from the pyunicorn project.
# Copyright (C) 2008--2019 Jonathan F. Donges and pyunicorn authors
# URL: <http://www.pik-potsdam.de/members/donges/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or published elsewhere.
#
# You can use the following reference:
# J.F. Donges, J. Heitzig, B. Beronov, M. Wiedermann, J. Runge, Q.-Y. Feng,
# L. Tupikina, V. Stolbova, R.V. Donner, N. Marwan, H.A. Dijkstra,
# and J. Kurths, "Unified functional network and nonlinear time series analysis
# for complex systems science: The pyunicorn package"
"""
Distributed work queue operations using mpi4py.
Allows for easy parallelization in controller/worker mode with one
controller submitting function or method calls to workers. Supports
multiple ranks per worker (collective workers). Uses mpi4py if
available, otherwise processes calls sequentially in one process.
"""
#
# Imports
#
import importlib
import json
import logging
import os
import random
import signal
import sys
import time
import traceback
from enum import IntEnum
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from mpi4py.MPI import Intercomm, Intracomm
from numpy import float64, ndarray
class CollectiveMode(IntEnum):
Gather = 1
SendRecv = 2
class MessageTag(IntEnum):
READY = 0
DONE = 1
TASK = 2
EXIT = 3
class GroupingMethod(IntEnum):
NoGrouping = 0
GroupSpawn = 1
GroupSplit = 2
logger = logging.getLogger(__name__)
# try to get the communicator object to see whether mpi is available:
try:
from mpi4py import MPI
world_comm = MPI.COMM_WORLD
has_mpi = True
except ImportError:
has_mpi = False
def mpi_excepthook(type, value, traceback):
"""
:param type:
:param value:
:param traceback:
:return:
"""
sys_excepthook(type, value, traceback)
sys.stdout.flush()
sys.stderr.flush()
MPI.COMM_WORLD.Abort(1)
has_args = "-" in sys.argv
my_args_start_index = sys.argv.index("-") + 1 if has_args else 0
my_args: Optional[List[str]] = sys.argv[my_args_start_index:] if has_args else None
my_config: Optional[Dict[Any, Any]] = None
# initialize:
workers_available = True
spawned = False
if has_mpi:
spawned = (my_args[0] == "distwq:spawned") if my_args is not None else False
size = world_comm.size
rank = world_comm.rank
controller_rank = int(os.environ.get("DISTWQ_CONTROLLER_RANK", "0"))
if controller_rank < 0:
controller_rank = size - 1
if controller_rank >= size:
raise RuntimeError(
f"Invalid controller rank {controller_rank} specified "
f"when world size is {size}"
)
is_controller = (not spawned) and (rank == controller_rank)
is_worker = not is_controller
if size < 2:
workers_available = False
is_worker = True
else:
size = 1
rank = 0
is_controller = True
is_worker = True
if has_mpi and (size > 1):
sys_excepthook = sys.excepthook
sys.excepthook = mpi_excepthook
if spawned:
my_config = json.loads(my_args[1]) if isinstance(my_args, list) else None
n_workers = (
int(my_config["n_workers"]) if spawned and isinstance(my_config, dict) else size - 1
)
start_time = time.time()
def multiple_task_arguments(N, args, kwargs, task_ids, workers):
"""
Helper function to set default arguments, task ids, and workers for multiple tasks.
"""
if (args is None) or (len(args) == 0):
args = [dict() for _ in range(N)]
if (kwargs is None) or (len(kwargs) == 0):
kwargs = [dict() for _ in range(N)]
if task_ids is None:
task_ids = [None for _ in range(N)]
if workers is None:
workers = [None for _ in range(N)]
return args, kwargs, task_ids, workers
class MPIController(object):
def __init__(self, comm: Intracomm, time_limit: Any = None) -> None:
size = comm.size
self.comm = comm
self.workers_available = True if size > 1 else False
self.count = 0
self.start_time = start_time
self.time_limit = time_limit
self.total_time_est = np.ones(size)
"""
(numpy array of ints)
total_time_est[i] is the current estimate of the total time
MPI worker i will work on already submitted calls.
On worker i, only total_time_est[i] is available.
"""
self.total_time_est[0] = np.inf
self.result_queue: List[int] = []
self.task_queue: List[int] = []
self.wait_queue: List[int] = []
self.waiting: Dict[
int,
Tuple[
str,
Union[List[Any], Tuple[Any]],
Dict[Any, Any],
str,
Optional[int],
Optional[int],
],
] = {}
self.ready_workers: List[int] = []
self.ready_workers_data: Dict[int, Any] = {}
"""(list) ids of submitted calls"""
self.assigned = {}
"""
(dictionary)
assigned[id] is the worker assigned to the call with that id.
"""
self.worker_queue = [[] for i in range(0, size)]
"""
(list of lists)
worker_queue[i] contains the ids of calls assigned to worker i.
"""
self.active_workers = set([])
"""
(set) active_workers contains the ids of workers that have
communicated with the controller
"""
self.n_processed = np.zeros(size).astype(int)
"""
(list of ints)
n_processed[rank] is the total number of calls processed by MPI node rank.
On worker i, only total_time[i] is available.
"""
self.total_time = np.zeros(size).astype(np.float32)
"""
(list of floats)
total_time[rank] is the total wall time until that node finished its last
call. On worker i, only total_time[i] is available.
"""
self.results = {}
"""
(dictionary)
if mpi is not available, the result of submit_call(..., id=a) will be
cached in results[a] until get_result(a).
"""
self.stats = []
"""
(list of dictionaries)
stats[id] contains processing statistics for the last call with this id. Keys:
- "id": id of the call
- "rank": MPI node who processed the call
- "this_time": wall time for processing the call
- "time_over_est": quotient of actual over estimated wall time
- "n_processed": no. of calls processed so far by this worker, including this
- "total_time": total wall time until this call was finished
"""
def process(self, limit: int = 1000) -> List[Union[int, Any]]:
"""
Process incoming messages.
"""
if not self.workers_available:
return
count = 0
while self.comm.Iprobe(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG):
if (limit is not None) and (limit < count):
break
status = MPI.Status()
data = self.comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=status)
worker = status.Get_source()
tag = status.Get_tag()
if tag == MessageTag.READY.value:
if worker not in self.ready_workers:
self.ready_workers.append(worker)
self.ready_workers_data[worker] = data
self.active_workers.add(worker)
logger.info(
f"MPI controller : received READY message from worker {worker}"
)
elif tag == MessageTag.DONE.value:
task_id, results, stats = data
logger.info(
f"MPI controller : received DONE message for task {task_id} "
f"from worker {worker}"
)
self.results[task_id] = results
self.stats.append(stats)
self.n_processed[worker] = stats["n_processed"]
self.total_time[worker] = stats["total_time"]
self.task_queue.remove(task_id)
self.result_queue.append(task_id)
self.worker_queue[worker].remove(task_id)
self.assigned.pop(task_id)
count += 1
else:
raise RuntimeError(f"MPI controller : invalid message tag {tag}")
else:
time.sleep(1)
return self.submit_waiting()
def submit_call(
self,
name_to_call: str,
args: Tuple[Any] = (),
kwargs: Dict[Any, Any] = {},
module_name: str = "__main__",
time_est: int = 1,
task_id: Optional[int] = None,
worker: Optional[int] = None,
) -> int:
"""
Submit a call for parallel execution.
If called by the controller and workers are available, the call is submitted
to a worker for asynchronous execution.
If called by a worker or if no workers are available, the call is instead
executed synchronously on this MPI node.
**Examples:**
1. Provide ids and time estimate explicitly:
.. code-block:: python
for n in range(0,10):
distwq.submit_call("doit", (n,A[n]), id=n, time_est=n**2)
for n in range(0,10):
result[n] = distwq.get_result(n)
2. Use generated ids stored in a list:
.. code-block:: python
for n in range(0,10):
ids.append(distwq.submit_call("doit", (n,A[n])))
for n in range(0,10):
results.append(distwq.get_result(ids.pop()))
3. Ignore ids altogether:
.. code-block:: python
for n in range(0,10):
distwq.submit_call("doit", (n,A[n]))
for n in range(0,10):
results.append(distwq.get_next_result())
4. Call a module function and use keyword arguments:
.. code-block:: python
distwq.submit_call("solve", (), {"a":a, "b":b},
module="numpy.linalg")
:arg str name_to_call: name of callable object (usually a function or
static method of a class) as contained in the namespace specified
by module.
:arg tuple args: the positional arguments to provide to the callable
object. Tuples of length 1 must be written (arg,). Default: ()
:arg dict kwargs: the keyword arguments to provide to the callable
object. Default: {}
:arg str module: optional name of the imported module or submodule in
whose namespace the callable object is contained. For objects
defined on the script level, this is "__main__", for objects
defined in an imported package, this is the package name. Must be a
key of the dictionary sys.modules (check there after import if in
doubt). Default: "__main__"
:arg float time_est: estimated relative completion time for this call;
used to find a suitable worker. Default: 1
:type id: object or None
:arg id: unique id for this call. Must be a possible dictionary key.
If None, a random id is assigned and returned. Can be re-used after
get_result() for this is. Default: None
:type worker: int > 0 and < comm.size, or None
:arg worker: optional no. of worker to assign the call to. If None, the
call is assigned to the worker with the smallest current total time
estimate. Default: None
:return object: id of call, to be used in get_result().
"""
if task_id is None:
task_id = self.count
self.count += 1
self.check_valid_task_id(task_id)
if self.workers_available:
self.process()
if len(self.ready_workers) > 0:
if worker is None:
ready_total_time_est = np.asarray(
[self.total_time_est[worker] for worker in self.ready_workers]
)
worker = self.ready_workers[np.argmin(ready_total_time_est)]
else:
if worker not in self.ready_workers:
raise RuntimeError(f"worker {worker} is not in ready queue!")
# send name to call, args, time_est to worker:
logger.info(
f"MPI controller : assigning call with id {task_id} to worker "
f"{worker}: {name_to_call} {args} {kwargs} ..."
)
req = self.comm.isend(
(name_to_call, args, kwargs, module_name, time_est, task_id),
dest=worker,
tag=MessageTag.TASK.value,
)
req.wait()
self.ready_workers.remove(worker)
del self.ready_workers_data[worker]
self.task_queue.append(task_id)
self.worker_queue[worker].append(task_id)
self.assigned[task_id] = worker
else:
self.queue_call(
name_to_call,
args=args,
kwargs=kwargs,
module_name=module_name,
time_est=time_est,
task_id=task_id,
requested_worker=worker,
)
else:
# perform call on this rank if no workers are available:
worker = 0
logger.info(f"MPI controller : calling {name_to_call} {args} {kwargs} ...")
object_to_call = None
try:
if module_name not in sys.modules:
importlib.import_module(module_name)
object_to_call = eval(name_to_call, sys.modules[module_name].__dict__)
except NameError:
logger.error(str(sys.modules[module_name].__dict__.keys()))
raise
call_time = time.time()
self.results[task_id] = object_to_call(*args, **kwargs)
self.result_queue.append(task_id)
this_time = time.time() - call_time
self.n_processed[0] += 1
self.total_time[0] = time.time() - start_time
self.stats.append(
{
"id": task_id,
"rank": worker,
"this_time": this_time,
"time_over_est": this_time / time_est,
"n_processed": self.n_processed[0],
"total_time": self.total_time[0],
}
)
self.total_time_est[worker] += time_est
return task_id
def queue_call(
self,
name_to_call: str,
args: Union[List[Any], Tuple[Any]] = (),
kwargs: Dict[Any, Any] = {},
module_name: str = "__main__",
time_est: int = 1,
task_id: Optional[int] = None,
requested_worker: Optional[int] = None,
) -> int:
"""Submit a call for later execution.
If called by the controller and workers are available, the
call is put on the wait queue and submitted to a worker when
it is available. Method process() checks the wait queue and
submits calls on the wait queue.
If called by a worker or if no workers are available, the call is instead
executed synchronously on this MPI node.
:arg str name_to_call: name of callable object (usually a function or
static method of a class) as contained in the namespace specified
by module.
:arg tuple args: the positional arguments to provide to the callable
object. Tuples of length 1 must be written (arg,). Default: ()
:arg dict kwargs: the keyword arguments to provide to the callable
object. Default: {}
:arg str module: optional name of the imported module or submodule in
whose namespace the callable object is contained. For objects
defined on the script level, this is "__main__", for objects
defined in an imported package, this is the package name. Must be a
key of the dictionary sys.modules (check there after import if in
doubt). Default: "__main__"
:arg float time_est: estimated relative completion time for this call;
used to find a suitable worker. Default: 1
:type id: object or None
:arg id: unique id for this call. Must be a possible dictionary key.
If None, a random id is assigned and returned. Can be re-used after
get_result() for this is. Default: None
:return object: id of call, to be used in get_result().
:type requested_worker: int > 0 and < comm.size, or None
:arg requested_worker: optional no. of worker to assign the call to.
If None, or the worker is not available, the call is assigned to
the worker with the smallest current total time estimate.
Default: None
"""
if task_id is None:
task_id = self.count
self.count += 1
self.check_valid_task_id(task_id)
if self.workers_available:
self.wait_queue.append(task_id)
self.waiting[task_id] = (
name_to_call,
args,
kwargs,
module_name,
time_est,
requested_worker,
)
else:
# perform call on this rank if no workers are available:
worker = 0
logger.info(f"MPI controller : calling {name_to_call} {args} {kwargs} ...")
object_to_call = None
try:
if module_name not in sys.modules:
importlib.import_module(module_name)
object_to_call = eval(name_to_call, sys.modules[module_name].__dict__)
except NameError:
logger.error(str(sys.modules[module_name].__dict__.keys()))
raise
call_time = time.time()
self.results[task_id] = object_to_call(*args, **kwargs)
self.result_queue.append(task_id)
this_time = time.time() - call_time
self.n_processed[0] += 1
self.total_time[0] = time.time() - start_time
self.stats.append(
{
"id": task_id,
"rank": worker,
"this_time": this_time,
"time_over_est": this_time / time_est,
"n_processed": self.n_processed[0],
"total_time": self.total_time[0],
}
)
return task_id
def submit_waiting(self) -> List[Union[int, Any]]:
"""
Submit waiting tasks if workers are available.
:return object: ids of calls, to be used in get_result().
"""
task_ids = []
if self.workers_available:
if (len(self.waiting) > 0) and len(self.ready_workers) > 0:
reqs = []
status = []
for i in range(len(self.ready_workers)):
if len(self.waiting) == 0:
break
task_id = self.wait_queue.pop(0)
(
name_to_call,
args,
kwargs,
module_name,
time_est,
requested_worker,
) = self.waiting[task_id]
if (requested_worker is None) or (
requested_worker not in self.ready_workers
):
ready_total_time_est = np.asarray(
[
self.total_time_est[worker]
for worker in self.ready_workers
]
)
worker = self.ready_workers[np.argmin(ready_total_time_est)]
else:
worker = requested_worker
# send name to call, args, time_est to worker:
logger.info(
f"MPI controller : assigning waiting call with id {task_id} "
f"to worker {worker}: {name_to_call} {args} {kwargs} ..."
)
req = self.comm.isend(
(name_to_call, args, kwargs, module_name, time_est, task_id),
dest=worker,
tag=MessageTag.TASK.value,
)
reqs.append(req)
status.append(MPI.Status())
self.ready_workers.remove(worker)
del self.ready_workers_data[worker]
self.task_queue.append(task_id)
self.worker_queue[worker].append(task_id)
self.assigned[task_id] = worker
del self.waiting[task_id]
self.total_time_est[worker] += time_est
task_ids.append(task_id)
MPI.Request.waitall(reqs, status)
return task_ids
def submit_multiple(
self,
name_to_call: str,
args: List[List[Any]] = [],
kwargs: Dict[Any, Any] = {},
module_name: str = "__main__",
time_est: int = 1,
task_ids: Optional[int] = None,
workers: Optional[int] = None,
) -> List[int]:
"""Submit multiple calls for parallel execution.
Analogous to submit_call, but accepts lists of arguments and
submits to multiple workers for asynchronous execution.
If called by a worker or if no workers are available, the call is instead
executed synchronously on this MPI node.
:arg str name_to_call: name of callable object (usually a function or
static method of a class) as contained in the namespace specified
by module.
:arg list args: the positional arguments to provide to the callable
object for each task, as a list of tuples. Default: []
:arg list kwargs: the keyword arguments to provide to the callable
object for each task, as a list of dictionaries. Default: []
:arg str module: optional name of the imported module or submodule in
whose namespace the callable object is contained. For objects
defined on the script level, this is "__main__", for objects
defined in an imported package, this is the package name. Must be a
key of the dictionary sys.modules (check there after import if in
doubt). Default: "__main__"
:arg float time_est: estimated relative completion time for this call;
used to find a suitable worker. Default: 1
:type task_ids: list or None
:arg task_ids: unique ids for each call. Must be a possible dictionary key.
If None, a random id is assigned and returned. Can be re-used after
get_result() for this id. Default: None
:type workers: list of int > 0 and < comm.size, or None
:arg worker: optional worker ids to assign the tasks to. If None, the
tasks are assigned in order to the workers with the smallest
current total time estimate. Default: None
:return object: id of call, to be used in get_result().
"""
if len(kwargs) > 0:
assert len(args) == len(kwargs)
submitted_task_ids = []
N = len(args)
if self.workers_available:
self.process()
args, kwargs, task_ids, workers = multiple_task_arguments(
N, args, kwargs, task_ids, workers
)
for this_args, this_kwargs, this_task_id, this_worker in zip(
args, kwargs, task_ids, workers
):
self.check_valid_task_id(this_task_id)
this_task_id = self.queue_call(
name_to_call,
args=this_args,
kwargs=this_kwargs,
module_name=module_name,
time_est=time_est,
task_id=this_task_id,
requested_worker=this_worker,
)
submitted_task_ids.append(this_task_id)
else:
# perform call on this rank if no workers are available:
worker = 0
logger.info(f"MPI controller : calling {name_to_call} {args} {kwargs} ...")
object_to_call = None
try:
if module_name not in sys.modules:
importlib.import_module(module_name)
object_to_call = eval(name_to_call, sys.modules[module_name].__dict__)
except NameError:
logger.error(str(sys.modules[module_name].__dict__.keys()))
raise
args, kwargs, task_ids, workers = multiple_task_arguments(
N, args, kwargs, task_ids, workers
)
for this_args, this_kwargs, this_task_id, this_worker in zip(
args, kwargs, task_ids, workers
):
if this_task_id is None:
this_task_id = self.count
self.count += 1
self.check_valid_task_id(this_task_id)
call_time = time.time()
self.results[this_task_id] = object_to_call(*this_args, **this_kwargs)
self.result_queue.append(this_task_id)
this_time = time.time() - call_time
self.n_processed[0] += 1
self.total_time[0] = time.time() - start_time
self.stats.append(
{
"id": this_task_id,
"rank": worker,
"this_time": this_time,
"time_over_est": this_time / time_est,
"n_processed": self.n_processed[0],
"total_time": self.total_time[0],
}
)
self.total_time_est[this_worker] += time_est
submitted_task_ids.append(this_task_id)
return submitted_task_ids
def get_ready_worker(self):
"""
Returns the id and data of a ready worker.
If there are no workers, or no worker is ready, returns (None, None)
"""
if self.workers_available:
self.process()
if len(self.ready_workers) > 0:
ready_total_time_est = np.asarray(
[self.total_time_est[worker] for worker in self.ready_workers]
)
worker = self.ready_workers[np.argmin(ready_total_time_est)]
return worker, self.ready_workers_data[worker]
else:
return None, None
else:
return None, None
def get_result(
self, task_id: int
) -> Union[
Tuple[int, Tuple[ndarray, ndarray]], Tuple[int, List[Tuple[ndarray, ndarray]]]
]:
"""
Return result of earlier submitted call.
Can only be called by the controller.
If the call is not yet finished, waits for it to finish.
Results should be collected in the same order as calls were submitted.
For each worker, the results of calls assigned to that worker must be
collected in the same order as those calls were submitted.
Can only be called once per call.
:type id: object
:arg id: id of an earlier submitted call, as provided to or returned
by submit_call().
:rtype: object
:return: return value of call.
"""
if task_id in self.results:
return task_id, self.results[task_id]
source = self.assigned[task_id]
if self.workers_available:
if self.worker_queue[source][0] != task_id:
raise RuntimeError(
f"get_result({task_id})) called before get_result("
f"{self.worker_queue[source][0]})"
)
logger.info(
f"MPI controller : retrieving result for call with id {task_id} "
f"from worker {source} ..."
)
while task_id not in self.results:
self.process()
logger.info(
f"MPI controller : received result for call with id {task_id} "
f"from worker {source}."
)
else:
logger.info(
f"MPI controller : returning result for call with id {task_id} " "..."
)
result = self.results[task_id]
self.result_queue.remove(task_id)
return task_id, result
def get_next_result(
self,
) -> Optional[
Union[
Tuple[int, Tuple[ndarray, ndarray]],
Tuple[int, List[Tuple[ndarray, ndarray]]],
]
]:
"""
Return result of next earlier submitted call whose result has not yet
been obtained.
Can only be called by the controller.
If the call is not yet finished, waits for it to finish.
:rtype: object
:return: id, return value of call, or None of there are no more calls in
the queue.
"""
self.process()
if len(self.result_queue) > 0:
task_id = self.result_queue.pop(0)
return task_id, self.results[task_id]
elif len(self.task_queue) > 0:
task_id = self.task_queue[0]
return task_id, self.get_result(task_id)[1]
else:
return None
def probe_next_result(self):
"""
Return result of next earlier submitted call whose result has not yet
been obtained.
Can only be called by the controller.
If no result is available, returns none.
:rtype: object
:return: id, return value of call, or None of there are no results ready.
"""
self.process()
if len(self.result_queue) > 0:
task_id = self.result_queue.pop(0)
logger.info(
f"MPI controller : received result for call with id {task_id} ..."
)
return task_id, self.results[task_id]
else:
return None
def probe_all_next_results(self):
"""
Return all available results of earlier submitted calls whose result has not yet
been obtained.
Can only be called by the controller.
If no result is available, returns empty list.
:rtype: object
:return: list of id, return value of call
"""
self.process()
ret = []
if len(self.result_queue) > 0:
for i in range(len(self.result_queue)):
task_id = self.result_queue.pop(0)
logger.info(
f"MPI controller : received result for call with id {task_id} ..."
)
ret.append((task_id, self.results[task_id]))
return ret
def info(self) -> None:
"""
Print processing statistics.
Can only be called by the controller.
"""
if len(self.stats) == 0:
return
call_times = np.array([s["this_time"] for s in self.stats])
call_quotients = np.array([s["time_over_est"] for s in self.stats])
cvar_call_quotients = call_quotients.std() / call_quotients.mean()
if self.workers_available:
worker_quotients = self.total_time / self.total_time_est
cvar_worker_quotients = worker_quotients.std() / worker_quotients.mean()
print(
"\n"
"distwq run statistics\n"
"==========================\n"
" results collected: "
f"{self.n_processed[1:].sum()}\n"
" results not yet collected: "
f"{len(self.task_queue)}\n"
" total reported time: "
f"{call_times.sum():.04f}\n"
" mean time per call: "
f"{call_times.mean():.04f}\n"
" std.dev. of time per call: "
f"{call_times.std():.04f}\n"
" coeff. of var. of actual over estd. time per call: "
f"{cvar_call_quotients:.04f}\n"
" workers: "
f"{n_workers}\n"
" mean calls per worker: "
f"{self.n_processed[1:].mean():.04f}\n"
" std.dev. of calls per worker: "
f"{self.n_processed[1:].std():.04f}\n"
" min calls per worker: "
f"{self.n_processed[1:].min()}\n"
" max calls per worker: "
f"{self.n_processed[1:].max()}\n"
" mean time per worker: "
f"{self.total_time.mean():.04f}\n"
" std.dev. of time per worker: "
f"{self.total_time.std():.04f}\n"
" coeff. of var. of actual over estd. time per worker: "
f"{cvar_worker_quotients:.04f}\n"
)
else:
print(
"\n"
"distwq run statistics\n"
"==========================\n"
" results collected: "
f"{self.n_processed[0]}\n"
" results not yet collected: "
f"{len(self.task_queue)}\n"
" total reported time: "
f"{call_times.sum():.04f}\n"
" mean time per call: "
f"{call_times.mean():.04f}\n"
" std.dev. of time per call: "
f"{call_times.std():.04f}\n"
" coeff. of var. of actual over estd. time per call: "
f"{cvar_call_quotients:.04f}\n"
)
def exit(self) -> None:
"""
Tell all workers to exit.
Can only be called by the controller.
"""
if self.workers_available:
while self.get_next_result() is not None:
pass
# tell workers to exit:
reqs = []
for worker in self.active_workers:
logger.info(f"MPI controller : telling worker {worker} " "to exit...")
reqs.append(
self.comm.isend(None, dest=worker, tag=MessageTag.EXIT.value)
)
MPI.Request.Waitall(reqs)
def abort(self):
"""
Abort execution on all MPI nodes immediately.
Can be called by controller and workers.
"""
traceback.print_exc()
logger.error("MPI controller : aborting...")
self.comm.Abort()
def check_valid_task_id(self, task_id: int) -> bool:
"""
Given a new task id, check that it is not already assigned or waiting.
"""
if task_id in self.assigned:
raise RuntimeError(f"task id {task_id} already in queue!")
if task_id in self.waiting:
raise RuntimeError(f"task id {task_id} already in wait queue!")
return True
class MPIWorker(object):
def __init__(
self, comm: Intracomm, group_comm: Intracomm, ready_data: Optional[Any] = None
) -> None:
size = comm.size
rank = comm.rank
self.comm = comm
self.group_comm = group_comm
self.worker_id = group_comm.rank + 1
self.total_time_est = np.zeros(size) * np.nan
self.total_time_est[rank] = 0
self.n_processed = np.zeros(size) * np.nan
self.n_processed[rank] = 0
self.start_time = start_time
self.total_time = np.zeros(size) * np.nan
self.total_time[rank] = 0
self.stats = []
self.ready_data = None
logger.info(f"MPI worker {self.worker_id}: initialized.")
def serve(self) -> None:
"""
Serve submitted calls until told to finish.
Call this function if workers need to perform initialization
different from the controller, like this:
>>> def workerfun(worker):
>>> do = whatever + initialization - is * necessary
>>> worker.serve()
>>> do = whatever + cleanup - is * necessary
If you don't define workerfun(), serve() will be called automatically by
run().
"""
rank = self.comm.rank
logger.info(f"MPI worker {rank}: waiting for calls.")
# wait for orders: