-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
3203 lines (2720 loc) · 154 KB
/
runner.py
File metadata and controls
3203 lines (2720 loc) · 154 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
#
# Copyright 2026 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Main hardware microbenchmarking runner.
This script provides the main entry point for running hardware microbenchmarks
and uses the modular components for parsing, statistics, plotting, and benchmarking.
"""
import os
import subprocess
import math
import numpy as np
import pandas as pd
import datetime
import argparse
import logging
import sys
import shlex
from pathlib import Path
from hw_characterization.scripts.parser import log_info, _require_env, consecutive_bytes_to_elemsize, format_bytes
from hw_characterization.scripts.numa_utils import expand_cpu_ranges
from hw_characterization.scripts.regression_analysis import least_squares_fit
from hw_characterization.scripts.plotters import plot_all_regression_stats, plot_all_regression_stats_gbytes, plot_PaHiS_submodel
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Global configuration
MAX_BUFF_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB
# Constants for unit conversions
BYTES_TO_GB = 1024**3 # Convert bytes to GB
BYTES_TO_GB_PER_SEC = 1e9 # Convert bytes/second to GB/s
# Map of microbenchmark kernels to their properties:
KERNEL_NAMES = ["chase", "sync", "copy", "daxpy", "dot", "triad"]
KERNEL_NAME_TO_IDX = {name: idx for idx, name in enumerate(KERNEL_NAMES)}
# - Number of IO vectors
KERNEL_VECNUM = [1, 0, 2, 2, 2, 3]
# - Number of reads
KERNEL_READS = [1, 1, 1, 1, 2, 2]
# - Number of writes
KERNEL_WRITES = [1, 1, 1, 1, 0, 1]
DEFAULT_BW_KERNELS = "copy,daxpy,triad" # default selection for --bw-kernels
def aggregate_values(values, method='mean'):
"""Aggregate an array/list of values using the specified method."""
if method == 'mean':
return float(np.mean(values))
elif method == 'min':
return float(np.min(values))
elif method == 'max':
return float(np.max(values))
else:
raise ValueError(f"Unknown aggregation method: {method}")
# Global variables for logging and file tracking
logger = None
file_tracker = set()
step_summaries = []
CPU_ALLOWED_FROM_TOPO = None # Optional CPU allow-list from topology file
def setup_logging(verbose=False):
"""Setup dual logging: detailed to runner.log, summary to stdout"""
global logger
# Get build directory for log file
build_dir = os.environ.get("HW_BUILD_DIR", "./build")
log_file = os.path.join(build_dir, "runner.log")
# Create logger
logger = logging.getLogger('runner')
logger.setLevel(logging.DEBUG)
# Clear any existing handlers
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# File handler for detailed logging
file_handler = logging.FileHandler(log_file, mode='w')
file_handler.setLevel(logging.DEBUG)
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
# Console handler for summary output (or debug if verbose)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG if verbose else logging.INFO)
console_formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
return log_file
def log_summary(step_name, status, details=None, files_generated=None):
"""Log a summary step to both file and console"""
global step_summaries
summary = {
'step': step_name,
'status': status,
'timestamp': datetime.datetime.now().isoformat(),
'details': details or {},
'files': files_generated or []
}
step_summaries.append(summary)
# Log to file (detailed)
logger.debug(f"STEP: {step_name}")
logger.debug(f"STATUS: {status}")
if details:
for key, value in details.items():
logger.debug(f" {key}: {value}")
if files_generated:
logger.debug(f"FILES GENERATED: {len(files_generated)}")
for file_path in files_generated:
logger.debug(f" - {file_path}")
# Log to console (summary)
status_symbol = "✓" if status == "SUCCESS" else "✗" if status == "ERROR" else "⚠"
logger.info(f"{status_symbol} {step_name}")
if details and len(details) <= 3: # Only show key details in console
for key, value in details.items():
logger.info(f" {key}: {value}")
if files_generated and len(files_generated) <= 5: # Only show first few files
logger.info(f" Files: {len(files_generated)} generated")
for file_path in files_generated[:3]:
logger.info(f" - {file_path}")
if len(files_generated) > 3:
logger.info(f" ... and {len(files_generated) - 3} more")
def track_file(file_path):
"""Track a generated file"""
global file_tracker
if file_path:
file_tracker.add(str(file_path))
def get_generated_files_summary():
"""Get summary of all generated files organized by type"""
if not file_tracker:
return {}
files_by_type = {}
for file_path in file_tracker:
path = Path(file_path)
if path.exists():
if path.suffix == '.csv':
files_by_type.setdefault('CSV Data', []).append(file_path)
elif path.suffix == '.png':
files_by_type.setdefault('Plots', []).append(file_path)
elif path.suffix == '.hpp':
files_by_type.setdefault('C++ Headers', []).append(file_path)
elif path.suffix == '.log':
files_by_type.setdefault('Logs', []).append(file_path)
else:
files_by_type.setdefault('Other', []).append(file_path)
return files_by_type
# Directory configuration - hardcoded paths + configurable ones
TOPOLOGY_DIR = "hw_characterization/topologies" # Hardcoded
RESULTS_DIR = "hw_characterization/results" # Hardcoded
CPP_MODEL_DIR = f"hw_characterization/results/{os.environ['HW_MODEL']}/output_headers" # Hardcoded with HW_MODEL
BUILD_DIR = os.environ.get("HW_BUILD_DIR", "./build") # Configurable
# Check if required environment variables are set
if not os.environ.get("HW_MODEL"):
print("\n" + "="*80)
print("ERROR: HW_MODEL environment variable not set!")
print("="*80)
print("Please source your system configuration file:")
print(" source config_${HW_MODEL}.sh")
print("Or set HW_MODEL manually:")
print(" export HW_MODEL=your_system_name")
print("="*80 + "\n")
exit(1)
# Check if ALP_PATH is set (optional for basic functionality)
ALP_PATH = os.environ.get("ALP_PATH")
if not ALP_PATH:
print("\n" + "="*80)
print("WARNING: ALP_PATH environment variable not set!")
print("="*80)
print("The runner will work for hardware characterization, but ALP-dependent")
print("features will be disabled. To enable full functionality:")
print(" source config_${HW_MODEL}.sh")
print("Or set ALP_PATH manually:")
print(" export ALP_PATH=/path/to/ALP")
print("="*80 + "\n")
else:
print(f"ALP_PATH set to: {ALP_PATH}")
class BenchmarkConfig:
"""
Configuration class to encapsulate common benchmark parameters.
This class stores all the parameters that are passed around between functions,
reducing the number of individual parameters needed in function signatures.
"""
def __init__(self, system_name, consecutive_bytes, num_threads, cacheline_size=64,
thread_offset=0, forced_intercept=-1, level_name=None,
create_sync_level="", alloc_policy="close",
numa_level_reached=0, system_cores=0, bw_kernel_indices=None,
kernel_aggregator='mean'):
"""
Initialize benchmark configuration.
Args:
system_name: Name of the system being benchmarked
consecutive_bytes: Consecutive byte size for benchmarks
num_threads: Number of threads to use
cacheline_size: Cache line size in bytes (default: 64)
thread_offset: Thread offset for CPU affinity (default: 0)
forced_intercept: Forced intercept value for regression (default: -1)
level_name: Name of the memory level (optional)
create_sync_level: GLOBAL_SYNC level creation method (default: "")
alloc_policy: NUMA allocation policy (default: "close")
numa_level_reached: The level of the NUMA node that we've reached (default: 0)
system_cores: Total number of cores in the system (default: 0)
bw_kernel_indices: List of kernel indices to use for bandwidth measurements
(default: None → uses copy, daxpy, triad)
kernel_aggregator: Method to aggregate across kernel measurements ('mean', 'min', 'max')
"""
self.system_name = system_name
self.consecutive_bytes = consecutive_bytes
self.num_threads = num_threads
self.cacheline_size = cacheline_size
self.thread_offset = thread_offset
self.forced_intercept = forced_intercept
self.level_name = level_name
self.create_sync_level = create_sync_level
self.alloc_policy = alloc_policy
self.numa_level_reached = numa_level_reached
self.system_cores = system_cores
self.bw_kernel_indices = bw_kernel_indices if bw_kernel_indices is not None else [
KERNEL_NAME_TO_IDX[k] for k in DEFAULT_BW_KERNELS.split(',')
]
self.kernel_aggregator = kernel_aggregator
# Derived properties
self.elemsize = consecutive_bytes_to_elemsize(consecutive_bytes)
self.chunk_elems = consecutive_bytes // self.elemsize
self.cacheline_elems = cacheline_size // self.elemsize
def __str__(self):
"""String representation of the configuration."""
return (f"BenchmarkConfig(system={self.system_name}, "
f"k={self.consecutive_bytes}B, threads={self.num_threads}, "
f"cacheline={self.cacheline_size}B, level={self.level_name}, "
f"alloc_policy={self.alloc_policy}, numa_level={self.numa_level_reached}, "
f"system_cores={self.system_cores})")
def __repr__(self):
"""Detailed string representation of the configuration."""
return (f"BenchmarkConfig(system_name='{self.system_name}', "
f"consecutive_bytes={self.consecutive_bytes}, "
f"num_threads={self.num_threads}, "
f"cacheline_size={self.cacheline_size}, "
f"thread_offset={self.thread_offset}, "
f"forced_intercept={self.forced_intercept}, "
f"level_name='{self.level_name}', "
f"create_sync_level={self.create_sync_level}, "
f"alloc_policy='{self.alloc_policy}', "
f"numa_level_reached={self.numa_level_reached}, "
f"system_cores={self.system_cores})")
def copy_with(self, **kwargs):
"""
Create a copy of this config with some parameters overridden.
Args:
**kwargs: Parameters to override in the new config
Returns:
BenchmarkConfig: New configuration with overridden parameters
"""
new_config = BenchmarkConfig(
system_name=self.system_name,
consecutive_bytes=self.consecutive_bytes,
num_threads=self.num_threads,
cacheline_size=self.cacheline_size,
thread_offset=self.thread_offset,
forced_intercept=self.forced_intercept,
level_name=self.level_name,
create_sync_level=self.create_sync_level,
alloc_policy=self.alloc_policy,
numa_level_reached=self.numa_level_reached,
system_cores=self.system_cores,
bw_kernel_indices=self.bw_kernel_indices,
kernel_aggregator=self.kernel_aggregator
)
for key, value in kwargs.items():
if hasattr(new_config, key):
setattr(new_config, key, value)
else:
raise ValueError(f"Unknown parameter: {key}")
# Recalculate derived properties
new_config.elemsize = consecutive_bytes_to_elemsize(new_config.consecutive_bytes)
new_config.chunk_elems = new_config.consecutive_bytes // new_config.elemsize
new_config.cacheline_elems = new_config.cacheline_size // new_config.elemsize
return new_config
def process_benchmark_results(h, av_timers, min_timers, max_timers, bench_idx, config):
"""
Process benchmark results and generate regression plots.
Args:
h: Array of working set sizes
av_timers: Array of average timer measurements
min_timers: Array of minimum timer measurements
max_timers: Array of maximum timer measurements
bench_idx: Benchmark index (0=chase, 1=sync, 2=copy, 3=daxpy, 4=dot, 5=triad)
config: BenchmarkConfig object containing benchmark parameters
Returns:
tuple: (gi_avg, Li_avg) - bandwidth and latency parameters
"""
h_datumsize = KERNEL_VECNUM[bench_idx] * (config.cacheline_size if config.consecutive_bytes <= config.cacheline_size else config.consecutive_bytes)
h_footprint = np.array([h[i] * h_datumsize for i in range(len(h))])
h_bytes_read = np.array([h[i] * KERNEL_READS[bench_idx] * config.consecutive_bytes for i in range(len(h))])
h_bytes_written = np.array([h[i] * KERNEL_WRITES[bench_idx] * config.consecutive_bytes for i in range(len(h))])
h_total = np.array([h_bytes_read[i] + h_bytes_written[i] for i in range(len(h))])
if config.forced_intercept == -42:
h_parsed, av_timers_parsed, gi_avg, Li_avg, h_removed, timers_removed =\
[1], av_timers, 0, av_timers[0], [], []
else:
h_parsed, av_timers_parsed, gi_avg, Li_avg, h_removed, timers_removed = least_squares_fit(
h_total, av_timers, LR_reps=1, forced_intercept=config.forced_intercept)
print("Least squares fit: gi_avg = %e (%.2lf Gb/s), Li_avg = %e" % (gi_avg, 1 / gi_avg / BYTES_TO_GB if gi_avg != 0 else 0, Li_avg))
regression_plot_flag = True
if regression_plot_flag:
# Create combined time plot
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("whitegrid")
plt.figure(figsize=(12, 8))
KB_memfoot_converter = lambda h_val: 1.0 * h_val / ((KERNEL_READS[bench_idx] + KERNEL_WRITES[bench_idx])* config.consecutive_bytes) \
* h_datumsize / 1024
# Plot the fitted data
plot_all_regression_stats(h_parsed, av_timers_parsed, gi_avg, Li_avg, KB_memfoot_converter, label_prefix="Avg", line_color="blue")
# Plot the removed outliers if any
if len(h_removed) > 0:
h_removed_KB = [KB_memfoot_converter(h_val) for h_val in h_removed]
plt.scatter(h_removed_KB, timers_removed, color='red', s=100, alpha=0.8,
marker='x', linewidths=3, label='Removed outliers (avg)', zorder=5)
plt.title(f"Benchmark: {KERNEL_NAMES[bench_idx]} | Level: {config.level_name} | Threads: {config.num_threads}", fontsize=14, fontweight='bold')
plt.legend()
save_path = f"{RESULTS_DIR}/{config.system_name}/{config.alloc_policy}/k_{config.consecutive_bytes}/t_{config.num_threads}/plots/time/regression_{KERNEL_NAMES[bench_idx]}_{config.level_name}.png"
os.makedirs(os.path.dirname(save_path), exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"Time regression plot saved to: {save_path}")
log_info(f"Saved time regression plot: {save_path}")
# Create combined GBytes plot
plt.figure(figsize=(12, 8))
gbytes_converter = lambda h_val, t_val: h_val / t_val / BYTES_TO_GB
plot_all_regression_stats_gbytes(h_parsed, av_timers_parsed, gi_avg, Li_avg, KB_memfoot_converter, gbytes_converter, label_prefix="Avg", line_color="blue")
# Plot the removed outliers in GBytes if any
if len(h_removed) > 0:
gbytes_removed = []
h_to_KB_valid = []
for h_val, t_val in zip(h_removed, timers_removed):
if t_val > 0: # Avoid division by zero
h_to_KB_valid.append(KB_memfoot_converter(h_val))
gbytes_removed.append(gbytes_converter(h_val, t_val))
if len(gbytes_removed) > 0:
plt.scatter(h_to_KB_valid, gbytes_removed, color='red', s=100, alpha=0.8,
marker='x', linewidths=3, label='Removed outliers (avg)', zorder=5)
plt.title(f"Benchmark: {KERNEL_NAMES[bench_idx]} | Level: {config.level_name} | Threads: {config.num_threads}", fontsize=14, fontweight='bold')
plt.legend()
save_path = f"{RESULTS_DIR}/{config.system_name}/{config.alloc_policy}/k_{config.consecutive_bytes}/t_{config.num_threads}/plots/gbytes/regression_{KERNEL_NAMES[bench_idx]}_{config.level_name}_gbytes.png"
os.makedirs(os.path.dirname(save_path), exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
log_info(f"Saved bandwidth regression plot: {save_path}")
return gi_avg, Li_avg
def calculate_spread_cpu_affinity(num_threads, config):
"""
Calculate CPU affinity for spread policy to distribute threads across NUMA nodes.
Uses the numa_utils module to get actual NUMA topology.
Args:
num_threads: Number of threads
config: BenchmarkConfig object containing system information
Returns:
list: List of CPU IDs for thread affinity
"""
from hw_characterization.scripts.numa_utils import get_numa_topology, get_cores_per_numa_node
num_numa_nodes = get_numa_topology()['num_nodes']
cores_per_numa = get_cores_per_numa_node()
print(f"Spread policy: {num_numa_nodes} NUMA nodes, {cores_per_numa} cores per node")
# Calculate CPU affinity for spread policy
cpu_affinity = []
threads_per_node = num_threads // num_numa_nodes
residual = num_threads % num_numa_nodes
# Calculate how many threads each NUMA node will have
# First 'residual' nodes get (threads_per_node + 1) threads, rest get threads_per_node
threads_per_node_list = [threads_per_node + 1 if i < residual else threads_per_node
for i in range(num_numa_nodes)]
# Build CPU affinity using block distribution (consecutive threads per NUMA node)
# Extra threads are already accounted for in threads_per_node_list
thread_counter = 0
for numa_node in range(num_numa_nodes):
# Assign consecutive threads to this NUMA node
threads_for_this_node = threads_per_node_list[numa_node]
for thread_in_node in range(threads_for_this_node):
cpu_id = config.thread_offset + numa_node * cores_per_numa + thread_in_node
cpu_affinity.append(cpu_id)
thread_counter += 1
print(f"Spread CPU affinity: {cpu_affinity}")
return cpu_affinity
def PaHiS_benchmark_run(bench_idx, buffer_size, sub_buffer_size, config):
"""
Run PaHiS benchmark and process results.
Args:
bench_idx: Benchmark index (0=chase, 1=sync, 2=copy, 3=daxpy, 4=dot, 5=triad)
buffer_size: Buffer size in bytes
sub_buffer_size: Sub-buffer size in bytes
config: BenchmarkConfig object containing benchmark parameters
Returns:
tuple: (gi_avg, Li_avg) - bandwidth and latency parameters
"""
# Use first num_threads cores for OMP_PLACES, formatted as "{0,1,2,...}"
threads = config.num_threads
filename = f"{RESULTS_DIR}/{config.system_name}/{config.alloc_policy}/k_{config.consecutive_bytes}/t_{config.num_threads}/" + \
f"results/{config.level_name}_{KERNEL_NAMES[bench_idx]}_buf{int(buffer_size)}_sub{int(sub_buffer_size)}_t{config.num_threads}.csv"
# Check if file already exists
if os.path.exists(filename):
print(f"Loading existing results from: {filename}")
try:
df = pd.read_csv(filename)
h = df['h'].tolist() # (df['h'] * threads).tolist() #
av_timers = df['av_timers'].tolist()
min_timers = df['min_timers'].tolist()
max_timers = df['max_timers'].tolist()
print(f"Loaded {len(h)} data points from existing file")
# Process the loaded data
return process_benchmark_results(h, av_timers, min_timers, max_timers,
bench_idx, config)
except Exception as e:
print(f"Error loading existing file: {e}, running new benchmark")
env = os.environ.copy()
env["OMP_NUM_THREADS"] = str(threads)
# Build requested affinity based on policy
if config.alloc_policy == "spread":
requested = calculate_spread_cpu_affinity(threads, config)
else:
requested = [config.thread_offset + i for i in range(threads)]
# If topology provided CPU_ALLOWED_LIST, filter/pad from it; else keep requested
global CPU_ALLOWED_FROM_TOPO
if CPU_ALLOWED_FROM_TOPO:
allowed = set(expand_cpu_ranges(CPU_ALLOWED_FROM_TOPO))
adjusted = [c for c in requested if c in allowed]
if len(adjusted) < threads:
adjusted += [c for c in sorted(allowed) if c not in adjusted][:threads - len(adjusted)]
else:
adjusted = requested
env["GOMP_CPU_AFFINITY"] = " ".join(str(cpu_id) for cpu_id in adjusted)
cmd = [
f"{BUILD_DIR}/bin/PaHiS_benchmark_numa_ELEM_SIZE-{config.elemsize}_CHUNK_ELEMS-{config.chunk_elems}_CACHELINE_ELEMS-{config.cacheline_elems}",
str(bench_idx),
str(int(buffer_size)),
str(int(sub_buffer_size)),
str(threads),
config.alloc_policy,
str(config.numa_level_reached if config.numa_level_reached > 1 else 0)
]
print("Running:", " ".join(cmd))
print("OMP_NUM_THREADS:", env["OMP_NUM_THREADS"])
print("GOMP_CPU_AFFINITY:", env["GOMP_CPU_AFFINITY"])
print(
f"NUMA parameters: alloc_policy={config.alloc_policy}, interleave_flag={config.numa_level_reached if config.numa_level_reached > 1 else 0}")
log_info(
f"Launching NUMA benchmark kernel_idx={bench_idx} level={config.level_name} threads={threads} k={config.consecutive_bytes}B alloc_policy={config.alloc_policy} interleave_flag={config.numa_level_reached if config.numa_level_reached > 1 else 0}")
result = subprocess.run(cmd, env=env, capture_output=True, text=True)
# Parse bandwidth from output
h = []
av_timers = []
min_timers = []
max_timers = []
new_line_counter = 0
for line in result.stdout.splitlines():
if new_line_counter == 1:
min_timers.append(float(line.split("Min=")[1].split("s")[0].strip()))
new_line_counter += 1
elif new_line_counter == 2:
max_timers.append(float(line.split("Max=")[1].split("s")[0].strip()))
new_line_counter += 1
elif new_line_counter == 3:
av_timers.append(float(line.split("Avg=")[1].split("s")[0].strip()))
new_line_counter = 0
elif "\th:" in line:
h.append(threads*int(line.split("h:")[1].split(",")[0].strip()))
new_line_counter = 1
# Create DataFrame with the specified columns
df_data = []
for i in range(len(h)):
row = {
# Cat 1: Configuration parameters (same for each row)
'level_name': config.level_name,
'bench_idx': bench_idx,
'elemsize': config.elemsize,
'chunk_elems': config.chunk_elems,
'cacheline_elems': config.cacheline_elems,
'buffer_size': int(buffer_size),
'sub_buffer_size': int(sub_buffer_size),
'threads': threads,
'interleave_flag': config.numa_level_reached if config.numa_level_reached > 1 else 0,
# Cat 2: Measurement data (different per row)
'h': h[i], # PANASTAS NOTE: This depends on how you translate gi - is it per thread or total)
'av_timers': av_timers[i],
'min_timers': min_timers[i],
'max_timers': max_timers[i]
}
df_data.append(row)
# Save to CSV
df = pd.DataFrame(df_data)
os.makedirs(os.path.dirname(filename), exist_ok=True)
df.to_csv(filename, index=False)
print(f"Results saved to: {filename}")
log_info(f"Saved CSV: {filename}")
return process_benchmark_results(h, av_timers, min_timers, max_timers,
bench_idx, config)
def benchmark_setup(cur_level, prev_level, config):
"""
Setup benchmark parameters for a given memory level.
Args:
cur_level: Current memory level data
prev_level: Previous memory level data
config: BenchmarkConfig object containing benchmark parameters
Returns:
tuple: (pi_mult, mem_sub, buffer_size, sub_buffer_size)
"""
memi = cur_level['memi']
pi = cur_level['pi']
level_ctr = cur_level['level']
level_name = cur_level['level_name']
num_threads = config.num_threads
prev_pi_mult = int(prev_level['pi_mult'])
prev_mi = int(prev_level['mi'])
pi_mult = pi * prev_pi_mult
bench_pi = 1 if prev_pi_mult > num_threads else min(num_threads, pi_mult)//prev_pi_mult
if pi == 1:
print("Level %d(%s): pi = 1, quasi-level with pi_mult = %d" % (level_ctr, level_name, pi_mult))
# For last level (main memory), do not use the actual sum of NUMA-node memories bellow.
# Use the sum of LLC memory sizes instead (NUMA communication cost will be estimated via interleaving)
if config.numa_level_reached:
mem_sub = bench_pi * int(prev_level['mem_sub'])
config.numa_level_reached *= pi
else:
mem_sub = bench_pi*(max(int(prev_level['mem_sub']), prev_mi))
if (level_name == "NUMANode"):
config.numa_level_reached = 1
mi = memi - mem_sub
if mi <= 0 :
print("\nERROR: Level %d memory (%s) smaller than sum of previous memories (%s)"
% (level_ctr, format_bytes(memi*1024), format_bytes(mem_sub*1024)))
exit(1)
elif mi/2 <= mem_sub:
print("\nWARNING: Level %d memory (%s) close to sum of previous memories (%s)"
% (level_ctr, format_bytes(memi*1024), format_bytes(mem_sub*1024)))
# Determine bench_mem_multiplier based on allocation policy
if config.alloc_policy == 'spread':
bench_mem_multiplier = min(num_threads, config.system_cores // pi_mult)
elif config.alloc_policy == 'close':
# Default/'close' allocation
bench_mem_multiplier = (num_threads // pi_mult) if (num_threads // pi_mult) else 1
else:
print(f"\nERROR: Unsupported allocation policy '{config.alloc_policy}'")
print(f"Supported policies: 'close', 'spread'")
exit(1)
sub_buffer_size = mem_sub * 1024 * bench_mem_multiplier
buffer_size = memi * 1024 * bench_mem_multiplier
if not sub_buffer_size:
# For lowest level cache hierarchy, increase the buffer to try to find BW
buffer_size *= 2
# Ensure buffer size is a multiple of cacheline size
CACHELINE_SIZE = 64 # 64 bytes cache line size
if buffer_size % CACHELINE_SIZE != 0:
buffer_size = (buffer_size // CACHELINE_SIZE) * CACHELINE_SIZE
if sub_buffer_size % CACHELINE_SIZE != 0:
sub_buffer_size = (sub_buffer_size // CACHELINE_SIZE) * CACHELINE_SIZE
if buffer_size > MAX_BUFF_SIZE:
print("Warning: Buffer size %s exceeds MAX_BUFF_SIZE (%s), using MAX_BUFF_SIZE instead."
% (format_bytes(buffer_size), format_bytes(MAX_BUFF_SIZE)))
buffer_size = MAX_BUFF_SIZE
if sub_buffer_size > MAX_BUFF_SIZE/2:
sub_buffer_size = MAX_BUFF_SIZE/2
print(f"Running level {level_ctr} ({level_name}) benchmarks.\n"
f"\tpi={pi}, pi_mult={pi_mult}, memi={format_bytes(memi*1024)}, mem_sub={format_bytes(mem_sub*1024)}\n"
f"\tthreads={num_threads}, bench_mem_multiplier={bench_mem_multiplier}, bench_pi={bench_pi}, buffer_size={format_bytes(buffer_size)}, sub_buffer_size={format_bytes(sub_buffer_size)}")
return pi_mult, mem_sub, buffer_size, sub_buffer_size
def create_hw_tree(config):
"""
Create hardware tree by running benchmarks for all memory levels.
Args:
config: BenchmarkConfig object containing benchmark parameters
Returns:
DataFrame: Combined benchmark results for all levels
"""
from hw_characterization.scripts.parser import parse_pahis_log_to_df, get_topology_file_path
# Use hardcoded paths + configurable BUILD_DIR
results_dir = RESULTS_DIR
build_dir = BUILD_DIR
log_info(f"Start analysis: system={config.system_name}, threads={config.num_threads}, k={config.consecutive_bytes}B")
log_info(f"Dirs: topo={TOPOLOGY_DIR}, results={results_dir}, build={build_dir}")
global CPU_ALLOWED_FROM_TOPO
hw_topo, config.system_cores, config.thread_offset, CPU_ALLOWED_FROM_TOPO, config.r_scalar, config.r_vec = parse_pahis_log_to_df(
get_topology_file_path(config.system_name))
# Update config with thread_offset from topology
print(hw_topo.to_markdown())
print(f"system_cores={config.system_cores}, target_threads={config.num_threads}")
log_info(f"Parsed topology; system_cores={config.system_cores}")
output_df = pd.DataFrame()
config.numa_level_reached = 0
for level_ctr in range(len(hw_topo)):
pi = int(hw_topo.iloc[level_ctr]['pi'])
memi = int(hw_topo.iloc[level_ctr]['mi'])
hw_topo.loc[hw_topo['level'] == level_ctr, 'memi'] = memi
level_name = str(hw_topo.iloc[level_ctr]['level_name'])
if level_ctr == 0:
hw_topo.loc[hw_topo['level'] == level_ctr, 'pi_mult'] = int(hw_topo.iloc[level_ctr]['pi'])
hw_topo.loc[hw_topo['level'] == level_ctr, 'mem_sub'] = 0
continue
curr_level = hw_topo.loc[hw_topo.index[hw_topo['level'] == level_ctr][0]]
prev_level = hw_topo.loc[hw_topo.index[hw_topo['level'] == level_ctr-1][0]]
pi_mult, mem_sub, buffer_size, sub_buffer_size = benchmark_setup(
curr_level, prev_level, config)
hw_topo.loc[hw_topo.index[hw_topo['level'] == level_ctr], 'pi_mult'] = pi_mult
hw_topo.loc[hw_topo.index[hw_topo['level'] == level_ctr], 'mem_sub'] = mem_sub
gi = []
Li = []
#Run chase benchmark to get a good latency estimation
level_config = config.copy_with(level_name=level_name, forced_intercept=0)
g_est, l_est = PaHiS_benchmark_run(0, buffer_size, sub_buffer_size, level_config)
x_values = np.linspace(mem_sub+1, memi, 10000)
x_range = np.array(x_values)
predicted_times = g_est * x_range + l_est
mean_time = np.mean(predicted_times/x_range)
Li = mean_time * config.cacheline_size
print(f"Access latency (Li) for level {level_ctr}: {Li:e} seconds")
log_info(f"Li (access) for level {level_ctr} = {Li:e} s")
idx_row = hw_topo.index[hw_topo['level'] == level_ctr][0]
hw_topo.at[idx_row, 'Li'] = Li
row = hw_topo.loc[idx_row]
for idx in config.bw_kernel_indices:
kernel_config = config.copy_with(level_name=level_name, forced_intercept=0)
g, l = PaHiS_benchmark_run(idx, buffer_size, sub_buffer_size, kernel_config)
if np.isnan(g) or np.isnan(l):
print(f"(g, l) = ({g}, {l}), Retrying with forced intercept {Li/config.cacheline_size}")
retry_config = config.copy_with(level_name=level_name, forced_intercept=Li/config.cacheline_size)
g, l = PaHiS_benchmark_run(idx, buffer_size, sub_buffer_size, retry_config)
if np.isnan(g) or np.isnan(l):
hw_topo.loc[hw_topo['level'] == level_ctr, 'memi']*= 2
print(f"(g, l) = ({g}, {l}), Retrying with double max buffer size {hw_topo.loc[hw_topo['level'] == level_ctr, 'memi']}")
final_retry_config = config.copy_with(level_name=level_name, forced_intercept=Li/config.cacheline_size)
g, l = PaHiS_benchmark_run(idx, buffer_size, sub_buffer_size, final_retry_config)
record = row.to_dict()
record.update({'consecutive_bytes': int(config.consecutive_bytes), 'threads': int(config.num_threads), 'interleave_flag': config.numa_level_reached if config.numa_level_reached > 1 else 0, 'buffer_size': int(buffer_size),
'sub_buffer_size': int(sub_buffer_size),'idx': int(idx), 'gi': float(g)})
output_df = pd.concat([output_df, pd.DataFrame([record])], ignore_index=True)
gi.append(g)
gi = aggregate_values(gi, config.kernel_aggregator)
hw_topo.at[idx_row, 'gi'] = gi
# Add GLOBAL_SYNC level if requested
if config.create_sync_level:
sync_config = config.copy_with(
level_name='GLOBAL_SYNC', forced_intercept=-42)
_, Li_sync = PaHiS_benchmark_run(1, 0, 0, sync_config)
print(f"SYNC latency (Li_sync): {Li_sync:e} seconds")
log_info(f"Li_sync = {Li_sync:e} s")
# Get last level's values
last_row = hw_topo.iloc[-1]
sync_level = {
'level': int(last_row['level']) + 1,
'level_name': "GLOBAL_SYNC",
'pi': 1,
'gi': 0.0, # GLOBAL_SYNC has no bandwidth (synchronization only)
'Li': Li_sync,
'mi': last_row['mi'],
'memi': last_row['memi'],
'pi_mult': last_row['pi_mult'],
'mem_sub': last_row['mem_sub'],
'consecutive_bytes': config.consecutive_bytes,
'threads': config.num_threads,
'buffer_size': last_row['buffer_size'] if 'buffer_size' in last_row else 0,
'sub_buffer_size': last_row['sub_buffer_size'] if 'sub_buffer_size' in last_row else 0,
'idx': 0
}
# Add to hw_topo and output_df
hw_topo = pd.concat([hw_topo, pd.DataFrame([sync_level])], ignore_index=True)
output_df = pd.concat([output_df, pd.DataFrame([sync_level])], ignore_index=True)
hw_topo = hw_topo[['level', 'level_name', 'pi', 'mi', 'gi', 'Li',
'pi_mult', 'memi', 'mem_sub']]
print(output_df.to_markdown())
return output_df
def _detect_violators(agg, level_names):
"""
Detect violator positions in an aggregated value sequence that should be
monotonically non-decreasing.
Rules:
- Edge levels (first/last) are always eligible for flagging.
- Middle levels are only eligible if their two neighbors are compliant with
each other (left <= right). Otherwise the middle level is skipped because
the real problem may lie in a neighbor.
- Deadlock fallback: if no violators are flagged but violations still exist,
flag the single level with the largest deviation from avg(left, right).
Args:
agg: list of float — aggregated values per level position (GLOBAL_SYNC excluded)
level_names: list of str — level names corresponding to each position
Returns:
list of int — positions of flagged violators (may be empty if monotonic)
"""
n = len(agg)
if n <= 1:
return []
violators = []
for i in range(n):
is_first = (i == 0)
is_last = (i == n - 1)
if is_first:
# Bump at first level: higher than its right neighbor
if agg[i] > agg[i + 1]:
violators.append(i)
elif is_last:
# Dip at last level: lower than its left neighbor
if agg[i] < agg[i - 1]:
violators.append(i)
else:
# Middle level: only eligible if neighbors are compliant with each other
left, right = agg[i - 1], agg[i + 1]
if left <= right:
# Bump: higher than both neighbors
if agg[i] > right and agg[i] > left:
violators.append(i)
# Dip: lower than both neighbors
elif agg[i] < left and agg[i] < right:
violators.append(i)
# Deadlock fallback: violations exist but no violator was flagged
if not violators:
has_violation = any(agg[i] > agg[i + 1] for i in range(n - 1))
if has_violation:
# Flag the single level with the largest deviation from avg(left, right)
best_idx = -1
best_dev = -1.0
for i in range(n):
if i == 0:
expected = 0.75 * agg[1]
elif i == n - 1:
expected = 1.5 * agg[n - 2]
else:
expected = (agg[i - 1] + agg[i + 1]) / 2.0
dev = abs(agg[i] - expected)
if dev > best_dev:
best_dev = dev
best_idx = i
if best_idx >= 0:
violators.append(best_idx)
return violators
def _compute_target(agg, i):
"""
Compute the interpolated target value for a violator at position i.
- First level: 0.75 * right neighbor
- Last level: 1.5 * left neighbor
- Middle level: average of left and right neighbors
"""
n = len(agg)
if i == 0:
return 0.75 * agg[1]
elif i == n - 1:
return 1.5 * agg[n - 2]
else:
return (agg[i - 1] + agg[i + 1]) / 2.0
def _enforce_monotonicity_column(df_adjusted, group_mask, levels, level_names_map,
column, kernel_aggregator, max_iterations=10):
"""
Iteratively enforce monotonicity on a single column ('gi' or 'Li') for one
(threads, alloc_policy, consecutive_bytes) group using violator detection,
neighbor interpolation, and proportional scaling.
Args:
df_adjusted: the mutable DataFrame being adjusted in-place
group_mask: boolean Series selecting this group's rows
levels: sorted list of level numbers (GLOBAL_SYNC excluded)
level_names_map: dict mapping level number to level name
column: 'gi' or 'Li'
kernel_aggregator: 'mean', 'min', or 'max'
max_iterations: safety limit on convergence iterations
Returns:
int — total number of individual row adjustments made
"""
total_adjustments = 0
# Filter out GLOBAL_SYNC levels from consideration
active_levels = [l for l in levels if level_names_map.get(l, 'Unknown') != "GLOBAL_SYNC"]
n = len(active_levels)
if n <= 1:
return 0
for iteration in range(1, max_iterations + 1):
# Step 1: Compute aggregated values per level
agg = []
for level in active_levels:
mask = group_mask & (df_adjusted['level'] == level)
agg.append(aggregate_values(df_adjusted.loc[mask, column], kernel_aggregator))
# Check if already monotonic
is_monotonic = all(agg[i] <= agg[i + 1] for i in range(n - 1))
if is_monotonic:
if iteration > 1:
logger.debug(f" {column} converged after {iteration - 1} iteration(s)")
break
level_names_list = [level_names_map.get(l, 'Unknown') for l in active_levels]
# Step 2: Detect violators
violators = _detect_violators(agg, level_names_list)
if not violators:
# Should not happen (not monotonic but no violators), but guard anyway
logger.debug(f" {column} iteration {iteration}: non-monotonic but no violators detected, stopping")
break
logger.debug(f" {column} iteration {iteration}: agg={[f'{v:.4e}' for v in agg]}")
logger.debug(f" {column} iteration {iteration}: violators at positions {violators} "
f"({[level_names_list[v] for v in violators]})")
# Steps 3 & 4: Compute targets and apply proportional scaling
for v in violators:
level = active_levels[v]
level_name = level_names_map.get(level, 'Unknown')
mask = group_mask & (df_adjusted['level'] == level)
current_agg = agg[v]
target = _compute_target(agg, v)
if current_agg == 0:
# Guard against division by zero: set all rows to target directly
logger.debug(f" {level_name}: agg=0, setting all rows to {target:.6e}")
df_adjusted.loc[mask, column] = target
else:
scale = target / current_agg
df_adjusted.loc[mask, column] *= scale
logger.debug(f" {level_name}: {current_agg:.6e} -> {target:.6e} "
f"(scale={scale:.4f}, {mask.sum()} rows)")
total_adjustments += mask.sum()
else:
# max_iterations reached without convergence
agg_final = []
for level in active_levels:
mask = group_mask & (df_adjusted['level'] == level)
agg_final.append(aggregate_values(df_adjusted.loc[mask, column], kernel_aggregator))
logger.warning(f" {column} did not converge after {max_iterations} iterations. "
f"Final agg={[f'{v:.4e}' for v in agg_final]}")
return total_adjustments
def enforce_parameter_monotonicity(df, kernel_aggregator='mean', keep_levels=None):
"""
Enforce monotonicity constraints on bandwidth (gi) and latency (Li) values in the dataframe.
Uses iterative violator detection: levels whose aggregated value breaks the
expected non-decreasing pattern are identified and adjusted via neighbor
interpolation with proportional scaling (preserving per-kernel variability).
Violator detection rules:
- Edge levels (first/last) are always eligible for flagging.
- Middle levels are only eligible if their two neighbors are compliant with
each other (left <= right).
- Deadlock fallback: when no violator is flagged but violations persist,
the level with the largest deviation from its expected position is flagged.
Args:
df: DataFrame with benchmark results containing columns: 'level', 'level_name', 'gi', 'Li',
'threads', 'alloc_policy', 'consecutive_bytes', etc.
kernel_aggregator: Method to aggregate across kernel rows ('mean', 'min', 'max')
keep_levels: Optional list of level names to restrict enforcement to (None = all levels).
When provided, only these levels participate in monotonicity checks,
preventing excluded levels (e.g. L1Cache) from influencing kept ones.
Returns:
DataFrame: DataFrame with adjusted gi and Li values that satisfy monotonicity
"""
logger.info(f"Enforcing parameter monotonicity (aggregator={kernel_aggregator}) on raw benchmark data...")
if keep_levels:
logger.info(f" Restricting to keep_levels: {keep_levels}")
logger.debug(f" Input dataframe shape: {df.shape}")
# Create a copy to avoid modifying the original
df_adjusted = df.copy()
# Track how many values were adjusted
total_gi_adjustments = 0
total_li_adjustments = 0