-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime_adaptative_models.py
1324 lines (1092 loc) · 48.8 KB
/
runtime_adaptative_models.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/env python3
"""
Run-Time Training and Prediction with Online Models
Author : Juan Encinas <[email protected]>
Date : December 2023
Description : This script:
- Processes power and performance traces received from an
independent c-code process via disk-backed files or ram-backed
memory-mapped regions (up to the user).
- Trains power (pl and ps) and performance online models on
demand from commands send via a socket from the independent
c-code process.
- Predicts with the trained models for the features receive from
the independent c-code process via another socket.
- Models are synchronized, training and testing simultaneously
All is done at run-time with concurrent threads for training the
models and predicting with them.
"""
import sys
import os
import argparse
import time
import struct
import threading
from datetime import datetime, timezone
# from multiprocessing import Process
import ctypes as ct
import pandas as pd
import river
import pickle
from incremental_learning import online_data_processing as odp
from incremental_learning import inter_process_communication as ipc
from incremental_learning import online_models as om
from incremental_learning import ping_pong_buffers as ppb
from incremental_learning import execution_modes_buffers as emb
class FeatureswCPUUsage(ct.Structure):
""" Features with CPU Usage - This class defines a C-like struct """
_fields_ = [
("user", ct.c_float),
("kernel", ct.c_float),
("idle", ct.c_float),
("Main", ct.c_uint8),
("aes", ct.c_uint8),
("bulk", ct.c_uint8),
("crs", ct.c_uint8),
("kmp", ct.c_uint8),
("knn", ct.c_uint8),
("merge", ct.c_uint8),
("nw", ct.c_uint8),
("queue", ct.c_uint8),
("stencil2d", ct.c_uint8),
("stencil3d", ct.c_uint8),
("strided", ct.c_uint8)
]
def get_dict(self):
"""Convert to dictionary"""
return dict((f, getattr(self, f)) for f, _ in self._fields_)
class FeatureswoCPUUsage(ct.Structure):
""" Features without CPU Usage- This class defines a C-like struct """
_fields_ = [
("Main", ct.c_uint8),
("aes", ct.c_uint8),
("bulk", ct.c_uint8),
("crs", ct.c_uint8),
("kmp", ct.c_uint8),
("knn", ct.c_uint8),
("merge", ct.c_uint8),
("nw", ct.c_uint8),
("queue", ct.c_uint8),
("stencil2d", ct.c_uint8),
("stencil3d", ct.c_uint8),
("strided", ct.c_uint8)
]
def get_dict(self):
"""Convert to dictionary"""
return dict((f, getattr(self, f)) for f, _ in self._fields_)
class PredictionDual(ct.Structure):
""" Prediction (Dual) - This class defines a C-like struct """
_fields_ = [
("top_power", ct.c_float),
("bottom_power", ct.c_float),
("time", ct.c_float)
]
class PredictionMono(ct.Structure):
""" Prediction (Mono) - This class defines a C-like struct """
_fields_ = [
("power", ct.c_float),
("time", ct.c_float)
]
class MetricsDual(ct.Structure):
""" Errro Metrics (Dual) - This class defines a C-like struct """
_fields_ = [
("ps_power_error", ct.c_float),
("pl_power_error", ct.c_float),
("time_error", ct.c_float)
]
class MetricsMono(ct.Structure):
""" Errro Metrics (Mono) - This class defines a C-like struct """
_fields_ = [
("power_error", ct.c_float),
("time_error", ct.c_float)
]
def training_thread_file_func(online_models, tcp_socket, board, cpu_usage):
"""Train models at run-time. (online data stored in disk-backed files)"""
# Wait for the client to connect via socket
tcp_socket.wait_connection()
print(f"[{'Training Thread (f)':^19}] TCP socket connected.")
# Set the path to the online.bin and traces files
output_data_path = "../outputs"
traces_data_path = "../traces"
# Useful local variables
t_interv = 0
notification = 1
num_measurements = 0
i = 0
is_training = True # True means training, False means testing
# Keep processsing files undefinatelly
# (test with finite number of iterations)
while notification != 0:
notification = tcp_socket.recv_data()
print(f"notification: {notification}")
print(f"[{'Training Thread (f)':^19}] {datetime.now(timezone.utc)}")
# Unpack the received binary data into an integer value
received_data = struct.unpack("i", notification)[0]
# Check is the message is for training or testing (MSB)
# 1 when training; 0 when testing
is_training = True if received_data & (1 << 31) != 0 else False
# Get the number of measurements (31 least significant bits)
num_measurements = received_data & ~(1 << 31)
if is_training:
print("We are Training!")
else:
print("We are Testing!")
# Generate tmp metrics
if board["power"]["rails"] == "dual":
test_metrics = [
river.metrics.RMSE(),
river.metrics.RMSE(),
river.metrics.RMSE()
]
elif board["power"]["rails"] == "mono":
test_metrics = [
river.metrics.RMSE(),
river.metrics.RMSE()
]
print(f"num_measurements: {num_measurements}")
if num_measurements == 0:
break
# Get number of measures to train with
# num_measurements = int(notification)
if i == 0:
# Time measurement logic
t_start = time.time()
for _ in range(num_measurements):
t_inter0 = time.time()
i += 1
# Generate the next online_info files path
curr_output_path = os.path.join(output_data_path, f"online_{i-1}.bin")
curr_power_path = os.path.join(traces_data_path, f"CON_{i-1}.BIN")
curr_traces_path = os.path.join(traces_data_path, f"SIG_{i-1}.BIN")
# Generate observations for this particular online_info.bin file
generated_obs = \
odp.generate_observations_from_online_data(
curr_output_path,
curr_power_path,
curr_traces_path,
board,
cpu_usage
)
# Check if this monitoring windows contains observations
# In case there are no observations just move to next window
if len(generated_obs) < 1:
# print("[{:^19}] No useful obs".format("Training Thread (f)"))
t_inter1 = time.time()
t_interv += t_inter1-t_inter0
continue
# Create dataframe just for this online_data file
dataframe = odp.generate_dataframe_from_observations(
generated_obs,
board,
cpu_usage
)
# DEBUG: Checking with observations are generated
# print(curr_output_path)
# print(traces_path)
# print(curr_traces_file)
# print(dataframe)
train_number_raw_observations = len(dataframe)
# remove nan (happens due to not using mutex for cpu_usage)
dataframe = dataframe.dropna()
train_number_observations = len(dataframe)
print(f"Train NaN rows: {train_number_raw_observations - train_number_observations}")
# Different behaviour depending if is training or testing
if is_training:
# Learn batch with the online models
online_models.train_s(dataframe)
else:
# Test batch with the online models
test_metrics = online_models.test_s(dataframe, test_metrics)
if board["power"]["rails"] == "dual":
# Different behaviour depending if is training or testing
if is_training:
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
online_models.get_metrics()
else:
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
test_metrics
# Generate c-like structure containing the model error metrics
metrics_to_send = MetricsDual(
tmp_top_metric,
tmp_bottom_metric,
tmp_time_metric
)
print(
f"[{'Training Thread (f)':^19}] Metrics: {tmp_top_metric} (top) | "
f"{tmp_bottom_metric} (bottom) | {tmp_time_metric} (time)"
)
elif board["power"]["rails"] == "mono":
# Different behaviour depending if is training or testing
if is_training:
tmp_power_metric, tmp_time_metric = \
online_models.get_metrics()
else:
tmp_power_metric, tmp_time_metric = test_metrics
# Generate c-like structure containing the model error metrics
metrics_to_send = MetricsMono(
tmp_power_metric,
tmp_time_metric
)
print(
f"[{'Training Thread (f)':^19}] Metrics: {tmp_power_metric} (power) | "
f"{tmp_time_metric} (time)"
)
t_inter1 = time.time()
t_interv += t_inter1-t_inter0
# Send the metrics obtained via socket
tcp_socket.send_data(metrics_to_send)
# Time measurement logic
t_end = time.time()
# Close the socket
tcp_socket.close_connection()
# Print useful information
if i > 0: # Take care of division by zero
print(f"[{'Training Thread (f)':^19}] Interval Elapsed Time (s):", t_interv, (t_interv)/i)
print(
f"[{'Training Thread (f)':^19}] Total Elapsed Time (s):",
t_end-t_start,
(t_end-t_start)/i
)
print(f"[{'Training Thread (f)':^19}] Number of trainings: {i}")
else:
print(f"[{'Training Thread (f)':^19}] No processing was made")
if board["power"]["rails"] == "dual":
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
online_models.get_metrics()
print(
f"[{'Training Thread (f)':^19}] Training Metrics: {tmp_top_metric} (top) | "
f"{tmp_bottom_metric} (bottom) | {tmp_time_metric} (time)"
)
elif board["power"]["rails"] == "mono":
tmp_power_metric, tmp_time_metric = online_models.get_metrics()
print(
f"[{'Training Thread (f)':^19}] Training Metrics: {tmp_power_metric} (top) | "
f"{tmp_time_metric} (time)"
)
print(f"[{'Training Thread (f)':^19}] Thread terminated.")
def training_thread_ram_func(online_models, tcp_socket, board, cpu_usage):
"""Train models at run-time. (or test is the c code wants to check metrics)
(online_data stored in ram-backed mmap'ed files)
"""
# Wait for the client to connect via socket
tcp_socket.wait_connection()
print(f"[{'Training Thread (r)':^19}] TCP socket connected.")
# Get number of training iterations
notification = tcp_socket.recv_data()
print(f"notification: {notification}")
print(f"[{'Training Thread (r)':^19}]", datetime.now(timezone.utc))
# Unpack the received binary data into an integer value
number_iterations = struct.unpack("i", notification)[0]
print(f"num_measurements: {number_iterations}")
# Ping-Pong/Execution-modes buffers configuration variables
# (maybe makes sense to allow some kind of configurability to the user)
SHM_ONLINE_FILE = "online"
SHM_POWER_FILE = "power"
SHM_TRACES_FILE = "traces"
SHM_ONLINE_REGION_SIZE = 2*1024 # Bytes
SHM_POWER_REGION_SIZE = 525*1024 # Bytes
SHM_TRACES_REGION_SIZE = 20*1024 # Bytes
# Create the ping-pong buffers
if number_iterations == 1:
buffers = ppb.PingPongBuffers(SHM_ONLINE_FILE,
SHM_ONLINE_REGION_SIZE,
SHM_POWER_FILE,
SHM_POWER_REGION_SIZE,
SHM_TRACES_FILE,
SHM_TRACES_REGION_SIZE,
create=True,
unregister=True)
elif number_iterations > 1:
buffers = emb.ExecutionModesBuffers(SHM_ONLINE_FILE,
SHM_ONLINE_REGION_SIZE,
SHM_POWER_FILE,
SHM_POWER_REGION_SIZE,
SHM_TRACES_FILE,
SHM_TRACES_REGION_SIZE,
number_iterations,
create=True,
unregister=True)
else:
raise Exception("Number of iterations cannot be less than 1.")
# Send ack indicating ack of the number_iterations
tcp_socket.send_data(b'1')
print("Sent number_iterations ack to the c program")
# Useful local variables
t_interv = 0
notification = 1
i = 0
num_useless_obs = 0
# Debug
t_copy_buf = 0
t_gen_obs = 0
t_toggle = 0
t_gen_dataframe = 0
t_print_df = 0
t_train = 0
t_metrics = 0
# Keep processsing files undefinatelly
# (test with finite number of iterations)
# Local Online Models Manager variables
iteration = 0
next_operation_mode = "train"
wait_obs = 0
# TODO: Remove. Used to store workload phaces
workloads_buffer_index = [[0,]]
workloads_obs_index = [[0,]]
# TODO: Test. Variable to store info for later generate temporal axis
# Formato: lista de listas. Cada sub lista contendrá la info de una etapa de train/test
# (idle no se recoje pero son el resto) necesaria para regenerar la gráfica
# [num_measurements, start_time_train/test, start_observation_index, end_time_train/test, end_observation_index]
# Como tenemos una lista con el error para cada observación y el indice de estas con la sublista anterior
# podemos identificar en qué momento se genera cada obs (distribuyendolas uniformement en la etapa medida+train/test)
# * Es cierto qeu el número de obs en idle puede no ser el real pues se hace una aproximación en el setup, pero como
# tenemos el tiempo justo del final de la etapa train/test anterior y el tiempo inicial de la siguiente sabemos ubicarlo
temporal_data = []
# TODO: Remove. Used to check ratio of observations per window
total_observations = 0
total_windows = 0
while notification != 0:
notification = tcp_socket.recv_data()
print(f"notification: {notification}")
print(f"[{'Training Thread (r)':^19}]", datetime.now(timezone.utc))
# Unpack the received binary data into an integer value
received_data = struct.unpack("i", notification)[0]
# Get the number of measurements
num_measurements = received_data
print(f"num_measurements: {num_measurements}")
if num_measurements < 0:
# Setup has indicated next obs come from new workload
print(f"Next Workload at buffer: {i} (iteration: {iteration})")
# Mark last workload buffer and obs index and append new list to mark next workload
workloads_buffer_index[-1].append(i-1)
workloads_buffer_index.append([i-1])
workloads_obs_index[-1].append(iteration-1)
workloads_obs_index.append([iteration-1])
continue
elif num_measurements == 0:
# Setup indicates end of execution
# Mark last workload end index
workloads_buffer_index[-1].append(i)
workloads_obs_index[-1].append(iteration)
break
if i == 0:
# Time measurement logic
t_start = time.time()
# Train/test from each measurement
# TODO:Test para generar eje temporal
temporal_data.append([])
temporal_data[-1].append(num_measurements)
temporal_data[-1].append(time.time())
temporal_data[-1].append(iteration)
for iter in range(num_measurements):
t_inter0 = time.time()
i += 1
# Get last int (it contains the size of the actual data)
online_size = int.from_bytes(buffers.online[-4:], sys.byteorder)
power_size = int.from_bytes(buffers.power[-4:], sys.byteorder)
traces_size = int.from_bytes(buffers.traces[-4:], sys.byteorder)
t_inter1 = time.time()
# Generate observations for this particular online_info.bin file
generated_obs = \
odp.generate_observations_from_online_data(
buffers.online[:online_size],
buffers.power[:power_size],
buffers.traces[:traces_size],
board,
cpu_usage)
t_inter2 = time.time()
# Toggle current buffers
buffers.toggle()
t_inter3 = time.time()
# Check if this monitoring windows contains observations
# In case there are no observations just move to next window
if len(generated_obs) < 1:
# print(f"[{'Training Thread (r)':^19}] No useful obs")
t_inter5 = time.time()
t_interv += t_inter5-t_inter0
num_useless_obs += 1
# Debug
t_copy_buf += t_inter1 - t_inter0
t_gen_obs += t_inter2 - t_inter1
t_toggle += t_inter3 - t_inter2
continue
# Create dataframe just for this online_data file
dataframe = odp.generate_dataframe_from_observations(
generated_obs,
board,
cpu_usage)
t_inter4 = time.time()
# train_number_raw_observations = len(dataframe)
# remove nan (happens due to not using mutex for cpu_usage)
dataframe = dataframe.dropna()
# TODO: Remove. Used to check ratio of observations per window
total_windows += 1
total_observations += len(dataframe)
# print(f"Train NaN rows: {train_number_raw_observations - train_number_observations}")
# Skip useless observations
if len(dataframe.index) < 1:
num_useless_obs += 1
continue
# Let the models manager decide whether train or test
# TODO: Quizá es más eficiente no entrenar con cada iteracion, sino concatenar los
# dataframes generados y entrenar una vez hayan llegado todos
iteration, next_operation_mode, wait_obs = online_models.update_models(
dataframe,
iteration
)
t_inter5 = time.time()
t_interv += t_inter5-t_inter0
# Debug
t_copy_buf += t_inter1 - t_inter0
t_gen_obs += t_inter2 - t_inter1
t_toggle += t_inter3 - t_inter2
t_gen_dataframe += t_inter4 - t_inter3
t_train += t_inter5 - t_inter4
# TODO: esto podría cambiar si en lugar de entrenar en cada iteración entrenamos al
# final, pero es cierto que al hacerlo cada cada iteración ahorraríamos tiempo
# de procesado de las iteraciones innecesarias
if next_operation_mode == "idle":
print(f"Reached Idle before processing all measurements: ({iter}/{num_measurements}")
break
# TODO: variables para añadir eje temporal
temporal_data[-1].append(time.time())
if next_operation_mode == "idle":
# In case we are in idle in next operation mode we have to substract the wait_obs since
# inside the update_models the training monitor increases the iteration value by
# wait_obs before it happens.
# So to ensure the postprocessing of the temporal data is properly applied we need to
# substract that
temporal_data[-1].append(iteration - wait_obs - 1)
else:
temporal_data[-1].append(iteration - 1) # Since update_models increases the iteration
# TODO: Lo de entrenar of test se quita porque ahora lo gestion el Training Monitor
# Send the metrics obtained via socket
# tcp_socket.send_data(metrics_to_send)
ack_value = wait_obs if next_operation_mode == "idle" else 0
ack_bytes = struct.pack("i", ack_value)
tcp_socket.send_data(ack_bytes)
print(f"[Pos-train]: iter: {iteration} | mode: {next_operation_mode} | wait_obs: {wait_obs}")
# Print useful information
if i > 0: # Take care of division by zero
print(f"[{'Training Thread (r)':^19}] Number of trainings: {i}")
print(
f"[{'Training Thread (r)':^19}] Interval Elapsed Time (s): "
f"(total) {t_interv:016.9f} | (ratio) {t_interv / i:012.9f}"
)
# Debug
print(
f"[{'Training Thread (r)':^19}] t_copy_buf (s) : "
f"(total) {t_copy_buf:016.9f} | (ratio) {t_copy_buf / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_gen_obs (s) : "
f"(total) {t_gen_obs:016.9f} | (ratio) {t_gen_obs / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_toggle (s) : "
f"(total) {t_toggle:016.9f} | (ratio) {t_toggle / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_gen_dataframe (s) : "
f"(total) {t_gen_dataframe:016.9f} | "
f"(ratio) {t_gen_dataframe / (i - num_useless_obs):012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_train (s) : "
f"(total) {t_train:016.9f} | (ratio) {t_train / (i - num_useless_obs):012.9f}"
)
# TODO: Send back to the setup what to do
print(
f"{'Training Thread (r)':^19}] Iteration: {iteration} | Mode: {next_operation_mode} | "
f"Wait Obs: {wait_obs}"
)
# Time measurement logic
t_end = time.time()
# Close the socket
tcp_socket.close_connection()
# Print useful information
if i > 0: # Take care of division by zero
print(f"[{'Training Thread (r)':^19}] Number of trainings: {i}")
print(
f"[{'Training Thread (r)':^19}] Total Elapsed Time (s): "
f"(total) {t_end - t_start:016.9f} | (ratio) {(t_end - t_start) / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] Interval Elapsed Time (s): "
f"(total) {t_interv:016.9f} | (ratio) {t_interv / i:012.9f}"
)
# Debug
print(
f"[{'Training Thread (r)':^19}] t_copy_buf (s) : "
f"(total) {t_copy_buf:016.9f} | (ratio) {t_copy_buf / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_gen_obs (s) : "
f"(total) {t_gen_obs:016.9f} | (ratio) {t_gen_obs / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_toggle (s) : "
f"(total) {t_toggle:016.9f} | (ratio) {t_toggle / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_gen_dataframe (s) : "
f"(total) {t_gen_dataframe:016.9f} | "
f"(ratio) {t_gen_dataframe / (i - num_useless_obs):012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] t_train (s) : "
f"(total) {t_train:016.9f} | (ratio) {t_train / (i - num_useless_obs):012.9f}"
)
print(f"Total Windows: {total_windows} | Total Observations: {total_observations} | Ratio: {total_observations/total_windows}")
# Print workload indexes
print("Workloads buffer indexes", workloads_buffer_index)
print("Workloads obs indexes", workloads_obs_index)
# Print temporal data
print("Temporal Data:", temporal_data)
else:
print(f"[{'Training Thread (r)':^19}] No processing was made")
# TODO: Remove
# TODO: Está triplicado, si nos cargamos 2 replicas?
# When there are no more obs the system is either in train or test mode.
# We need fill the last test/train_region list with the actual iteration
for model in online_models._models:
if model._training_monitor.operation_mode == "train":
model._training_monitor.train_train_regions[-1].append(iteration-1)
elif model._training_monitor.operation_mode == "test":
model._training_monitor.test_test_regions[-1].append(iteration-1)
###############
# Guardar temporal data y modelos en fichero (online_models y temporal_data)
# Create directory if it does not exit
model_error_figures_dir = "./model_error_figures"
if not os.path.exists(model_error_figures_dir):
os.makedirs(model_error_figures_dir)
# Generar gráficas
# online_models.print_training_monitor_info(model_error_figures_dir)
# Ask the user for the figure name
data_save_file_name = input("Give me name to save models object and temporal data "
f"(path:{model_error_figures_dir}/<name>.pkl): ")
# Save the models training monitor
with open(f"{model_error_figures_dir}/{data_save_file_name}_training_monitor.pkl", 'wb') as file:
tmp_var = [model._training_monitor for model in online_models._models]
pickle.dump(tmp_var, file)
# Save the temporal data
with open(f"{model_error_figures_dir}/{data_save_file_name}_temporal_data.pkl", 'wb') as file:
pickle.dump(temporal_data, file)
if board["power"]["rails"] == "dual":
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
online_models.get_metrics()
print(
f"[{'Training Thread (r)':^19}] Training Metrics: {tmp_top_metric} (top) | "
f"{tmp_bottom_metric} (bottom) | {tmp_time_metric} (time)"
)
elif board["power"]["rails"] == "mono":
tmp_power_metric, tmp_time_metric = online_models.get_metrics()
print(
f"[{'Training Thread (r)':^19}] Training Metrics: {tmp_power_metric} (power) | "
f"{tmp_time_metric} (time)"
)
# Close shared memories (unlink if desired)
buffers.clean(unlink=True)
print(f"[{'Training Thread (r)':^19}] Thread terminated.")
def training_thread_ram_func_old(online_models, tcp_socket, board, cpu_usage):
"""Train models at run-time. (or test is the c code wants to check metrics)
(online_data stored in ram-backed mmap'ed files)
"""
# Wait for the client to connect via socket
tcp_socket.wait_connection()
print(f"[{'Training Thread (r)':^19}] TCP socket connected.")
# Get number of training iterations
notification = tcp_socket.recv_data()
print(f"notification: {notification}")
print(f"[{'Training Thread (r)':^19}]", datetime.now(timezone.utc))
# Unpack the received binary data into an integer value
number_iterations = struct.unpack("i", notification)[0]
print(f"num_measurements: {number_iterations}")
# Send ack indicating ack of the number_iterations
tcp_socket.send_data(b'1')
print("Sent number_iterations ack to the c program")
# Ping-Pong/Execution-modes buffers configuration variables
# (maybe makes sense to allow some kind of configurability to the user)
SHM_ONLINE_FILE = "online"
SHM_POWER_FILE = "power"
SHM_TRACES_FILE = "traces"
SHM_ONLINE_REGION_SIZE = 2*1024 # Bytes
SHM_POWER_REGION_SIZE = 525*1024 # Bytes
SHM_TRACES_REGION_SIZE = 20*1024 # Bytes
# Create the ping-pong buffers
if number_iterations == 1:
buffers = ppb.PingPongBuffers(SHM_ONLINE_FILE,
SHM_ONLINE_REGION_SIZE,
SHM_POWER_FILE,
SHM_POWER_REGION_SIZE,
SHM_TRACES_FILE,
SHM_TRACES_REGION_SIZE,
create=True,
unregister=True)
elif number_iterations > 1:
buffers = emb.ExecutionModesBuffers(SHM_ONLINE_FILE,
SHM_ONLINE_REGION_SIZE,
SHM_POWER_FILE,
SHM_POWER_REGION_SIZE,
SHM_TRACES_FILE,
SHM_TRACES_REGION_SIZE,
number_iterations,
create=True,
unregister=True)
else:
raise Exception("Number of iterations cannot be less than 1.")
# Useful local variables
t_interv = 0
notification = 1
i = 0
num_useless_obs = 0
is_training = True # True means training, False means testing
# Debug
t_copy_buf = 0
t_gen_obs = 0
t_toggle = 0
t_gen_dataframe = 0
t_print_df = 0
t_train = 0
t_metrics = 0
# Keep processsing files undefinatelly
# (test with finite number of iterations)
while notification != 0:
notification = tcp_socket.recv_data()
print(f"notification: {notification}")
print(f"[{'Training Thread (r)':^19}]", datetime.now(timezone.utc))
# Unpack the received binary data into an integer value
received_data = struct.unpack("i", notification)[0]
# Check is the message is for training or testing (MSB)
# 1 when training; 0 when testing
is_training = True if received_data & (1 << 31) != 0 else False
# Get the number of measurements (31 least significant bits)
num_measurements = received_data & ~(1 << 31)
if is_training:
print("We are Training!")
else:
print("We are Testing!")
# Generate tmp metrics
if board["power"]["rails"] == "dual":
test_metrics = [
river.metrics.RMSE(),
river.metrics.RMSE(),
river.metrics.RMSE(),
]
elif board["power"]["rails"] == "mono":
test_metrics = [
river.metrics.RMSE(),
river.metrics.RMSE(),
river.metrics.RMSE(),
]
print(f"num_measurements: {num_measurements}")
if num_measurements == 0:
break
# Get number of measurements to train with
# num_measurements = int(notification)
if i == 0:
# Time measurement logic
t_start = time.time()
for _ in range(num_measurements):
t_inter0 = time.time()
i += 1
# Get last int (it contains the size of the actual data)
online_size = int.from_bytes(buffers.online[-4:], sys.byteorder)
power_size = int.from_bytes(buffers.power[-4:], sys.byteorder)
traces_size = int.from_bytes(buffers.traces[-4:], sys.byteorder)
# print("Write to files")
# with open("test_ram/CON_{}.BIN".format(iter), "wb") as b_file:
# # Write bytes to file
# binary_file.write(buffers.power[:power_size])
# with open("test_ram/SIG_{}.BIN".format(iter), "wb") as b_file:
# # Write bytes to file
# binary_file.write(buffers.traces[:traces_size])
# with open("test_ram/online_{}.bin".format(iter), "wb") as b_file:
# # Write bytes to file
# binary_file.write(buffers.online[:online_size])
# print(online_size)
# print(power_size)
# print(traces_size)
t_inter1 = time.time()
# Generate observations for this particular online_info.bin file
generated_obs = \
odp.generate_observations_from_online_data(
buffers.online[:online_size],
buffers.power[:power_size],
buffers.traces[:traces_size],
board,
cpu_usage)
t_inter2 = time.time()
# print(generated_obs)
# Toggle current buffers
buffers.toggle()
t_inter3 = time.time()
# print(generated_obs)
# Check if this monitoring windows contains observations
# In case there are no observations just move to next window
if len(generated_obs) < 1:
print(f"[{'Training Thread (r)':^19}] No useful obs")
t_inter7 = time.time()
t_interv += t_inter7-t_inter0
num_useless_obs += 1
# Debug
t_copy_buf += t_inter1 - t_inter0
t_gen_obs += t_inter2 - t_inter1
t_toggle += t_inter3 - t_inter2
continue
# Create dataframe just for this online_data file
dataframe = odp.generate_dataframe_from_observations(
generated_obs,
board,
cpu_usage)
t_inter4 = time.time()
# DEBUG: Checking with observations are generated
# print(curr_output_path)
# print(traces_path)
# print(curr_traces_file)
# print(dataframe)
t_inter5 = time.time()
train_number_raw_observations = len(dataframe)
# remove nan (happens due to not using mutex for cpu_usage)
dataframe = dataframe.dropna()
train_number_observations = len(dataframe)
print(f"Train NaN rows: {train_number_raw_observations - train_number_observations}")
if len(dataframe.index) < 1:
num_useless_obs += 1
continue
# Different behaviour depending if is training or testing
if is_training:
# Learn batch with the online models
online_models.train_s(dataframe, lock)
else:
# Test batch with the online models
test_metrics = online_models.test_s(dataframe, lock, test_metrics)
t_inter6 = time.time()
if board["power"]["rails"] == "dual":
# Different behaviour depending if is training or testing
if is_training:
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
online_models.get_metrics()
else:
tmp_top_metric, tmp_bottom_metric, tmp_time_metric = \
test_metrics
# Generate c-like structure containing the model error metrics
metrics_to_send = MetricsDual(
tmp_top_metric.get(),
tmp_bottom_metric.get(),
tmp_time_metric.get()
)
print(
f"[{'Training Thread (r)':^19}] Metrics: {tmp_top_metric} (top) | "
f"{tmp_bottom_metric} (bottom) | {tmp_time_metric} (time)"
)
elif board["power"]["rails"] == "mono":
# Different behaviour depending if is training or testing
if is_training:
tmp_power_metric, tmp_time_metric = \
online_models.get_metrics()
else:
tmp_power_metric, tmp_time_metric = test_metrics
# Generate c-like structure containing the model error metrics
metrics_to_send = MetricsMono(
tmp_power_metric.get(),
tmp_time_metric.get()
)
print(
f"[{'Training Thread (r)':^19}] Metrics: {tmp_power_metric} (power) | "
f"{tmp_time_metric} (time)"
)
t_inter7 = time.time()
t_interv += t_inter7-t_inter0
# Debug
t_copy_buf += t_inter1 - t_inter0
t_gen_obs += t_inter2 - t_inter1
t_toggle += t_inter3 - t_inter2
t_gen_dataframe += t_inter4 - t_inter3
t_print_df += t_inter5 - t_inter4
t_train += t_inter6 - t_inter5
t_metrics += t_inter7 - t_inter6
# Send the metrics obtained via socket
tcp_socket.send_data(metrics_to_send)
# Time measurement logic
t_end = time.time()
# Close the socket
tcp_socket.close_connection()
# Print useful information
if i > 0: # Take care of division by zero
print(f"[{'Training Thread (r)':^19}] Number of trainings: {i}")
print(
f"[{'Training Thread (r)':^19}] Total Elapsed Time (s): "
f"(total) {t_end - t_start:016.9f} | (ratio) {(t_end - t_start) / i:012.9f}"
)
print(
f"[{'Training Thread (r)':^19}] Interval Elapsed Time (s): "
f"(total) {t_interv:016.9f} | (ratio) {t_interv / i:012.9f}"