-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstart.py
More file actions
3100 lines (2420 loc) · 127 KB
/
start.py
File metadata and controls
3100 lines (2420 loc) · 127 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
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/env python3
# https://wiki.python.org/moin/PyQt
# https://www.riverbankcomputing.com/static/Docs/PyQt5/
# Example of path to designer in Windows OS: Python38/Lib/site-packages/qt5_applications/Qt/bin/designer.exe
import sys, platform, time, shutil, pickle, threading, math, socket
import datetime
import os
import psutil
import gc
import random
import copy
import numpy as np
import torch
import logging
# Qt namespace is a full list of attributes that you can use to customize and control Qt widgets
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox, QDialog, QFileDialog, QFontDialog
from PyQt5 import QtCore, QtGui, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
sys.path.append(os.path.join(os.path.dirname(__file__), "./generated"))
sys.path.append(os.path.join(os.path.dirname(__file__), "./../"))
sys.path.append(os.path.join(os.path.dirname(__file__), "./"))
from generated import MainView, AboutBox, ConfigWidget, LogWindow,\
SimulationWidget, AnalysisWidget, MultiMachineSelector
from utils import gpu_utils, comm_socket, git_utils, algorithms
import utils
import run
import data_preprocess
# Import PyTorch root package import torch
import torch
import matplotlib
from torch.utils.collect_env import get_pretty_env_info
# Matplotlib functionality
import matplotlib
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
# Import the toolbar widget for matplotlib
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
# Configure that plots from Matplotlib displayed in PyQt5 are actually rendered by the Agg backend.
matplotlib.use("Qt5Agg")
class MplCanvas(FigureCanvasQTAgg):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
self.fig = fig
super().__init__(fig)
# Instantiate toolbar. First arg - is canvas for rendering, and second is parent of toolbar.
self.toolbar = NavigationToolbar(self, parent)
app = None # Application object
mainView = None # Main window
logView = None # Log window
configView = None # Configuration window
simulationView = None # Widget for simulation
analysisView = None # Widget for analysis
simulationThreadPool = utils.thread_pool.ThreadPool() # Simulation main threads
sim_stats_res_lock = threading.Lock() # Locker for next 4 data objects
earlyStopSimulations = set() # Set of early stop simulations job_id
simulations_stats = {} # Simulations key - job_id, value collected statistics
simulations_result = {} # Simulation result, key - job_id, value server-state (stop to change)
simulations_by_rows = [] # Simulations, index - row in table, value - job_id
gui_rnd = random.Random() # Random generator in UI
machineDescriptions = [] # Description of external used compute resources
# ======================================================================================================================
compressorTypes = ["ident", "randk",
"bernulli", "natural",
"qsgd", "nat.dithering", "std.dithering", "topk",
"rank_k",
"terngrad"]
compressorFormats = ["", "randk:<percentage-of-D [0,100]>% | randk:k[1,D]",
"bernulli:p[0,1]", "",
"qsgd:levels", "nat.dithering:levels:norm", "std.dithering:levels:norm",
"topk:<percentage-of-D [0,100]>% | topk:<K>[1,D]",
"rank_k:<percentage-of-D [0,100]>% | rank_k:<K>[1,D]",
""]
# ======================================================================================================================
requestUpdateResultTable = False
def showArtificialDatasetParameters(show=True):
configView.lblL.setVisible(show)
configView.edtL.setVisible(show)
configView.lblMu.setVisible(show)
configView.edtMu.setVisible(show)
if show:
configView.edtNumberOfClients.setReadOnly(False)
configView.edtNumberOfClients.setStyleSheet("background-color: rgb(255, 255, 255);")
configView.lblGlobalModel.setVisible(False)
configView.cbxGlobalModel.setVisible(False)
configView.lblLossFunctionForGlobalModel.setVisible(False)
configView.cbxLossFunctionForGlobalModel.setVisible(False)
configView.lblSamplesPerClient.setVisible(True)
configView.edtSamplesPerClient.setVisible(True)
configView.lblHomogeneousDS.setVisible(True)
configView.cbxHomogeneousDS.setVisible(True)
configView.lblValidationOptMetric.setVisible(False)
configView.cbxValidationOptMetric.setVisible(False)
configView.lblVarsInOpt.setVisible(True)
configView.edtVarsInOpt.setVisible(True)
else:
configView.edtNumberOfClients.setReadOnly(True)
configView.edtNumberOfClients.setStyleSheet("background-color: rgb(233, 185, 110);")
configView.lblGlobalModel.setVisible(True)
configView.cbxGlobalModel.setVisible(True)
configView.lblLossFunctionForGlobalModel.setVisible(True)
configView.cbxLossFunctionForGlobalModel.setVisible(True)
configView.lblSamplesPerClient.setVisible(False)
configView.edtSamplesPerClient.setVisible(False)
configView.lblHomogeneousDS.setVisible(False)
configView.cbxHomogeneousDS.setVisible(False)
configView.lblValidationOptMetric.setVisible(True)
configView.cbxValidationOptMetric.setVisible(True)
configView.lblVarsInOpt.setVisible(False)
configView.edtVarsInOpt.setVisible(False)
def totalSimulations():
res = 0
for th in simulationThreadPool.threads:
res += len(th.cmds)
return res
def onMoveToNextTabInMain():
"""Move to the next tab in a cyclic way in a tabs inside a main window"""
mainView.tabMainView.setCurrentIndex((mainView.tabMainView.currentIndex() + 1) % mainView.tabMainView.count())
def onMoveToPrevTabInMain():
"""Move to the prev tab in a cyclic way in a tabs inside a main window"""
prev = mainView.tabMainView.currentIndex() - 1
while prev < 0:
prev += mainView.tabMainView.count()
mainView.tabMainView.setCurrentIndex(prev)
def onShowAboutDialog():
"""Show about dialog"""
about_box = QDialog()
about_box_ui = AboutBox.Ui_AboutBox()
about_box_ui.setupUi(about_box)
about_box.ui = about_box_ui
about_box_ui.btnCloseAbout.clicked.connect(lambda: about_box.close())
# Update information about the program
programInfo = "FL_PyTorch Optimization Research Tool, 2022.\n"
programInfo += "\n"
programInfo += f"Branch name: {git_utils.branch()}\n"
programInfo += f"Revision: {git_utils.revision()}\n"
programInfo += f"Data of last revision submission: {git_utils.dateAndTimeOfLastRevision()}\n"
programInfo += "\n"
programInfo += f"Current working directory: {os.getcwd()}\n"
programInfo += f"Executed program: {__file__}\n"
programInfo += "\n"
programInfo += f"Python: {sys.executable}\n"
programInfo += f"Python version: {sys.version}\n"
programInfo += f"Platform name: {sys.platform}\n"
programInfo += "\n"
programInfo += f"PyTorch version: {torch.__version__}\n"
programInfo += f"Matplotlib version: {matplotlib.__version__}\n"
programInfo += f"Qt version: {QtCore.qVersion()}\n"
programInfo += f"NumPy version: {np.__version__}\n"
programInfo += "\n"
programInfo += "Repository: https://github.com/burlachenkok/flpytorch\n"
programInfo += "Paper: https://dl.acm.org/doi/abs/10.1145/3488659.3493775"
about_box_ui.edtText.setText(programInfo)
about_box.show()
about_box.exec_()
def uiLogInfo(text):
prevText = logView.txtMain.toPlainText()
logView.txtMain.setPlainText(prevText + text + "\n")
def onMemoryInfo():
process = psutil.Process(os.getpid())
uiLogInfo(f'Allocated resident host (CPU) memory {process.memory_info().rss / (1024 ** 2):.2f} MBytes')
uiLogInfo(f'Reserved virtual host (CPU) memory {process.memory_info().vms / (1024 ** 2):.2f} MBytes')
mem = psutil.virtual_memory()
uiLogInfo(f'Available physical RAM memory in a system {mem.total / (1024**3):.2f} GBytes')
gpus_properties = gpu_utils.get_available_gpus()
uiLogInfo(f"Number of installed GPUs in the system: {len(gpus_properties)}")
for i in range(len(gpus_properties)):
device = "cuda:" + str(i)
memory_gpu = torch.cuda.memory_stats(device)['reserved_bytes.all.current']
uiLogInfo(" {0}. Used {1:.2f} MBytes. Available {2:.2f} MBytes GDDR".format(gpus_properties[i].name,
memory_gpu/1024.0/1024.0,
gpus_properties[i].total_memory /
(1024. ** 2)
)
)
def onExitLogWindow():
"""Close log window"""
logView.close()
def onExitMachineSelectorWindow():
"""Close machine selector window"""
machinesView.close()
def onCmdLineGenerationForCurrentExperiment(withNewLines):
"""Generate command line for current experiment"""
python = "python"
if True:
cmds = currentCommandLineFromGUI()
job_id = "current"
cmdline = ""
cmdline_new_line = " \\" # For Bash
for item in cmds:
item = item.strip()
if item.find("--") == 0:
# Move to new line
if withNewLines:
cmdline += cmdline_new_line + "\n" + item
else:
cmdline += " " + item
elif len(item) == 0:
# Empty argument - escaping with ""
cmdline += " "
cmdline += '""'
else:
# Extra escaping for possible arguments
cmdline += " "
cmdline += ('"' + item + '"')
# Add output filename for cmdline
if withNewLines:
cmdline += (cmdline_new_line + "\n" + f'--out "{job_id}.bin"')
else:
cmdline += (" " + f'--out "{job_id}.bin"')
cmdline = f"{python} run.py" + cmdline
cmdline = cmdline.strip()
uiLogInfo(f"# ===========================================================")
uiLogInfo(f"{datetime.datetime.now()}")
uiLogInfo(f"# ===========================================================")
uiLogInfo(f"# Command line for currently selected configuration in GUI")
uiLogInfo(cmdline)
uiLogInfo(f"# ===========================================================")
uiLogInfo("")
def onCmdLineGenerationForFinishedExperiments(withNewLines):
"""Generate command line for finished experiments and current experiment"""
python = "python"
for job_id in simulations_stats.keys():
sim_stats_res_lock.acquire()
cmds = simulations_stats[job_id]['H']['raw_cmdline']
sim_stats_res_lock.release()
cmdline = ""
cmdline_new_line = " \\" # For Bash
for item in cmds:
item = item.strip()
if item.find("--") == 0:
# Move to new line
if withNewLines:
cmdline += cmdline_new_line + "\n" + item
else:
cmdline += " " + item
elif len(item) == 0:
# Empty argument - escaping with ""
cmdline += " "
cmdline += '""'
else:
# Extra escaping for possible arguments
cmdline += " "
cmdline += ('"' + item + '"')
# Add output filename for cmdline
if withNewLines:
cmdline += (cmdline_new_line + "\n" + f'--out "{job_id}.bin"')
else:
cmdline += (" " + f'--out "{job_id}.bin"')
cmdline = f"{python} run.py" + cmdline
cmdline = cmdline.strip()
uiLogInfo(f"# Command line for experiment with job_id={job_id}")
uiLogInfo(cmdline)
uiLogInfo("")
def onExperimentInfoGeneration():
"""Generate description information about current numerical experiment"""
algorithm = configView.cbxOptAlgo.currentText().lower()
docString = algorithms.getImplClassForAlgo(algorithm).__doc__
docString = docString.replace("\r\n", "").replace("\n", "")
uiLogInfo("Optimization Algorithm:")
uiLogInfo(docString)
def onCleanupMemory():
process = psutil.Process(os.getpid())
memory_cpu_start = (process.memory_info().rss + process.memory_info().vms) # in bytes
gpus_properties = gpu_utils.get_available_gpus()
memory_gpu_start = []
memory_gpu_end = []
for i in range(len(gpus_properties)):
device = "cuda:" + str(i)
# get the current active allocated memory in bytes
memory_gpu_start.append(torch.cuda.memory_stats(device)['reserved_bytes.all.current'])
# do the garbage collection
uiLogInfo('Release unoccupied cache memory from PyTorch...')
torch.cuda.empty_cache()
uiLogInfo('Running the garbage collector...')
gc.collect() # gc is the garbage collection module
memory_cpu_end = (process.memory_info().rss + process.memory_info().vms) # in bytes
memory_freed = abs(memory_cpu_start - memory_cpu_end)
uiLogInfo(f' Done. {memory_freed / 1024 ** 2:.2f} MB was removed from Virtual and Resident memory of interpreter. Current used amount of memory is {memory_cpu_end/ 1024 ** 2:.2f} MBytes')
for i in range(len(gpus_properties)):
device = "cuda:" + str(i)
# get the current active allocated memory in bytes
memory_gpu_end.append(torch.cuda.memory_stats(device)['reserved_bytes.all.current'])
memory_freed = memory_gpu_start[i] - memory_gpu_end[i]
uiLogInfo(f' Done. {memory_freed / 1024 ** 2:.2f} MB was removed from {device}. Current used amount of memory is {memory_gpu_end[-1]/ 1024 ** 2:.2f} MBytes')
def onLogSystemInformation():
"""Append some default information into log window"""
uiLogInfo("Information about Python")
uiLogInfo(f" Path to python: {sys.executable}")
uiLogInfo(f" Python version: {sys.version}")
uiLogInfo(f" Platform name: {sys.platform}")
uiLogInfo(f" Current working directory: {os.getcwd()}")
uiLogInfo("")
uiLogInfo("Information about System")
(system, node, release, version, machine, processor) = platform.uname()
uiLogInfo(f" System/OS name: {system}/{release}/{version}")
uiLogInfo(f" Machine name: {machine}")
uiLogInfo(f" Host name: {socket.gethostname()}")
uiLogInfo(f" IP address of one Network Interface: {socket.gethostbyname(socket.gethostname())}")
uiLogInfo("")
uiLogInfo("Information about installed compute devices")
uiLogInfo(f" CPU name: {processor}")
gpus_properties = gpu_utils.get_available_gpus()
uiLogInfo(f" Number of installed GPUs in the system: {len(gpus_properties)}")
for i in range(len(gpus_properties)):
uiLogInfo(" {0} {1:g} GBytes of GDDR".format(gpus_properties[i].name, gpus_properties[i].total_memory / (1024.0 ** 3)))
uiLogInfo("")
uiLogInfo("Information about installed software")
uiLogInfo(f" PyTorch version: {torch.__version__}")
uiLogInfo(f" Matplotlib version: {matplotlib.__version__}")
uiLogInfo(f" Qt version: {QtCore.qVersion()}")
uiLogInfo(f" NumPy version: {np.__version__}")
def isSimulationNeedEarlyStop(H):
"""Predictor which provide information do we need early stopping"""
global earlyStopSimulations
global sim_stats_res_lock
result = False
sim_stats_res_lock.acquire()
if H['run_id'] in earlyStopSimulations:
result = True # Report that this simulation need early stop
earlyStopSimulations.discard(H['run_id']) # Remove job_id for simulation
sim_stats_res_lock.release()
return result
def simulationProgressSteps(progress, H):
job_id = H["run_id"]
# dataload_duration = []
# inference_duration = []
# backprop_duration = []
# full_gradient_oracles = []
# samples_gradient_oracles = []
# send_scalars_to_master = []
# =================================================================================================================
for round, round_info in H['history'].items():
for client_id, client_summary in round_info['client_states'].items():
client_stats = client_summary['client_state']['stats']
# dataload_duration.append(client_stats['dataload_duration'])
# inference_duration.append(client_stats['inference_duration'])
# backprop_duration.append(client_stats['backprop_duration'])
# full_gradient_oracles.append(client_stats['full_gradient_oracles'])
# samples_gradient_oracles.append(client_stats['samples_gradient_oracles'])
# send_scalars_to_master.append(client_stats['send_scalars_to_master'])
# ==================================================================================================================
sim_stats_res_lock.acquire()
simulations_stats[job_id]["progress"] = int(100 * progress)
rounds = H['history'].keys()
simulations_stats[job_id]["completed_rounds"] = len(rounds)
simulations_stats[job_id]["best_metric"] = H["best_metric"]
if 'th_stepsize_noncvx' in H:
simulations_stats[job_id]["th_stepsize_noncvx"] = H['th_stepsize_noncvx']
if 'th_stepsize_cvx' in H:
simulations_stats[job_id]["th_stepsize_cvx"] = H['th_stepsize_cvx']
if len(rounds) > 0:
current_round = max(rounds)
simulations_stats[job_id]["grad_sgd_server_l2"] = H['history'][current_round]['grad_sgd_server_l2']
simulations_stats[job_id]["approximate_f_avg_value"] = H['history'][current_round]['approximate_f_avg_value']
# if len(dataload_duration) > 0:
# simulations_stats[job_id]["dataload_duration_avg"] = sum(dataload_duration)/len(dataload_duration)
# if len(inference_duration) > 0:
# simulations_stats[job_id]["inference_duration_avg"] = sum(inference_duration)/len(inference_duration)
# if len(backprop_duration) > 0:
# simulations_stats[job_id]["backprop_duration_avg"] = sum(backprop_duration)/len(backprop_duration)
# if len(full_gradient_oracles) > 0:
# simulations_stats[job_id]["full_gradient_oracles_avg"] = sum(full_gradient_oracles)/len(full_gradient_oracles)
# if len(samples_gradient_oracles) > 0:
# simulations_stats[job_id]["samples_gradient_oracles_avg"] = sum(samples_gradient_oracles)/len(samples_gradient_oracles)
# if len(send_scalars_to_master) > 0:
# simulations_stats[job_id]["send_scalars_to_master"] = sum(send_scalars_to_master)/len(send_scalars_to_master)
simulations_stats[job_id]["H"] = H
if "server_state_update_time" in H:
simulations_stats[job_id]["server_state_update_time"] = H["server_state_update_time"]
if "last_round_elapsed_sec" in H:
simulations_stats[job_id]["last_round_elapsed_sec"] = H["last_round_elapsed_sec"]
sim_stats_res_lock.release()
# ==================================================================================================================
# Make request for update table for analysis
global requestUpdateResultTable
requestUpdateResultTable = True
# ==================================================================================================================
def simulationFinishInternal(H, lock):
job_id = H["run_id"]
if lock:
sim_stats_res_lock.acquire()
earlyStopSimulations.discard(H['run_id'])
simulations_result[job_id] = H
for item in vars(H["args"]):
simulations_stats[job_id][item] = getattr(H["args"], item)
if 'th_step_size_cvx' in H:
simulations_stats[job_id]["th_step_size_cvx"] = H['th_step_size_cvx']
if 'th_step_size_nocvx' in H:
simulations_stats[job_id]["th_step_size_nocvx"] = H['th_step_size_nocvx']
simulations_stats[job_id]["best_metric"] = H["best_metric"]
simulations_stats[job_id]["D"] = H["D"]
simulations_stats[job_id]["D_include_frozen"] = H["D_include_frozen"] # dimension of the problem including frozen variables(not trainable)
simulations_stats[job_id]["progress"] = 100
simulations_stats[job_id]["completed_rounds"] = len(H['history'])
simulations_stats[job_id]["finished"] = True
# ==================================================================================================================
simulations_stats[job_id]["client_compressor"] = H["client_compressor"]
if "xfinal" in H:
simulations_stats[job_id]["xfinal"] = H["xfinal"]
if "used_x_solution" in H:
simulations_stats[job_id]["used_x_solution"] = H["used_x_solution"]
if "server_state_update_time" in H:
simulations_stats[job_id]["server_state_update_time"] = H["server_state_update_time"]
if "last_round_elapsed_sec" in H:
simulations_stats[job_id]["last_round_elapsed_sec"] = H["last_round_elapsed_sec"]
simulations_stats[job_id]["args"] = H["args"]
if "group-name" in H:
simulations_stats[job_id]["group-name"] = H["group-name"]
# ==================================================================================================================
rounds = H['history'].keys()
if len(rounds) > 0:
current_round = max(rounds)
simulations_stats[job_id]["grad_sgd_server_l2"] = H['history'][current_round]['grad_sgd_server_l2']
#simulations_stats[job_id]["xi_after"] = [H['history'][k]['xi_after'] for k in H['history'].keys()]
simulations_stats[job_id]["approximate_f_avg_value"] = H['history'][current_round]['approximate_f_avg_value']
simulations_stats[job_id]["H"] = H
if lock:
sim_stats_res_lock.release()
# Force updating table with results
global requestUpdateResultTable
requestUpdateResultTable = True
def simulationFinish(H):
return simulationFinishInternal(H, lock = True)
def simulationStart(H):
job_id = H["run_id"]
stats = {"progress": 0, "finished": False}
# copy all args for launching
for item in vars(H["args"]):
stats[item] = getattr(H["args"], item)
stats["D"] = H["D"] # dimension of the problem
stats["D_include_frozen"] = H["D_include_frozen"] # dimension of the problem including frozen variables(not trainable)
stats["completed_rounds"] = 0 # number of completed rounds
stats["finished"] = False # flag about the fact that job is finished
stats["client_compressor"] = H["client_compressor"]
if "start_time" in H:
stats["start_time"] = H["start_time"]
if "server_state_update_time" in H:
stats["server_state_update_time"] = H["server_state_update_time"]
if "last_round_elapsed_sec" in H:
simulations_stats[job_id]["last_round_elapsed_sec"] = H["last_round_elapsed_sec"]
stats["args"] = H["args"]
stats["progress"] = int(0)
stats["H"] = H
if "group-name" in H:
stats["group-name"] = H["group-name"]
if "x0" in H:
stats["x0_l2_norm"] = torch.linalg.norm(H["x0"])
stats["x0"] = H["x0"]
if "xfinal" in H:
stats["xfinal"] = H["xfinal"]
# stats["dataload_duration_avg"] = 0
# stats["inference_duration_avg"] = 0
# stats["backprop_duration_avg"] = 0
# stats["full_gradient_oracles_avg"] = 0
# stats["samples_gradient_oracles_avg"] = 0
# stats["send_scalars_to_master"] = 0
sim_stats_res_lock.acquire()
simulations_stats[job_id] = stats
simulations_by_rows.append(job_id)
sim_stats_res_lock.release()
# Make request for update table for analysis
global requestUpdateResultTable
requestUpdateResultTable = True
# ======================================================================================================================
class ProgressDelegate(QtWidgets.QStyledItemDelegate):
"""Progress bar delegate to experiment status"""
def paint(self, painter, option, index):
progress, is_terminated_early = index.data(QtCore.Qt.UserRole + 1000)
opt = QtWidgets.QStyleOptionProgressBar()
opt.rect = option.rect
opt.minimum = 0
opt.maximum = 100
opt.progress = progress
opt.text = "{}%".format(progress)
opt.textVisible = True
if is_terminated_early:
opt.palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(157, 13, 20))
QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_ProgressBar, opt, painter)
# ======================================================================================================================
class StatusDelegate(QtWidgets.QStyledItemDelegate):
"""Status delegate which is dedicated to report about remote machine status online/offline"""
def paint(self, painter, option, index):
online = index.data(QtCore.Qt.UserRole + 2000)
brush = QtGui.QBrush()
brush.setStyle(Qt.SolidPattern)
rect = QtCore.QRect(option.rect)
if online:
brush.setColor(QtGui.QColor("green"))
painter.fillRect(rect, brush)
painter.drawText(option.rect, Qt.AlignLeft, "online")
else:
brush.setColor(QtGui.QColor("grey"))
painter.fillRect(rect, brush)
painter.drawText(option.rect, Qt.AlignLeft, "offline")
# ======================================================================================================================
def onUpdateStatusForExternalResources():
"""Update connection status for a remote resources"""
# Retrieve information from the network
for i in range(len(machineDescriptions)):
descr = machineDescriptions[i]
try:
s = comm_socket.CommSocket()
# Use 5 socket timeout to setup a connection with a remote side
s.sock.settimeout(5)
s.sock.connect((descr["ip"], descr["port"]))
descr["online"] = True
s.rawSendString("list_of_gpus")
gpu_count = int(s.rawRecvString())
descr["devices"] = ["cpu:-1"]
for i in range(gpu_count):
descr["devices"].append(f"gpu:{i}")
except socket.error as exc:
# print(exc)
descr["devices"] = []
descr["online"] = False
# ==================================================================================================================
# Fill the table
for r in range(machinesView.tblMachines.rowCount()):
descr = machineDescriptions[r]
it_name = machinesView.tblMachines.item(r, 0)
it_ip = machinesView.tblMachines.item(r, 1)
it_port = machinesView.tblMachines.item(r, 2)
it_gpus = machinesView.tblMachines.item(r, 3)
it_use_cpu = machinesView.tblMachines.item(r, 4)
it_use_gpu1 = machinesView.tblMachines.item(r, 5)
it_use_gpu2 = machinesView.tblMachines.item(r, 6)
it_use_gpu3 = machinesView.tblMachines.item(r, 7)
it_use_gpu4 = machinesView.tblMachines.item(r, 8)
it_online = machinesView.tblMachines.item(r, 9)
it_gpus.setText(str(len([d for d in descr["devices"] if d.find("cpu") == -1])))
it_online.setData(QtCore.Qt.UserRole + 2000, descr["online"])
if "cpu:-1" in descr["devices"]:
it_use_cpu.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
else:
it_use_cpu.setFlags(QtCore.Qt.NoItemFlags)
if "gpu:0" in descr["devices"]:
it_use_gpu1.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
else:
it_use_gpu1.setFlags(QtCore.Qt.NoItemFlags)
if "gpu:1" in descr["devices"]:
it_use_gpu2.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
else:
it_use_gpu2.setFlags(QtCore.Qt.NoItemFlags)
if "gpu:2" in descr["devices"]:
it_use_gpu3.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
else:
it_use_gpu3.setFlags(QtCore.Qt.NoItemFlags)
if "gpu:3" in descr["devices"]:
it_use_gpu4.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
else:
it_use_gpu4.setFlags(QtCore.Qt.NoItemFlags)
# ==================================================================================================================
# Force update view for machines
machinesView.tblMachines.update()
# ==================================================================================================================
def onTimerEvent():
w = simulationView.tblExperiments
sim_stats_res_lock.acquire()
while w.rowCount() < len(simulations_by_rows):
it_id = QtWidgets.QTableWidgetItem("")
it_device = QtWidgets.QTableWidgetItem("")
it_progress = QtWidgets.QTableWidgetItem()
w.insertRow(w.rowCount())
r = w.rowCount() - 1
it_progress.setFlags(it_progress.flags() ^ QtCore.Qt.ItemIsEditable)
it_device.setFlags(it_device.flags() ^ QtCore.Qt.ItemIsEditable)
for c, item in enumerate((it_id, it_device, it_progress)):
w.setItem(r, c, item)
for i in range(len(simulations_by_rows)):
job_id = simulations_by_rows[i]
progress = simulations_stats[job_id]["progress"]
device_id = simulations_stats[job_id]["gpu"]
# For comfortable of GUI user represent single device as single string
if type(device_id) is list and len(device_id) == 1:
device_id = device_id[0]
w.item(i, 0).setText(job_id)
w.item(i, 1).setText(str(device_id))
is_terminated_early = False
if simulations_stats[job_id]["finished"] and \
simulations_stats[job_id]["completed_rounds"] < simulations_stats[job_id]["rounds"]:
is_terminated_early = True
w.item(i, 2).setData(QtCore.Qt.UserRole + 1000, (progress, is_terminated_early) )
if totalSimulations() == 0:
# Disable remove experiment button
simulationView.btnRemoveExperiments.setEnabled(True)
simulationView.btnClean.setEnabled(True)
else:
# Enable remove experiment button
simulationView.btnRemoveExperiments.setEnabled(False)
simulationView.btnClean.setEnabled(False)
sim_stats_res_lock.release()
while w.rowCount() > len(simulations_by_rows):
w.removeRow(w.rowCount() - 1)
updateMemoryUsageStatus()
global requestUpdateResultTable
if requestUpdateResultTable:
onUpdateTableForAnalysis()
requestUpdateResultTable = False
# ==================================================================================================================
# Update titles of tabs in analysis widget
tab_index = analysisView.tabWidget.currentIndex()
if analysisView.cbxSyncTitleWithTabName.checkState() == Qt.Checked:
setup_text = analysisView.customPlots[tab_index].axes.title.get_text()
else:
setup_text = f"Plot-{tab_index+1}"
if setup_text != analysisView.tabWidget.tabText(tab_index):
analysisView.tabWidget.setTabText(tab_index, setup_text)
# ==================================================================================================================
def cbxClientSamplingTypeSelection(index):
algo = configView.cbxClientSamlingType.currentText().lower()
if algo == "uniform sampling":
configView.lblPoissonSampling.setVisible(False)
configView.edtPoissonSampling.setVisible(False)
configView.lblNumClientsPerRound.setVisible(True)
configView.edtNumClientsPerRound.setVisible(True)
elif algo == "poisson sampling" or algo == "poisson sampling with no empty sample":
configView.lblPoissonSampling.setVisible(True)
configView.edtPoissonSampling.setVisible(True)
configView.lblNumClientsPerRound.setVisible(False)
configView.edtNumClientsPerRound.setVisible(False)
def cbxOptAlgorithmSelection(index):
algo = configView.cbxOptAlgo.currentText().lower()
#if algo == "fedprox":
# configView.edtExperimentalExtraOpts.setText("mu_prox:0.1")
def cleanupFromComments(input, startComment = "(", endComment = ")"):
'''Remove comments in form (my comment), and remove beginning and ending whitespaces '''
while True:
s = input.find("(")
e = input.find(")")
if s == -1 or e == -1:
break
else:
input = input[:max(0,s)] + input[e+1:]
return input.strip()
def currentCommandLineFromGUI():
"""Generate comman line arguments"""
# Automatically generate seeds
if configView.cbxGenerateInitSeedAuto.checkState() == Qt.Checked:
configView.edtRandomInitSeed.setText(str(gui_rnd.randint(1, 10**9)))
if configView.cbxGenerateRunSeedAuto.checkState() == Qt.Checked:
configView.edtRandomRunSeed.setText(str(gui_rnd.randint(1, 10**9)))
# Arguments for command line
cmdline = []
cmdline.append("--rounds")
cmdline.append(configView.edtComRounds.text())
sampling_index_type = configView.cbxClientSamlingType.currentIndex()
if sampling_index_type == 0:
cmdline.append("--client-sampling-type")
cmdline.append("uniform")
cmdline.append("--num-clients-per-round")
cmdline.append(configView.edtNumClientsPerRound.text())
elif sampling_index_type == 1:
cmdline.append("--client-sampling-type")
cmdline.append("poisson")
cmdline.append("--client-sampling-poisson")
cmdline.append(configView.edtPoissonSampling.text())
elif sampling_index_type == 2:
cmdline.append("--client-sampling-type")
cmdline.append("poisson-no-empty")
cmdline.append("--client-sampling-poisson")
cmdline.append(configView.edtPoissonSampling.text())
cmdline.append("--global-lr")
cmdline.append(configView.edtGlbInitLearningRate.text())
cmdline.append("--global-optimiser")
cmdline.append(configView.cbxGlobalOptimizer.currentText())
cmdline.append("--global-weight-decay")
cmdline.append(configView.edtGlobalWeightDecay.text())
cmdline.append("--number-of-local-iters")
cmdline.append(configView.edtLocalIterations.text())
if configView.cbxLocalIterationsType.currentText() == "local-steps":
cmdline.append("--run-local-steps")
cmdline.append("--batch-size")
cmdline.append(configView.edtDataLoadBatchSize.text())
cmdline.append("--local-lr")
cmdline.append(configView.edtLocalInitialLr.text())
cmdline.append("--local-optimiser")
cmdline.append(configView.cbxLocalOpt.currentText())
cmdline.append("--local-weight-decay")
cmdline.append(configView.edtLocalWeightDecay.text())
ds = configView.cbxDataset.currentText().lower()
cmdline.append("--dataset")
cmdline.append(ds)
# Dataset generation specification
if ds == "generated_for_quadratic_minimization":
dsGenSpec = []
dsGenSpec.append(f"homogeneous:{int(configView.cbxHomogeneousDS.checkState() == Qt.Checked)}")
dsGenSpec.append(f"mu:{str(configView.edtMu.text())}")
dsGenSpec.append(f"L:{str(configView.edtL.text())}")
dsGenSpec.append(f"samples_per_client:{str(configView.edtSamplesPerClient.text())}")
dsGenSpec.append(f"clients:{str(configView.edtNumberOfClients.text())}")
dsGenSpec.append(f"variables:{str(configView.edtVarsInOpt.text())}")
dsGenSpecStr = ",".join(dsGenSpec)
cmdline.append("--dataset-generation-spec")
cmdline.append(dsGenSpecStr)
cmdline.append("--loss")
cmdline.append("mse")
cmdline.append("--model")
cmdline.append("linear")
cmdline.append("--metric")
cmdline.append("loss")
else:
cmdline.append("--loss")
cmdline.append(configView.cbxLossFunctionForGlobalModel.currentText())
cmdline.append("--model")
cmdline.append(configView.cbxGlobalModel.currentText())
if configView.cbxPretrained.checkState() == Qt.Checked:
cmdline.append("--use-pretrained")
if configView.cbxTrainLastLayerOnly.checkState() == Qt.Checked:
cmdline.append("--train-last-layer")
if configView.cbxTurnOffBatchNormAndDropOut.checkState() == Qt.Checked:
cmdline.append("--turn-off-batch-normalization-and-dropout")
cmdline.append("--metric")
cmdline.append(configView.cbxValidationOptMetric.currentText())
cmdline.append("--global-regulizer")
cmdline.append(configView.cbxGlobalLossRegulizer.currentText())
cmdline.append("--global-regulizer-alpha")
cmdline.append(configView.edtGlobalRegulizerCoefficent.text())
cmdline.append("--checkpoint-dir")
cmdline.append(configView.edtCheckpointDir.text())
if configView.cbxDoNotSaveEvalCheckpoints.checkState() == Qt.Checked:
cmdline.append("--do-not-save-eval-checkpoints")
cmdline.append("--data-path")
cmdline.append(configView.edtDataPath.text())
cmdline.append("--compute-type")
cmdline.append(configView.cbxParamsType.currentText())
cmdline.append("--gpu")
device_index = configView.cbxComputeDevice.currentIndex()
if device_index == 0:
# Single CPU
device_index = -1
cmdline.append(str(device_index))
elif device_index == configView.cbxComputeDevice.count() - 1:
# Complicated selection - CPUs, GPUs, or even external compute resources
devicesList = []
# Process local devices
gpus_properties = gpu_utils.get_available_gpus()
for i in range(len(gpus_properties)):
if configView.loComputeDevices.itemAt(i + 1).widget().checkState() == Qt.Checked:
devicesList.append(i)
if configView.loComputeDevices.itemAt(0).widget().checkState() == Qt.Checked:
devicesList.append(-1)
if len(devicesList) == 0:
dlg = QMessageBox()
dlg.setWindowTitle("Error")
dlg.setText(f"You have to select at least one computation device in Configuration/System Aspects")
dlg.setStandardButtons(QMessageBox.Ok)
dlg.setIcon(QMessageBox.Critical)
button = dlg.exec_()
return
devString = ",".join([str(d) for d in devicesList])
cmdline.append(devString)
# Cmdline option for external resources
if configView.loComputeDevices.itemAt(configView.loComputeDevices.count() - 1).widget().checkState() == Qt.Checked:
cmdline.append("--external-devices")
usedMachines = []
for m in machineDescriptions:
for md in m['used_devices']:
usedMachines.append(m["ip"] + ":" + str(m["port"]) + ":" + md)
machineString = ",".join([str(m) for m in usedMachines])
cmdline.append(machineString)
else:
# Single GPU
device_index = device_index - 1
cmdline.append(str(device_index))
if configView.cbxLogGPUusage.checkState() == Qt.Checked:
cmdline.append("--log-gpu-usage")
cmdline.append("--num-workers-train")
cmdline.append(configView.edtNumWorkersForTrainDataLoad.text())
cmdline.append("--num-workers-test")
cmdline.append(configView.edtNumWorkersForValDataLoad.text())
if configView.cbxRunDeterministically.checkState() == Qt.Checked:
cmdline.append("--deterministic")
cmdline.append("--manual-init-seed")
cmdline.append(configView.edtRandomInitSeed.text())
cmdline.append("--manual-runtime-seed")
cmdline.append(configView.edtRandomRunSeed.text())
cmdline.append("--group-name")
cmdline.append(configView.edtGroupName.text())
cmdline.append("--comment")
cmdline.append(configView.edtCommentForExperiment.text())
cmdline.append("--hostname")
cmdline.append(socket.gethostname())