-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.py
More file actions
1673 lines (1343 loc) · 67.8 KB
/
benchmark.py
File metadata and controls
1673 lines (1343 loc) · 67.8 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
import os
import time
import json
import platform
import argparse
import subprocess
import datetime
from pathlib import Path
import numpy as np
import pandas as pd
# Set matplotlib backend to non-GUI 'Agg' to avoid Qt dependency issues
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import psutil
# Try importing deep learning libraries with graceful fallbacks
try:
import torch
import torch.nn as nn
import torch.optim as optim
TORCH_AVAILABLE = True
except ImportError:
TORCH_AVAILABLE = False
print("PyTorch not available. Some benchmarks will be skipped.")
try:
import tensorflow as tf
TF_AVAILABLE = True
except ImportError:
TF_AVAILABLE = False
print("TensorFlow not available. Some benchmarks will be skipped.")
try:
import cpuinfo
CPU_INFO_AVAILABLE = True
except ImportError:
CPU_INFO_AVAILABLE = False
print("py-cpuinfo not available. CPU details will be limited.")
try:
import GPUtil
GPU_UTIL_AVAILABLE = True
except ImportError:
GPU_UTIL_AVAILABLE = False
print("GPUtil not available. NVIDIA GPU details will be limited.")
class DeepLearningBenchmark:
def __init__(self, output_dir="benchmark_results", no_plots=False):
self.results = {
"system_info": {},
"pytorch": {},
"tensorflow": {},
"numpy": {},
"memory": {},
"disk": {},
"timestamp": datetime.datetime.now().isoformat()
}
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True, parents=True)
self.no_plots = no_plots
def run_all_benchmarks(self):
"""Run all benchmarks and save results"""
print("🔍 Gathering system information...")
self.gather_system_info()
print("\n📊 Running NumPy benchmarks...")
self.benchmark_numpy()
if TORCH_AVAILABLE:
print("\n🔥 Running PyTorch benchmarks...")
self.benchmark_pytorch()
if TF_AVAILABLE:
print("\n🧠 Running TensorFlow benchmarks...")
self.benchmark_tensorflow()
print("\n💾 Checking storage performance...")
self.benchmark_disk_io()
print("\n💻 Checking memory performance...")
self.benchmark_memory()
print("\n📝 Saving results...")
self.save_results()
print("\n📈 Generating performance report...")
# Pass the no_plots flag from command line arguments
self.generate_report(no_plots=hasattr(self, 'no_plots') and self.no_plots)
print("\n✅ Benchmarks completed!")
self.print_summary()
def gather_system_info(self):
"""Gather detailed system information"""
system_info = {
"platform": platform.platform(),
"processor": platform.processor(),
"python_version": platform.python_version(),
"total_memory_gb": round(psutil.virtual_memory().total / (1024**3), 2),
"logical_cpu_count": psutil.cpu_count(logical=True),
"physical_cpu_count": psutil.cpu_count(logical=False),
}
# Get detailed CPU info if available
if CPU_INFO_AVAILABLE:
cpu_info = cpuinfo.get_cpu_info()
system_info.update({
"cpu_brand": cpu_info.get("brand_raw", "Unknown"),
"cpu_hz": cpu_info.get("hz_actual_friendly", "Unknown"),
"cpu_arch": cpu_info.get("arch", "Unknown"),
"cpu_bits": cpu_info.get("bits", "Unknown"),
"cpu_flags": cpu_info.get("flags", [])
})
# PyTorch GPU info
if TORCH_AVAILABLE:
system_info["cuda_available"] = torch.cuda.is_available()
if torch.cuda.is_available():
system_info["cuda_version"] = torch.version.cuda
system_info["cuda_device_count"] = torch.cuda.device_count()
system_info["cuda_current_device"] = torch.cuda.current_device()
system_info["cuda_device_name"] = torch.cuda.get_device_name(0)
# Get memory info for the GPU
for i in range(torch.cuda.device_count()):
props = torch.cuda.get_device_properties(i)
system_info[f"cuda_device_{i}_name"] = props.name
system_info[f"cuda_device_{i}_total_memory"] = round(props.total_memory / (1024**3), 2) # GB
# TensorFlow GPU info
if TF_AVAILABLE:
system_info["tf_version"] = tf.__version__
system_info["tf_gpu_available"] = len(tf.config.list_physical_devices('GPU')) > 0
system_info["tf_physical_devices"] = {
device_type: len(tf.config.list_physical_devices(device_type))
for device_type in ['GPU', 'CPU']
}
# Get more detailed TF GPU info if available
if system_info["tf_gpu_available"]:
gpus = tf.config.list_physical_devices('GPU')
for i, gpu in enumerate(gpus):
system_info[f"tf_gpu_{i}"] = str(gpu)
# Additional GPU info using GPUtil for NVIDIA GPUs
if GPU_UTIL_AVAILABLE:
try:
gpus = GPUtil.getGPUs()
for i, gpu in enumerate(gpus):
system_info[f"gpu_{i}_name"] = gpu.name
system_info[f"gpu_{i}_driver"] = gpu.driver
system_info[f"gpu_{i}_memory_total"] = gpu.memoryTotal
system_info[f"gpu_{i}_memory_used"] = gpu.memoryUsed
system_info[f"gpu_{i}_temperature"] = gpu.temperature
except Exception as e:
system_info["gputil_error"] = str(e)
self.results["system_info"] = system_info
# Print some basic system info
print(f"System: {system_info['platform']}")
print(f"CPU: {system_info.get('cpu_brand', system_info['processor'])}")
print(f"Cores: {system_info['physical_cpu_count']} physical, {system_info['logical_cpu_count']} logical")
print(f"Memory: {system_info['total_memory_gb']} GB")
if TORCH_AVAILABLE and system_info["cuda_available"]:
print(f"GPU: {system_info['cuda_device_name']}")
print(f"CUDA Version: {system_info['cuda_version']}")
elif TF_AVAILABLE and system_info["tf_gpu_available"]:
print(f"TensorFlow GPU: {system_info['tf_physical_devices']}")
else:
print("No GPU detected for deep learning")
def benchmark_numpy(self):
"""Benchmark NumPy for basic linear algebra operations"""
print("Testing NumPy matrix operations...")
results = {}
# Test matrix multiplication with increasing sizes
matrix_sizes = [128, 512, 1024, 2048, 4096]
for size in matrix_sizes:
print(f" Matrix multiplication {size}x{size}...", end="", flush=True)
# Generate random matrices
a = np.random.rand(size, size).astype(np.float32)
b = np.random.rand(size, size).astype(np.float32)
# Warm-up
np.matmul(a, b)
# Benchmark
start_time = time.time()
np.matmul(a, b)
elapsed = time.time() - start_time
results[f"matmul_{size}"] = elapsed
print(f" {elapsed:.3f} seconds")
# Test SVD decomposition (common in many ML algorithms)
for size in [128, 512, 1024]:
print(f" SVD decomposition {size}x{size}...", end="", flush=True)
# Generate random matrix
a = np.random.rand(size, size).astype(np.float32)
# Benchmark
start_time = time.time()
np.linalg.svd(a)
elapsed = time.time() - start_time
results[f"svd_{size}"] = elapsed
print(f" {elapsed:.3f} seconds")
self.results["numpy"] = results
def benchmark_pytorch(self):
"""Benchmark PyTorch operations and models"""
if not TORCH_AVAILABLE:
return
results = {
"operations": {},
"training": {},
"inference": {},
"cuda": {} # New section for CUDA-specific tests
}
# Determine device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Running PyTorch benchmarks on: {device}")
# Run CUDA-specific tests if available
if device.type == "cuda":
print("Running CUDA-specific tests...")
cuda_results = self._benchmark_cuda_operations()
results["cuda"] = cuda_results
# Test tensor operations
print("Testing PyTorch tensor operations...")
# Matrix multiplication
matrix_sizes = [512, 1024, 2048, 4096]
for size in matrix_sizes:
print(f" Matrix multiplication {size}x{size}...", end="", flush=True)
# Generate random matrices
a = torch.rand(size, size, device=device)
b = torch.rand(size, size, device=device)
# Warm-up
torch.matmul(a, b)
torch.cuda.synchronize() if device.type == "cuda" else None
# Benchmark
start_time = time.time()
c = torch.matmul(a, b)
torch.cuda.synchronize() if device.type == "cuda" else None
elapsed = time.time() - start_time
results["operations"][f"matmul_{size}"] = elapsed
print(f" {elapsed:.3f} seconds")
# Convolution operation (important for CNNs)
batch_sizes = [16, 32, 64]
for batch_size in batch_sizes:
print(f" Conv2d batch_size={batch_size}...", end="", flush=True)
# Create a sample input and convolution layer
input_tensor = torch.rand(batch_size, 3, 224, 224, device=device)
conv_layer = nn.Conv2d(3, 64, kernel_size=3, padding=1).to(device)
# Warm-up
conv_layer(input_tensor)
torch.cuda.synchronize() if device.type == "cuda" else None
# Benchmark
start_time = time.time()
output = conv_layer(input_tensor)
torch.cuda.synchronize() if device.type == "cuda" else None
elapsed = time.time() - start_time
results["operations"][f"conv2d_b{batch_size}"] = elapsed
print(f" {elapsed:.3f} seconds")
# Test model training (simple CNN for MNIST-like data)
print("Testing model training...")
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 3, 1)
self.conv2 = nn.Conv2d(16, 32, 3, 1)
self.fc1 = nn.Linear(5*5*32, 128)
self.fc2 = nn.Linear(128, 10)
self.relu = nn.ReLU()
self.max_pool = nn.MaxPool2d(2)
def forward(self, x):
x = self.relu(self.conv1(x))
x = self.max_pool(x)
x = self.relu(self.conv2(x))
x = self.max_pool(x)
x = x.view(-1, 5*5*32)
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# Create a simple dataset
batch_size = 64
train_data = torch.rand(batch_size, 1, 28, 28, device=device)
train_labels = torch.randint(0, 10, (batch_size,), device=device)
# Create model and optimizer
model = SimpleCNN().to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
# Warm-up
for _ in range(3):
optimizer.zero_grad()
output = model(train_data)
loss = criterion(output, train_labels)
loss.backward()
optimizer.step()
torch.cuda.synchronize() if device.type == "cuda" else None
# Benchmark training for 10 iterations
start_time = time.time()
for _ in range(10):
optimizer.zero_grad()
output = model(train_data)
loss = criterion(output, train_labels)
loss.backward()
optimizer.step()
torch.cuda.synchronize() if device.type == "cuda" else None
train_elapsed = time.time() - start_time
results["training"]["cnn_10epochs"] = train_elapsed
results["training"]["cnn_iterations_per_sec"] = 10 / train_elapsed
print(f" Training 10 iterations: {train_elapsed:.3f} seconds ({10/train_elapsed:.2f} it/s)")
# Test inference with larger batch size
print("Testing inference...")
infer_batch_size = 128
infer_data = torch.rand(infer_batch_size, 1, 28, 28, device=device)
# Warm-up
with torch.no_grad():
model(infer_data)
torch.cuda.synchronize() if device.type == "cuda" else None
# Benchmark inference
n_runs = 50
start_time = time.time()
with torch.no_grad():
for _ in range(n_runs):
model(infer_data)
torch.cuda.synchronize() if device.type == "cuda" else None
infer_elapsed = time.time() - start_time
results["inference"]["cnn_inference"] = infer_elapsed
results["inference"]["images_per_sec"] = (n_runs * infer_batch_size) / infer_elapsed
print(f" Inference: {infer_elapsed:.3f} seconds " +
f"({(n_runs * infer_batch_size) / infer_elapsed:.2f} images/s)")
# Test with a larger model (ResNet-like)
if device.type == "cuda" or self.results["system_info"]["total_memory_gb"] > 8:
print("Testing larger model (ResNet)...")
# Try importing a pretrained model
try:
from torchvision.models import resnet50
resnet = resnet50(pretrained=False).to(device)
resnet.eval()
# Benchmark with standard ImageNet size
resnet_batch = 16
resnet_data = torch.rand(resnet_batch, 3, 224, 224, device=device)
# Warm-up
with torch.no_grad():
resnet(resnet_data)
torch.cuda.synchronize() if device.type == "cuda" else None
# Benchmark
resnet_runs = 10
start_time = time.time()
with torch.no_grad():
for _ in range(resnet_runs):
resnet(resnet_data)
torch.cuda.synchronize() if device.type == "cuda" else None
resnet_elapsed = time.time() - start_time
results["inference"]["resnet50_inference"] = resnet_elapsed
results["inference"]["resnet50_images_per_sec"] = (resnet_runs * resnet_batch) / resnet_elapsed
print(f" ResNet50 inference: {resnet_elapsed:.3f} seconds " +
f"({(resnet_runs * resnet_batch) / resnet_elapsed:.2f} images/s)")
except Exception as e:
print(f" Could not test ResNet: {e}")
results["inference"]["resnet50_error"] = str(e)
self.results["pytorch"] = results
def benchmark_tensorflow(self):
"""Benchmark TensorFlow operations and models"""
if not TF_AVAILABLE:
return
results = {
"operations": {},
"training": {},
"inference": {}
}
print("Testing TensorFlow tensor operations...")
# Check if GPU is being used
physical_devices = tf.config.list_physical_devices('GPU')
if physical_devices:
tf.config.experimental.set_memory_growth(physical_devices[0], True)
print(f"TensorFlow using GPU: {physical_devices[0]}")
else:
print("TensorFlow using CPU")
# Matrix multiplication
matrix_sizes = [512, 1024, 2048, 4096]
for size in matrix_sizes:
print(f" Matrix multiplication {size}x{size}...", end="", flush=True)
# Generate random matrices
a = tf.random.normal([size, size])
b = tf.random.normal([size, size])
# Warm-up
tf.matmul(a, b)
# Benchmark
start_time = time.time()
c = tf.matmul(a, b)
elapsed = time.time() - start_time
results["operations"][f"matmul_{size}"] = elapsed
print(f" {elapsed:.3f} seconds")
# Convolution operation
batch_sizes = [16, 32, 64]
for batch_size in batch_sizes:
print(f" Conv2D batch_size={batch_size}...", end="", flush=True)
# Create a sample input and convolution layer
input_tensor = tf.random.normal([batch_size, 224, 224, 3])
conv_layer = tf.keras.layers.Conv2D(64, 3, padding='same')
# Warm-up
_ = conv_layer(input_tensor)
# Benchmark
start_time = time.time()
output = conv_layer(input_tensor)
elapsed = time.time() - start_time
results["operations"][f"conv2d_b{batch_size}"] = elapsed
print(f" {elapsed:.3f} seconds")
# Test model training
print("Testing model training...")
# Create a simple CNN model
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(16, 3, activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10)
])
model.compile(
optimizer=tf.keras.optimizers.Adam(0.001),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
# Create a simple dataset
batch_size = 64
train_data = tf.random.normal([batch_size, 28, 28, 1])
train_labels = tf.random.uniform([batch_size], minval=0, maxval=10, dtype=tf.int32)
# Warm-up
model.fit(train_data, train_labels, epochs=1, verbose=0)
# Benchmark training
start_time = time.time()
model.fit(train_data, train_labels, epochs=5, verbose=0)
train_elapsed = time.time() - start_time
results["training"]["cnn_5epochs"] = train_elapsed
results["training"]["seconds_per_epoch"] = train_elapsed / 5
print(f" Training 5 epochs: {train_elapsed:.3f} seconds ({train_elapsed/5:.3f} s/epoch)")
# Test inference
print("Testing inference...")
infer_batch_size = 128
infer_data = tf.random.normal([infer_batch_size, 28, 28, 1])
# Warm-up
model.predict(infer_data, verbose=0)
# Benchmark inference
n_runs = 20
start_time = time.time()
for _ in range(n_runs):
model.predict(infer_data, verbose=0)
infer_elapsed = time.time() - start_time
results["inference"]["cnn_inference"] = infer_elapsed
results["inference"]["images_per_sec"] = (n_runs * infer_batch_size) / infer_elapsed
print(f" Inference: {infer_elapsed:.3f} seconds " +
f"({(n_runs * infer_batch_size) / infer_elapsed:.2f} images/s)")
# Test with a larger model if available
try:
if physical_devices or self.results["system_info"]["total_memory_gb"] > 8:
print("Testing larger model (ResNet50)...")
# Load pretrained model
resnet = tf.keras.applications.ResNet50(weights=None, include_top=True)
# Benchmark with standard ImageNet size
resnet_batch = 16
resnet_data = tf.random.normal([resnet_batch, 224, 224, 3])
# Warm-up
resnet.predict(resnet_data, verbose=0)
# Benchmark
resnet_runs = 10
start_time = time.time()
for _ in range(resnet_runs):
resnet.predict(resnet_data, verbose=0)
resnet_elapsed = time.time() - start_time
results["inference"]["resnet50_inference"] = resnet_elapsed
results["inference"]["resnet50_images_per_sec"] = (resnet_runs * resnet_batch) / resnet_elapsed
print(f" ResNet50 inference: {resnet_elapsed:.3f} seconds " +
f"({(resnet_runs * resnet_batch) / resnet_elapsed:.2f} images/s)")
except Exception as e:
print(f" Could not test ResNet: {e}")
results["inference"]["resnet50_error"] = str(e)
self.results["tensorflow"] = results
def _benchmark_cuda_operations(self):
"""Run CUDA-specific benchmarks to test GPU capabilities"""
cuda_results = {}
try:
# Check CUDA and GPU properties
cuda_results["cuda_version"] = torch.version.cuda
cuda_results["cudnn_version"] = torch.backends.cudnn.version()
cuda_results["cudnn_enabled"] = torch.backends.cudnn.enabled
cuda_results["gpu_count"] = torch.cuda.device_count()
# Test CUDA memory operations
print(" Testing CUDA memory operations...")
mem_results = self._test_cuda_memory()
cuda_results["memory"] = mem_results
# Test CUDA transfer speeds
print(" Testing CPU-GPU transfer speeds...")
transfer_results = self._test_cuda_transfers()
cuda_results["transfer"] = transfer_results
# Test CUDA kernel launch overhead
print(" Testing CUDA kernel launch overhead...")
kernel_results = self._test_cuda_kernel_overhead()
cuda_results["kernel_overhead"] = kernel_results
# Test CUDA numerical precision
print(" Testing CUDA numerical precision...")
precision_results = self._test_cuda_precision()
cuda_results["precision"] = precision_results
# Test multi-GPU if available
if torch.cuda.device_count() > 1:
print(f" Testing multi-GPU operations across {torch.cuda.device_count()} GPUs...")
multi_gpu_results = self._test_multi_gpu()
cuda_results["multi_gpu"] = multi_gpu_results
except Exception as e:
print(f" Error during CUDA tests: {e}")
cuda_results["error"] = str(e)
return cuda_results
def _test_cuda_memory(self):
"""Test CUDA memory allocation, transfer, and bandwidth"""
results = {}
# Get total and available memory
results["total_memory"] = torch.cuda.get_device_properties(0).total_memory / (1024**3) # in GB
results["max_memory_reserved"] = torch.cuda.max_memory_reserved() / (1024**3) # in GB
# Test allocation time for different tensor sizes
sizes = [
(1000, 1000), # ~4 MB for float32
(5000, 5000), # ~100 MB for float32
(10000, 10000), # ~400 MB for float32
]
alloc_times = {}
for i, size in enumerate(sizes):
# Skip larger tests if we're running low on memory
if i > 0 and torch.cuda.memory_allocated() / torch.cuda.get_device_properties(0).total_memory > 0.7:
print(f" Skipping allocation test for size {size} due to memory constraints")
continue
# Measure allocation time
torch.cuda.synchronize()
start = time.time()
x = torch.rand(size, device="cuda")
torch.cuda.synchronize()
alloc_time = time.time() - start
# Store result and free memory
size_mb = x.nelement() * x.element_size() / (1024**2)
alloc_times[f"{size[0]}x{size[1]}"] = {
"time_seconds": alloc_time,
"size_mb": size_mb,
"speed_gbps": (size_mb / 1024) / alloc_time
}
del x
torch.cuda.empty_cache()
results["allocation"] = alloc_times
# Test memset speed (zeroing memory)
memset_times = {}
for size in [(10000, 10000)]: # Just test one large size
x = torch.rand(size, device="cuda")
torch.cuda.synchronize()
start = time.time()
x.zero_()
torch.cuda.synchronize()
memset_time = time.time() - start
size_mb = x.nelement() * x.element_size() / (1024**2)
memset_times[f"{size[0]}x{size[1]}"] = {
"time_seconds": memset_time,
"size_mb": size_mb,
"speed_gbps": (size_mb / 1024) / memset_time
}
del x
torch.cuda.empty_cache()
results["memset"] = memset_times
return results
def _test_cuda_transfers(self):
"""Test CPU to GPU and GPU to CPU transfer speeds"""
results = {}
sizes = [
(1000, 1000), # ~4 MB for float32
(8000, 8000), # ~256 MB for float32
]
h2d_times = {} # Host to Device (CPU to GPU)
d2h_times = {} # Device to Host (GPU to CPU)
for size in sizes:
# Create CPU tensor
x_cpu = torch.rand(size)
# Measure Host to Device transfer (CPU -> GPU)
torch.cuda.synchronize()
start = time.time()
x_gpu = x_cpu.cuda()
torch.cuda.synchronize()
h2d_time = time.time() - start
size_mb = x_cpu.nelement() * x_cpu.element_size() / (1024**2)
h2d_times[f"{size[0]}x{size[1]}"] = {
"time_seconds": h2d_time,
"size_mb": size_mb,
"speed_gbps": (size_mb / 1024) / h2d_time
}
# Measure Device to Host transfer (GPU -> CPU)
torch.cuda.synchronize()
start = time.time()
x_back = x_gpu.cpu()
torch.cuda.synchronize()
d2h_time = time.time() - start
d2h_times[f"{size[0]}x{size[1]}"] = {
"time_seconds": d2h_time,
"size_mb": size_mb,
"speed_gbps": (size_mb / 1024) / d2h_time
}
# Clean up
del x_cpu, x_gpu, x_back
torch.cuda.empty_cache()
results["cpu_to_gpu"] = h2d_times
results["gpu_to_cpu"] = d2h_times
# Test pinned memory transfer speed if available
try:
# Create pinned memory tensor
x_pinned = torch.rand(8000, 8000).pin_memory()
# Measure transfer with pinned memory
torch.cuda.synchronize()
start = time.time()
x_gpu = x_pinned.cuda(non_blocking=True)
torch.cuda.synchronize()
pinned_time = time.time() - start
size_mb = x_pinned.nelement() * x_pinned.element_size() / (1024**2)
results["pinned_memory"] = {
"time_seconds": pinned_time,
"size_mb": size_mb,
"speed_gbps": (size_mb / 1024) / pinned_time
}
# Clean up
del x_pinned, x_gpu
torch.cuda.empty_cache()
except Exception as e:
results["pinned_memory_error"] = str(e)
return results
def _test_cuda_kernel_overhead(self):
"""Test CUDA kernel launch overhead"""
results = {}
# Test with a simple operation (addition)
x = torch.ones(10, device="cuda")
y = torch.ones(10, device="cuda")
# Warm up
for _ in range(5):
z = x + y
torch.cuda.synchronize()
# Measure overhead for many small kernel launches
iterations = 1000
start = time.time()
for _ in range(iterations):
z = x + y
torch.cuda.synchronize() # Force waiting for kernel completion
total_time = time.time() - start
results["small_kernel_avg_overhead_ms"] = (total_time / iterations) * 1000
# Test kernel fusion capabilities
# Create tensors for multiple operations
a = torch.rand(5000, 5000, device="cuda")
b = torch.rand(5000, 5000, device="cuda")
c = torch.rand(5000, 5000, device="cuda")
# Warm up
d = a + b + c
del d
torch.cuda.synchronize()
# Measure time for separate operations
start = time.time()
temp = a + b
result = temp + c
torch.cuda.synchronize()
separate_time = time.time() - start
# Measure time for fused operations
torch.cuda.synchronize()
start = time.time()
result = a + b + c
torch.cuda.synchronize()
fused_time = time.time() - start
results["separate_ops_time"] = separate_time
results["fused_ops_time"] = fused_time
results["fusion_speedup"] = separate_time / fused_time if fused_time > 0 else 0
return results
def _test_cuda_precision(self):
"""Test different numerical precision performance on CUDA"""
results = {}
# Test different data types
dtypes = [
(torch.float32, "float32"),
(torch.float16, "float16"),
(torch.int32, "int32"),
(torch.int64, "int64")
]
# Try to add bfloat16 if available
try:
dtypes.append((torch.bfloat16, "bfloat16"))
except AttributeError:
pass
# Create tensors and test matmul performance
size = 4096
for dtype, name in dtypes:
try:
# Skip integer types for matmul
if "int" in name:
continue
a = torch.rand(size, size, dtype=dtype, device="cuda")
b = torch.rand(size, size, dtype=dtype, device="cuda")
# Warm up
c = torch.matmul(a, b)
torch.cuda.synchronize()
# Measure performance
start = time.time()
c = torch.matmul(a, b)
torch.cuda.synchronize()
elapsed = time.time() - start
# Calculate throughput in TFLOPS
# Each matrix multiply does 2*N^3 operations
ops = 2 * (size ** 3)
results[f"matmul_{name}_time"] = elapsed
results[f"matmul_{name}_tflops"] = (ops / elapsed) / 1e12
# Clean up
del a, b, c
torch.cuda.empty_cache()
except Exception as e:
results[f"error_{name}"] = str(e)
# Test Tensor Core operations if available
if torch.cuda.get_device_capability(0)[0] >= 7: # Volta or later
try:
# Enable TensorCores
torch.backends.cudnn.benchmark = True
a = torch.rand(size, size, dtype=torch.float16, device="cuda")
b = torch.rand(size, size, dtype=torch.float16, device="cuda")
# Warm up with TensorCores
c = torch.matmul(a, b)
torch.cuda.synchronize()
# Measure performance
start = time.time()
c = torch.matmul(a, b)
torch.cuda.synchronize()
tensorcore_time = time.time() - start
# Calculate throughput
ops = 2 * (size ** 3)
results["matmul_tensorcore_time"] = tensorcore_time
results["matmul_tensorcore_tflops"] = (ops / tensorcore_time) / 1e12
# Clean up
del a, b, c
torch.cuda.empty_cache()
# Reset benchmark setting
torch.backends.cudnn.benchmark = False
except Exception as e:
results["error_tensorcore"] = str(e)
return results
def _test_multi_gpu(self):
"""Test multi-GPU operations if multiple GPUs are available"""
results = {}
gpu_count = torch.cuda.device_count()
if gpu_count <= 1:
return {"available": False}
results["available"] = True
results["count"] = gpu_count
# Test data parallel performance
try:
from torch.nn.parallel import DataParallel
class SimpleModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.bn = torch.nn.BatchNorm2d(64)
self.relu = torch.nn.ReLU()
self.fc = torch.nn.Linear(64 * 224 * 224, 1000)
def forward(self, x):
x = self.relu(self.bn(self.conv(x)))
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# Create model and wrap in DataParallel
model = SimpleModel().cuda()
dp_model = DataParallel(model)
# Create input data
batch_size = 16
input_data = torch.rand(batch_size, 3, 224, 224, device="cuda")
# Test single GPU
torch.cuda.synchronize()
start = time.time()
output = model(input_data)
torch.cuda.synchronize()
single_gpu_time = time.time() - start
# Test multi-GPU
torch.cuda.synchronize()
start = time.time()
output = dp_model(input_data)
torch.cuda.synchronize()
multi_gpu_time = time.time() - start
results["single_gpu_time"] = single_gpu_time
results["multi_gpu_time"] = multi_gpu_time
results["speedup"] = single_gpu_time / multi_gpu_time if multi_gpu_time > 0 else 0
# Clean up
del model, dp_model, input_data, output
torch.cuda.empty_cache()
except Exception as e:
results["error"] = str(e)
return results
def print_summary(self):
"""Print a summary of benchmark results to console"""
rating = self._calculate_performance_rating()
print("\n" + "=" * 60)
print(f"BENCHMARK SUMMARY")
print("=" * 60)
print(f"Overall Performance Rating: {rating['overall_rating']}/10")
print(f"Category: {rating['category']}")
print(f"\nStrengths: {', '.join(rating['strengths'])}")
print(f"Weaknesses: {', '.join(rating['weaknesses'])}")
# Add CUDA-specific summary if available
if TORCH_AVAILABLE and torch.cuda.is_available() and "pytorch" in self.results and "cuda" in self.results["pytorch"]:
cuda_results = self.results["pytorch"]["cuda"]
if cuda_results and "precision" in cuda_results:
print("\nCUDA Performance:")
# Show precision tests results if available
precision = cuda_results["precision"]
for key, value in precision.items():
if key.startswith("matmul_") and key.endswith("_tflops"):
format_name = key.replace("matmul_", "").replace("_tflops", "")
print(f" {format_name.upper()} performance: {value:.2f} TFLOPS")
# Show memory transfer speeds
if "transfer" in cuda_results and "cpu_to_gpu" in cuda_results["transfer"]:
for size, data in cuda_results["transfer"]["cpu_to_gpu"].items():
if "8000x8000" in size: # Just show the largest size
print(f" CPU → GPU transfer: {data.get('speed_gbps', 0):.2f} GB/s")
break
# Show tensor cores if tested
if "matmul_tensorcore_tflops" in precision:
tc_speedup = precision.get("matmul_tensorcore_tflops", 0) / precision.get("matmul_float16_tflops", 1)
print(f" Tensor Cores: {'Available' if tc_speedup > 1.2 else 'Limited benefit'}")
if tc_speedup > 1.2:
print(f" Tensor Core speedup: {tc_speedup:.2f}x over FP16")