-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgpubench.py
More file actions
2821 lines (2407 loc) · 111 KB
/
gpubench.py
File metadata and controls
2821 lines (2407 loc) · 111 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
# -*- coding: utf-8 -*-
# GPUBench - A Performance Benchmarking Tool for AI/ML Servers
#
# Copyright (C) 2024 Liquid Web, LLC <deveng@liquidweb.com>
# Copyright (C) 2024 Ryan MacDonald <rmacdonald@liquidweb.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import os
import sys
import time
import json
import argparse
import tempfile
import platform
import subprocess
import logging
import textwrap
import threading
import hashlib
import gzip
import importlib
import shutil
import socket
from datetime import datetime, timezone
import numpy as np
import psutil
import GPUtil
import torch
import torch.nn as nn
import torch.optim as optim
from tabulate import tabulate
import multiprocessing as mp
logger = logging.getLogger(__name__)
def configure_logging():
"""Configure project-wide logging for consistent output."""
root_logger = logging.getLogger()
if not root_logger.handlers:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%H:%M:%S",
)
else:
root_logger.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
def parse_float(value):
"""Safely parse a value into a float."""
try:
return float(str(value).strip())
except (TypeError, ValueError, AttributeError):
return None
def run_nvidia_smi_query(query_fields):
"""Query nvidia-smi for additional GPU telemetry information."""
if not is_command_available('nvidia-smi'):
return None, "`nvidia-smi` command is not available."
command = [
'nvidia-smi',
f"--query-gpu={','.join(query_fields)}",
'--format=csv,noheader,nounits'
]
try:
result = subprocess.run(command, capture_output=True, text=True, check=True)
lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
telemetry = []
for line in lines:
values = [value.strip() for value in line.split(',')]
telemetry.append(dict(zip(query_fields, values)))
return telemetry, None
except (subprocess.CalledProcessError, FileNotFoundError, OSError) as exc:
message = f"Failed to query nvidia-smi: {exc}"
logger.warning(message)
return None, message
def is_command_available(command):
"""Return True if the given command is available on PATH."""
return shutil.which(command) is not None
def check_python_package(module_name):
"""Return True if the given Python package can be imported."""
try:
importlib.import_module(module_name)
return True
except ImportError:
return False
def create_temp_benchmark_file(directory, prefix, suffix):
"""Create a temporary file for benchmarks in the target directory."""
temp_file = tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, delete=False, dir=directory)
temp_path = temp_file.name
temp_file.close()
return temp_path
def check_cuda_toolkit(torch_module):
"""Check if the CUDA toolkit or CUDA-enabled PyTorch runtime is available."""
if is_command_available('nvcc'):
return True
cuda_version = getattr(torch_module.version, 'cuda', None)
if cuda_version:
return True
return False
def run_preflight_checks(args, run_flags, gpu_available):
"""Run dependency checks and update execution flags as needed."""
logger.info("Running pre-flight dependency checks...")
updated_flags = run_flags.copy()
skip_reasons = {}
# Disk benchmarking requires fio.
if run_flags.get('disk_io'):
if not is_command_available('fio'):
logger.warning(
"`fio` is not installed or not on PATH. Disk I/O benchmarks will be skipped. "
"Install it via `sudo apt-get install -y fio` or build from https://github.com/axboe/fio."
)
updated_flags['disk_io'] = False
skip_reasons['disk_io'] = "Missing `fio`; install via `sudo apt-get install -y fio` or build from source."
# GPU logging and GPU introspection need nvidia-smi.
if run_flags.get('gpu_benchmarks') or args.log_gpu:
if not is_command_available('nvidia-smi'):
logger.warning(
"`nvidia-smi` was not detected. GPU monitoring and some GPU benchmarks may fail. "
"Install NVIDIA drivers and the CUDA toolkit from https://developer.nvidia.com/cuda-downloads."
)
if args.log_gpu:
logger.warning("Disabling GPU telemetry logging because `nvidia-smi` is unavailable.")
updated_flags['log_gpu'] = False
skip_reasons['log_gpu'] = "Missing `nvidia-smi`; install NVIDIA drivers and the CUDA toolkit."
# Ensure CUDA runtime/toolkit is available when GPU benchmarks are requested.
if run_flags.get('gpu_benchmarks') and gpu_available:
if not check_cuda_toolkit(torch):
logger.warning(
"A CUDA toolkit or CUDA-enabled PyTorch runtime was not detected. GPU benchmarks may not run. "
"Install CUDA from https://developer.nvidia.com/cuda-downloads or use a GPU-enabled PyTorch build."
)
# Optional model-specific dependencies for inference.
if run_flags.get('gpu_inference') and gpu_available:
model_name = getattr(args, 'gpu_inference_model', 'custom')
model_name_lower = model_name.lower()
if model_name_lower == 'resnet50':
if not check_python_package('torchvision'):
warning_message = (
"`torchvision` is required for the ResNet50 inference benchmark. Install it with `pip install torchvision` "
"or choose a different model via `--gpu-inference-model`. Skipping GPU inference benchmarks."
)
logger.warning(warning_message)
updated_flags['gpu_inference'] = False
skip_reasons['gpu_inference'] = warning_message
elif model_name_lower in {'bert', 'gpt2'}:
if not check_python_package('transformers'):
warning_message = (
f"The `transformers` package is required for the {model_name.upper()} inference benchmark. Install it with "
"`pip install transformers` or choose a different model via `--gpu-inference-model`. "
"Skipping GPU inference benchmarks."
)
logger.warning(warning_message)
updated_flags['gpu_inference'] = False
skip_reasons['gpu_inference'] = warning_message
return updated_flags, skip_reasons
def safe_get_gpus(context):
"""Safely retrieve GPU information, logging friendly warnings on failure."""
try:
return GPUtil.getGPUs(), None
except Exception as exc:
gpu_not_found_error = getattr(GPUtil, 'GPUNotFound', None)
gpu_query_error = getattr(GPUtil, 'GPUQueryError', None)
gputil_general_error = getattr(GPUtil, 'GPUtilError', None)
if gpu_not_found_error and isinstance(exc, gpu_not_found_error):
message = ("No GPUs were detected while {}. GPU-specific functionality "
"will be skipped.").format(context)
elif ((gpu_query_error and isinstance(exc, gpu_query_error)) or
(gputil_general_error and isinstance(exc, gputil_general_error))):
message = ("GPUtil could not query GPUs while {}: {}. GPU-specific "
"functionality will be skipped.".format(context, exc))
elif isinstance(exc, (subprocess.SubprocessError, FileNotFoundError, OSError)):
message = ("Failed to execute GPU query while {}: {}. Ensure NVIDIA drivers "
"and `nvidia-smi` are installed.".format(context, exc))
else:
message = ("Unexpected error while {}: {}. GPU-specific functionality will "
"be skipped.".format(context, exc))
logger.warning(message)
return [], message
# Set default tensor type based on precision
def set_default_tensor_type(precision):
if precision == 'fp16':
torch.set_default_dtype(torch.float16)
elif precision == 'fp32':
torch.set_default_dtype(torch.float32)
elif precision == 'fp64':
torch.set_default_dtype(torch.float64)
elif precision == 'bf16':
if torch.cuda.is_available() and torch.cuda.is_bf16_supported():
torch.set_default_dtype(torch.bfloat16)
else:
print("bfloat16 is not supported on this device. Falling back to float32.")
torch.set_default_dtype(torch.float32)
else:
print(f"Unknown precision: {precision}. Using float32.")
torch.set_default_dtype(torch.float32)
# Utility Functions
def get_system_info():
"""Collect a comprehensive snapshot of system configuration and health."""
uname = platform.uname()
boot_time = psutil.boot_time()
uptime_seconds = time.time() - boot_time if boot_time else None
cpu_freq = psutil.cpu_freq()
cpu_stats = psutil.cpu_stats()
load_avg = os.getloadavg() if hasattr(os, 'getloadavg') else (None, None, None)
cpu_model = platform.processor() or uname.processor or "Unknown"
cpu_info = {
'model': cpu_model,
'architecture': platform.machine(),
'physical_cores': psutil.cpu_count(logical=False),
'logical_cores': psutil.cpu_count(logical=True),
'current_frequency_mhz': round(cpu_freq.current, 2) if cpu_freq else None,
'max_frequency_mhz': round(cpu_freq.max, 2) if cpu_freq else None,
'min_frequency_mhz': round(cpu_freq.min, 2) if cpu_freq else None,
'load_average': load_avg,
'context_switches': getattr(cpu_stats, 'ctx_switches', None),
'interrupts': getattr(cpu_stats, 'interrupts', None),
'soft_interrupts': getattr(cpu_stats, 'soft_interrupts', None),
'syscalls': getattr(cpu_stats, 'syscalls', None),
}
svmem = psutil.virtual_memory()
swap = psutil.swap_memory()
ram_info = {
'total_gb': round(svmem.total / (1024 ** 3), 2),
'available_gb': round(svmem.available / (1024 ** 3), 2),
'used_gb': round(svmem.used / (1024 ** 3), 2),
'percent_used': svmem.percent,
}
swap_info = {
'total_gb': round(swap.total / (1024 ** 3), 2),
'used_gb': round(swap.used / (1024 ** 3), 2),
'percent_used': swap.percent,
}
disk_usage = psutil.disk_usage('/')
disk_info = {
'root_total_gb': round(disk_usage.total / (1024 ** 3), 2),
'root_used_percent': disk_usage.percent,
}
disk_partitions = []
for partition in psutil.disk_partitions(all=False):
try:
usage = psutil.disk_usage(partition.mountpoint)
except PermissionError:
continue
disk_partitions.append({
'device': partition.device,
'mountpoint': partition.mountpoint,
'fstype': partition.fstype,
'total_gb': round(usage.total / (1024 ** 3), 2),
'used_percent': usage.percent,
})
gpus, gpu_warning = safe_get_gpus("collecting system information")
nvidia_query_fields = [
'index',
'name',
'driver_version',
'vbios_version',
'temperature.gpu',
'fan.speed',
'power.draw',
'power.limit',
'utilization.gpu',
'memory.total',
'memory.used',
'clocks.current.sm',
'clocks.current.memory'
]
nvidia_telemetry, nvidia_error = run_nvidia_smi_query(nvidia_query_fields)
nvidia_telemetry_map = {}
if nvidia_telemetry:
for entry in nvidia_telemetry:
gpu_index = entry.get('index')
if gpu_index is not None:
nvidia_telemetry_map[str(gpu_index)] = entry
gpu_info_list = []
for gpu in gpus:
telemetry = nvidia_telemetry_map.get(str(gpu.id), {})
gpu_entry = {
'id': gpu.id,
'name': gpu.name,
'total_memory_gb': round(gpu.memoryTotal / 1024, 2),
'memory_used_gb': round(gpu.memoryUsed / 1024, 2),
'temperature_c': getattr(gpu, 'temperature', None),
'fan_speed_percent': getattr(gpu, 'fanSpeed', None),
'utilization_percent': getattr(gpu, 'load', None) * 100 if getattr(gpu, 'load', None) is not None else None,
'driver_version': telemetry.get('driver_version') or gpu.driver,
'vbios_version': telemetry.get('vbios_version'),
'power_draw_watts': parse_float(telemetry.get('power.draw')),
'power_limit_watts': parse_float(telemetry.get('power.limit')),
'sm_clock_mhz': parse_float(telemetry.get('clocks.current.sm')),
'memory_clock_mhz': parse_float(telemetry.get('clocks.current.memory')),
}
gpu_info_list.append(gpu_entry)
cuda_available = torch.cuda.is_available()
cuda_device_count = torch.cuda.device_count() if cuda_available else 0
cuda_devices = []
if cuda_available:
for logical_id in range(cuda_device_count):
try:
props = torch.cuda.get_device_properties(logical_id)
capability = f"{props.major}.{props.minor}"
cuda_devices.append({
'logical_id': logical_id,
'name': props.name,
'total_memory_gb': round(props.total_memory / 1e9, 2),
'multi_processor_count': props.multi_processor_count,
'compute_capability': capability,
'max_threads_per_block': props.max_threads_per_block,
})
except Exception as exc: # noqa: BLE001
logger.debug("Unable to query CUDA device %s: %s", logical_id, exc)
torch_info = {
'version': torch.__version__,
'cuda_version': torch.version.cuda,
'cudnn_version': getattr(torch.backends.cudnn, 'version', lambda: None)(),
'cuda_available': cuda_available,
'device_count': cuda_device_count,
'devices': cuda_devices,
}
network_info = []
net_stats = psutil.net_if_stats()
for interface, stats in net_stats.items():
network_info.append({
'interface': interface,
'is_up': stats.isup,
'speed_mbps': stats.speed,
'mtu': stats.mtu,
})
environment = {
'python_executable': sys.executable,
'python_version': platform.python_version(),
'cuda_visible_devices': os.environ.get('CUDA_VISIBLE_DEVICES'),
}
system_overview = {
'hostname': socket.gethostname(),
'os': platform.platform(),
'kernel': uname.release,
'uptime_seconds': round(uptime_seconds, 2) if uptime_seconds is not None else None,
'timestamp_utc': datetime.now(timezone.utc).isoformat(),
}
system_info = {
'system': system_overview,
'cpu': cpu_info,
'memory': ram_info,
'swap': swap_info,
'disk': disk_info,
'disk_partitions': disk_partitions,
'network_interfaces': network_info,
'gpu_info': gpu_info_list,
'torch': torch_info,
'environment': environment,
}
if gpu_warning:
system_info['gpu_warning'] = gpu_warning
if nvidia_error:
system_info['nvidia_smi_warning'] = nvidia_error
return system_info
def start_gpu_logging(log_file, log_metrics):
metrics = log_metrics.split(',')
query_fields = ','.join(metrics)
log_cmd = [
'nvidia-smi',
f'--query-gpu={query_fields}',
'--format=csv',
'-l', '1',
'-f', log_file
]
try:
# Start the logging process
log_process = subprocess.Popen(log_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return log_process
except Exception as e:
_print_status("error", f"Error starting GPU logging: {e}")
return None
def stop_gpu_logging(log_process):
try:
if log_process:
# Send termination signal
log_process.terminate()
# Wait for the process to terminate
log_process.wait(timeout=5)
except Exception as e:
_print_status("error", f"Error stopping GPU logging: {e}")
def _print_heading(title):
"""Render a consistent console heading banner using rounded outlines."""
banner = tabulate([[title]], tablefmt='rounded_outline', colalign=('center',))
print(f"\n{banner}")
def _print_status(label, message, *, newline_before=False):
"""Print a status line with a consistent prefix."""
prefix = f"[{label.upper()}]"
if newline_before:
print()
print(f"{prefix} {message}")
def _get_console_width(min_width=120):
"""Return the current console width with a sensible minimum fallback."""
try:
width = shutil.get_terminal_size(fallback=(min_width, 24)).columns
except OSError:
width = min_width
return max(width, min_width)
def _measure_table_width(table_str):
"""Return the maximum line width of a pre-rendered table string."""
if not table_str:
return 0
return max(len(line) for line in table_str.splitlines())
def _compute_column_widths(rows, headers):
"""Compute the natural maximum content width for each column."""
column_count = 0
if headers:
column_count = len(headers)
elif rows:
column_count = len(rows[0])
widths = [0] * column_count
for col_idx in range(column_count):
cells = []
if headers:
cells.append(headers[col_idx])
for row in rows:
if col_idx < len(row):
cells.append(row[col_idx])
max_width = 0
for cell in cells:
lines = str(cell).splitlines() or [""]
for line in lines:
max_width = max(max_width, len(line))
widths[col_idx] = max_width
return widths
def _render_table(rows, headers, tablefmt, colalign):
"""Render a table while adapting to the current console width."""
table_kwargs = {
'headers': headers,
'tablefmt': tablefmt,
}
if colalign:
table_kwargs['colalign'] = colalign
table_str = tabulate(rows, **table_kwargs)
max_width = _get_console_width()
if _measure_table_width(table_str) <= max_width:
return table_str
column_count = len(headers) if headers else (len(rows[0]) if rows else 0)
if column_count == 0:
return table_str
natural_widths = _compute_column_widths(rows, headers)
adjustable_columns = list(range(column_count))
if colalign:
adjustable_columns = [idx for idx, align in enumerate(colalign) if align != 'right']
if not adjustable_columns:
adjustable_columns = list(range(column_count))
maxcolwidths = [None] * column_count
for idx in adjustable_columns:
maxcolwidths[idx] = natural_widths[idx]
min_column_width = 12
table_str = tabulate(rows, maxcolwidths=maxcolwidths, **table_kwargs)
if _measure_table_width(table_str) <= max_width:
return table_str
# Gradually reduce adjustable columns until the table fits or we hit the minimum width.
while True:
shrinkable = [idx for idx in adjustable_columns if maxcolwidths[idx] is None or maxcolwidths[idx] > min_column_width]
if not shrinkable:
break
widest_idx = max(
shrinkable,
key=lambda idx: maxcolwidths[idx] if maxcolwidths[idx] is not None else natural_widths[idx],
)
current_width = maxcolwidths[widest_idx]
if current_width is None:
maxcolwidths[widest_idx] = min_column_width
elif current_width > min_column_width:
maxcolwidths[widest_idx] = max(min_column_width, current_width - 1)
else:
adjustable_columns.remove(widest_idx)
continue
table_str = tabulate(rows, maxcolwidths=maxcolwidths, **table_kwargs)
if _measure_table_width(table_str) <= max_width:
return table_str
if maxcolwidths[widest_idx] == min_column_width:
adjustable_columns.remove(widest_idx)
return table_str
def _print_section_table(title, rows, headers, *, tablefmt='rounded_grid', colalign=None, allow_empty=False):
"""Print a tabular section where the title is folded into the header."""
if not rows and not allow_empty:
return
display_headers = list(headers) if headers else []
if display_headers:
first_header = display_headers[0]
if first_header.strip().lower() == "category":
display_headers[0] = title
else:
display_headers[0] = f"{title} ▸ {first_header}"
print()
table_str = _render_table(rows, display_headers, tablefmt, colalign)
print(table_str)
def _format_detail_value(value):
"""Format detailed benchmark values for compact tabular display."""
if value is None:
return "N/A"
if isinstance(value, bool):
return "Yes" if value else "No"
if isinstance(value, (list, tuple)):
return "\n".join(str(item) for item in value)
if isinstance(value, dict):
return json.dumps(value, indent=2)
if isinstance(value, int) and not isinstance(value, bool):
return f"{value:,}"
if isinstance(value, float):
formatted = f"{value:,.6f}".rstrip('0').rstrip('.')
return formatted
text = str(value)
if '\n' in text:
return text
return textwrap.fill(text, width=70)
def print_detailed_results(results):
if not results:
return
_print_heading("Detailed Benchmark Results")
field_preference = [
("Input Parameters", "input_params"),
("Metrics", "metrics"),
("GFLOPS", "gflops"),
("Execution Time (s)", "execution_time"),
("Score", "score"),
]
for result in results:
if not result:
continue
task = result.get('task', 'Unknown Task')
rows = []
seen_keys = set()
for label, key in field_preference:
if key in result and key not in {'task', 'category'}:
rows.append([label, _format_detail_value(result[key])])
seen_keys.add(key)
for key, value in sorted(result.items()):
if key in seen_keys or key in {'task', 'category'}:
continue
friendly_key = key.replace('_', ' ').title()
rows.append([friendly_key, _format_detail_value(value)])
_print_section_table(
task,
rows,
["Field", "Value"],
tablefmt='rounded_grid',
colalign=('left', 'left'),
allow_empty=True,
)
def print_results_table(results, total_score, total_execution_time):
"""Render benchmark results grouped by category with consistent tables."""
if not results and total_score is None and total_execution_time is None:
return
console_width = _get_console_width()
max_width_input = max(18, min(30, console_width // 5))
max_width_metrics = max(32, min(50, int(console_width * 0.33)))
sections = [
("GPU Benchmarks", [res for res in results if res and res.get('category') == 'GPU']),
("System Benchmarks", [res for res in results if res and res.get('category') == 'System']),
("Other Benchmarks", [res for res in results if res and res.get('category') not in {'GPU', 'System'}]),
]
headers = ["Category", "Task", "Input", "Metrics", "Exec Time (s)", "Score"]
colalign = ("left", "left", "left", "left", "right", "right")
rows = []
for title, section_results in sections:
if not section_results:
continue
first_in_section = True
for result in section_results:
task = result.get('task', 'Unknown Task')
input_params = result.get('input_params', '')
metrics = result.get('metrics', 'N/A')
score = result.get('score', 'N/A')
execution_time = result.get('execution_time', 'N/A')
wrapped_input = '\n'.join(textwrap.wrap(str(input_params), width=max_width_input)) if input_params else ''
wrapped_metric = '\n'.join(textwrap.wrap(str(metrics), width=max_width_metrics)) if metrics else ''
execution_time_str = f"{float(execution_time):.2f}" if isinstance(execution_time, (int, float)) else 'N/A'
score_str = f"{float(score):.1f}" if isinstance(score, (int, float)) else 'N/A'
category_label = title if first_in_section else ""
rows.append([category_label, task, wrapped_input, wrapped_metric, execution_time_str, score_str])
first_in_section = False
if total_execution_time is not None or total_score is not None:
execution_time_str = f"{float(total_execution_time):.2f}" if isinstance(total_execution_time, (int, float)) else 'N/A'
score_str = f"{float(total_score):.1f}" if isinstance(total_score, (int, float)) else 'N/A'
rows.append([
"Summary",
"Aggregate Totals",
"",
"",
execution_time_str,
score_str,
])
_print_section_table(
"Benchmark Results",
rows,
headers,
tablefmt='rounded_grid',
colalign=colalign,
allow_empty=True,
)
def _format_value(value, unit="", precision=2):
if value is None:
return "N/A"
if isinstance(value, (int, float)):
formatted = f"{value:.{precision}f}" if not isinstance(value, int) else str(value)
else:
formatted = str(value)
return f"{formatted} {unit}".strip()
def print_system_overview(system_info, detailed=False):
"""Pretty-print system overview information."""
if not system_info:
_print_status("info", "System information unavailable.")
return
if 'error' in system_info:
_print_status("error", f"System information error: {system_info['error']}")
return
if 'gpu_warning' in system_info:
_print_status("warning", system_info['gpu_warning'])
if 'nvidia_smi_warning' in system_info:
_print_status("warning", system_info['nvidia_smi_warning'])
system_meta = system_info.get('system', {})
environment = system_info.get('environment', {})
cpu = system_info.get('cpu', {})
memory = system_info.get('memory', {})
swap = system_info.get('swap', {})
disk = system_info.get('disk', {})
gpu_info = system_info.get('gpu_info', [])
torch_info = system_info.get('torch', {})
disk_partitions = system_info.get('disk_partitions', [])
network_interfaces = system_info.get('network_interfaces', [])
def _fmt(value, unit="", precision=2, skip_zero=False):
if value is None:
return None
if skip_zero and isinstance(value, (int, float)) and value == 0:
return None
formatted = _format_value(value, unit=unit, precision=precision)
return formatted if formatted != 'N/A' else None
def _lines_to_cell(lines):
filtered = [line for line in lines if line]
return "\n".join(filtered) if filtered else "N/A"
def _format_bool(value, true_label="Yes", false_label="No"):
if value is None:
return "N/A"
return true_label if value else false_label
def _wrap_text(value, width=70):
if value is None:
return "N/A"
if isinstance(value, (int, float, bool)):
return str(value)
return textwrap.fill(str(value), width=width)
load_values = []
for value in cpu.get('load_average', []) or []:
if isinstance(value, (int, float)):
load_values.append(f"{value:.2f}")
elif value is not None:
load_values.append(str(value))
load_display = ', '.join(load_values) if load_values else None
cuda_visible_raw = environment.get('cuda_visible_devices')
if cuda_visible_raw:
cuda_visible_display = str(cuda_visible_raw)
else:
cuda_visible_display = 'Not set'
if gpu_info:
cuda_visible_display = 'Not set (all GPUs visible)'
summary_rows = []
system_lines = [
f"Host: {system_meta.get('hostname', 'Unknown')}",
f"OS: {system_meta.get('os', 'Unknown')}",
f"Kernel: {system_meta.get('kernel', 'Unknown')}",
]
summary_rows.append(('System', _lines_to_cell(system_lines)))
uptime_line = None
uptime_seconds = system_meta.get('uptime_seconds')
if uptime_seconds is not None:
uptime_line = f"Uptime: {int(uptime_seconds)} s"
timestamp_line = system_meta.get('timestamp_utc')
clock_lines = [uptime_line, f"Timestamp: {timestamp_line}" if timestamp_line else None]
summary_rows.append(('Clock', _lines_to_cell(clock_lines)))
cpu_lines = []
model = cpu.get('model') or 'Unknown'
architecture = cpu.get('architecture')
if architecture and architecture != model:
cpu_lines.append(f"Model: {model} ({architecture})")
else:
cpu_lines.append(f"Model: {model}")
core_parts = []
if cpu.get('physical_cores') is not None:
core_parts.append(f"{cpu.get('physical_cores')}P")
if cpu.get('logical_cores') is not None:
core_parts.append(f"{cpu.get('logical_cores')}L")
if core_parts:
cpu_lines.append(f"Cores: {' / '.join(core_parts)}")
freq_parts = []
for label, key in [('cur', 'current_frequency_mhz'), ('min', 'min_frequency_mhz'), ('max', 'max_frequency_mhz')]:
freq_str = _fmt(cpu.get(key), unit='MHz', precision=0, skip_zero=True)
if freq_str:
freq_parts.append(f"{label} {freq_str}")
if freq_parts:
cpu_lines.append("Freq: " + ', '.join(freq_parts))
if load_display:
cpu_lines.append(f"Load avg: {load_display}")
summary_rows.append(('CPU', _lines_to_cell(cpu_lines)))
memory_lines = []
ram_used = _fmt(memory.get('used_gb'), 'GB')
ram_total = _fmt(memory.get('total_gb'), 'GB')
if ram_used and ram_total:
memory_lines.append(f"RAM: {ram_used} / {ram_total}")
elif ram_total:
memory_lines.append(f"RAM Total: {ram_total}")
elif ram_used:
memory_lines.append(f"RAM Used: {ram_used}")
ram_available = _fmt(memory.get('available_gb'), 'GB')
if ram_available:
memory_lines.append(f"Available: {ram_available}")
ram_percent = _fmt(memory.get('percent_used'), '%', precision=1)
if ram_percent:
memory_lines.append(f"Usage: {ram_percent}")
swap_used = _fmt(swap.get('used_gb'), 'GB')
swap_total = _fmt(swap.get('total_gb'), 'GB')
swap_percent = _fmt(swap.get('percent_used'), '%', precision=1)
if swap_used and swap_total:
memory_lines.append(f"Swap: {swap_used} / {swap_total}")
elif swap_total:
memory_lines.append(f"Swap Total: {swap_total}")
if swap_percent:
memory_lines.append(f"Swap Usage: {swap_percent}")
summary_rows.append(('Memory', _lines_to_cell(memory_lines)))
storage_lines = []
root_total = _fmt(disk.get('root_total_gb'), 'GB')
root_used_percent = _fmt(disk.get('root_used_percent'), '%', precision=1)
if root_used_percent and root_total:
storage_lines.append(f"Root usage: {root_used_percent} of {root_total}")
elif root_used_percent:
storage_lines.append(f"Root usage: {root_used_percent}")
elif root_total:
storage_lines.append(f"Root capacity: {root_total}")
partition_count = len(disk_partitions)
if partition_count:
storage_lines.append(f"Partitions: {partition_count}")
summary_rows.append(('Storage', _lines_to_cell(storage_lines)))
if gpu_info:
for gpu in sorted(gpu_info, key=lambda g: g.get('id', 0)):
gpu_lines = [
f"Name: {gpu.get('name', 'Unknown')}",
f"Driver: {gpu.get('driver_version', 'Unknown')}"
]
vbios = gpu.get('vbios_version')
if vbios:
gpu_lines.append(f"VBIOS: {vbios}")
mem_used_gpu = _fmt(gpu.get('memory_used_gb'), 'GB')
mem_total_gpu = _fmt(gpu.get('total_memory_gb'), 'GB')
if mem_used_gpu and mem_total_gpu:
gpu_lines.append(f"Memory: {mem_used_gpu} / {mem_total_gpu}")
elif mem_total_gpu:
gpu_lines.append(f"Memory Total: {mem_total_gpu}")
temp_display = _fmt(gpu.get('temperature_c'), '°C')
if temp_display:
gpu_lines.append(f"Temp: {temp_display}")
util_display = _fmt(gpu.get('utilization_percent'), '%', precision=1)
if util_display:
gpu_lines.append(f"Util: {util_display}")
power_draw = _fmt(gpu.get('power_draw_watts'), 'W', precision=1)
power_limit = _fmt(gpu.get('power_limit_watts'), 'W', precision=1)
if power_draw and power_limit:
gpu_lines.append(f"Power: {power_draw} / {power_limit}")
elif power_draw:
gpu_lines.append(f"Power: {power_draw}")
elif power_limit:
gpu_lines.append(f"Power Limit: {power_limit}")
fan_display = _fmt(gpu.get('fan_speed_percent'), '%', precision=0)
if fan_display:
gpu_lines.append(f"Fan: {fan_display}")
sm_clock = _fmt(gpu.get('sm_clock_mhz'), 'MHz', precision=0)
mem_clock = _fmt(gpu.get('memory_clock_mhz'), 'MHz', precision=0)
clock_parts = []
if sm_clock:
clock_parts.append(f"SM {sm_clock}")
if mem_clock:
clock_parts.append(f"Mem {mem_clock}")
if clock_parts:
gpu_lines.append("Clocks: " + ' | '.join(clock_parts))
summary_rows.append((f"GPU {gpu.get('id', 'N/A')}", _lines_to_cell(gpu_lines)))
else:
summary_rows.append(('GPU', 'No GPUs detected.'))
torch_lines = [f"PyTorch: {torch_info.get('version', 'Unknown')}"]
if torch_info.get('cuda_version'):
torch_lines.append(f"CUDA: {torch_info.get('cuda_version')}")
if torch_info.get('cudnn_version'):
torch_lines.append(f"cuDNN: {torch_info.get('cudnn_version')}")
torch_lines.append(f"CUDA available: {_format_bool(torch_info.get('cuda_available'))}")
if torch_info.get('device_count') is not None:
torch_lines.append(f"Devices detected: {torch_info.get('device_count')}")
summary_rows.append(('PyTorch', _lines_to_cell(torch_lines)))
env_lines = []
python_version = environment.get('python_version')
if python_version:
env_lines.append(f"Python: {python_version}")
python_exec = environment.get('python_executable')
if python_exec:
env_lines.append(f"Executable: {python_exec}")
env_lines.append(f"CUDA_VISIBLE_DEVICES: {cuda_visible_display}")
summary_rows.append(('Environment', _lines_to_cell(env_lines)))
_print_section_table(
'System Overview',
summary_rows,
['Category', 'Details'],
tablefmt='rounded_grid',
colalign=('left', 'left'),
allow_empty=True,
)
if detailed:
partition_rows = []
for part in sorted(disk_partitions, key=lambda p: (p.get('mountpoint') or '', p.get('device') or '')):
partition_rows.append([
part.get('device') or 'Unknown',
part.get('mountpoint') or 'Unknown',
part.get('fstype') or 'Unknown',
_fmt(part.get('total_gb'), 'GB') or 'N/A',
_fmt(part.get('used_percent'), '%', precision=1) or 'N/A',
])
_print_section_table(
'Disk Partitions',
partition_rows,
['Device', 'Mount', 'FS', 'Total (GB)', 'Used %'],
tablefmt='rounded_grid',
colalign=('left', 'left', 'left', 'right', 'right'),
)
cpu_stats_rows = []
for label, key in [
('Context Switches', 'context_switches'),
('Interrupts', 'interrupts'),
('Soft Interrupts', 'soft_interrupts'),
('System Calls', 'syscalls'),
]:
stat_value = cpu.get(key)
if stat_value is not None:
cpu_stats_rows.append([label, stat_value])
_print_section_table(
'CPU Scheduler Stats',
cpu_stats_rows,
['Metric', 'Value'],
tablefmt='rounded_grid',
colalign=('left', 'right'),
)
torch_devices = torch_info.get('devices', [])
device_rows = []
for device in torch_devices:
device_rows.append([
device.get('logical_id'),
device.get('name', 'Unknown'),
_fmt(device.get('total_memory_gb'), 'GB') or 'N/A',
device.get('compute_capability') or 'Unknown',