-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrun.py
More file actions
451 lines (371 loc) · 14.8 KB
/
run.py
File metadata and controls
451 lines (371 loc) · 14.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
"""
Benchmark Runner Script
This script builds and runs benchmarks for various tensor operations implemented in C++.
It supports both CPU and GPU benchmarks based on user input.
It compares the performance of these implementations against PyTorch (on the same device)
equivalents if PyTorch is available.
"""
import subprocess
import sys
import os
import re
import argparse
import time
try:
import torch
HAS_TORCH = True
except ModuleNotFoundError:
HAS_TORCH = False
print("PyTorch not found, running only C++.\n")
# Configuration
EXECUTABLE_PATHS_CPU = [
"./bin/test_trivial.out",
"./bin/test_concat.out",
"./bin/test_topk.out",
"./bin/test_transpose.out",
"./bin/test_where.out",
]
EXECUTABLE_PATHS_GPU = [
"./build/test_trivial",
"./build/test_transpose",
"./build/test_concat",
"./build/test_where",
"./build/test_topk",
]
BENCHMARK_SIZES = [128, 256, 512, 1024, 2048, 4096, 8192]
def build_kernel_tests_cpu():
"""
Calls the Makefile to build the kernel tests.
Returns True if successful, False otherwise.
"""
print("Building kernel tests with Make...")
try:
# Check if Makefile exists
if not os.path.exists("Makefile"):
print("Error: Makefile not found in current directory")
return False
# Run 'make'.
subprocess.run(["make", "-j8"], check=True)
print("Build successful\n")
return True
except subprocess.CalledProcessError:
print("Build failed. Please fix C++ errors before running benchmarks")
return False
except FileNotFoundError:
print("Error: 'make' command not found. Is it installed?")
return False
def build_kernel_tests_gpu():
"""
Runs cmake to build the kernel tests.
Returns True if successful, False otherwise.
"""
print("Building kernel tests with CMake...")
try:
# Check if Makefile exists
if not os.path.exists("Makefile"):
print("Error: Makefile not found in current directory")
return False
# Run 'make'.
subprocess.run(["cmake", "-S.", "-Bbuild"], check=True)
subprocess.run(["cmake", "--build", "build", "-j8"], check=True)
print("Build successful\n")
return True
except subprocess.CalledProcessError:
print("Build failed. Please fix C++ errors before running benchmarks")
return False
except FileNotFoundError:
print("Error: 'cmake' command not found. Is it installed?")
return False
def get_op_name(executable_path):
"""
Infers the operation name from the executable path.
"""
if "trivial" in executable_path:
return "trivial"
if "transpose" in executable_path:
return "transpose"
if "concat" in executable_path:
return "concat"
if "where" in executable_path:
return "where"
if "topk" in executable_path:
return "topk"
return "unknown"
def run_pytorch_benchmark(op_name, N, num_repeats=10, warmup=10):
"""
Runs the equivalent operation in PyTorch and measures execution time.
Compatible with both CPU and GPU.
Parameters:
- op_name: Name of the operation to benchmark.
- N: Size parameter for the operation.
- num_repeats: Number of times to repeat the operation for averaging.
- warmup: Number of warmup iterations before timing.
Returns:
- Average execution time in milliseconds, or None if operation is unknown.
"""
if not HAS_TORCH:
return None
# Detect device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Setup Data
if op_name == "trivial":
x = torch.randn(N, N, device=device, dtype=torch.float32)
y = torch.empty_like(x)
op = lambda: y.copy_(x) # noqa: E731
elif op_name == "transpose":
x = torch.randn(N, N, device=device, dtype=torch.float32)
y = torch.empty(N, N, device=device, dtype=torch.float32)
op = lambda: y.copy_(x.t()) # noqa: E731
elif op_name == "concat":
t1 = torch.randn(N, N, device=device, dtype=torch.float32)
t2 = torch.randn(N, N, device=device, dtype=torch.float32)
t3 = torch.randn(N, N, device=device, dtype=torch.float32)
out_tensor = torch.empty(N, 3 * N, device=device, dtype=torch.float32)
op = lambda: torch.cat((t1, t2, t3), dim=1, out=out_tensor) # noqa: E731
elif op_name == "where":
cond = torch.randint(0, 2, (N, N), device=device, dtype=torch.bool)
x = torch.randn(N, N, device=device, dtype=torch.float32)
y = torch.randn(N, N, device=device, dtype=torch.float32)
out_tensor = torch.empty_like(x)
op = lambda: torch.where(cond, x, y, out=out_tensor) # noqa: E731
elif op_name == "topk":
k = 4
x = torch.randn(N, N, device=device, dtype=torch.float32)
values = torch.empty(N, k, device=device, dtype=torch.float32)
indices = torch.empty(N, k, device=device, dtype=torch.long)
op = lambda: torch.topk(x, k, out=(values, indices)) # noqa: E731
else:
return None
# Warmup
for _ in range(warmup):
op()
if device.type == "cuda":
torch.cuda.synchronize()
# Benchmarking
if device.type == "cuda":
# GPU Timing (Asynchronous)
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()
for _ in range(num_repeats):
op()
end_event.record()
torch.cuda.synchronize()
total_ms = start_event.elapsed_time(end_event)
else:
# CPU Timing (Synchronous)
start_time = time.perf_counter()
for _ in range(num_repeats):
op()
end_time = time.perf_counter()
total_ms = (end_time - start_time) * 1000.0
return total_ms / num_repeats
def run_cpp_benchmark(executable_path, args):
"""
Runs the compiled executable with arguments.
Parameters:
- executable_path: Path to the compiled C++ executable.
- args: List of arguments to pass to the executable.
"""
if not os.path.exists(executable_path):
print(f"Error: Executable '{executable_path}' not found after build")
return
N = args[0]
try:
# Construct the command
cmd = [executable_path] + [str(a) for a in args]
# Run and capture output for parsing
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
output = result.stdout
kernel_match = re.search(r"TIME_KERNEL_MS:\s+(\d+\.?\d*)", output)
total_match = re.search(r"TIME_TOTAL_MS:\s+(\d+\.?\d*)", output)
if kernel_match and total_match:
return float(kernel_match.group(1)), float(total_match.group(1))
else:
print(f"Output parsing failed for size {N}x{N}.")
print("Printing raw output from the cpp executable")
print(output)
return None
except subprocess.CalledProcessError as e:
print(f"Execution failed with return code {e.returncode}")
print("Stderr:", e.stderr)
def main(gpu=False):
"""
Main function to build and run benchmarks.
1. Builds the kernel tests (CPU or GPU based on flag).
2. Runs benchmarks for each operation and size.
3. Compares C++ results with PyTorch if available.
Parameters:
- gpu: Boolean flag to indicate whether to benchmark GPU executables.
"""
if gpu:
print(f"\n{'Build System':^100}")
print("-" * 100)
# Build Phase
if not build_kernel_tests_gpu():
sys.exit(1)
# Benchmarking System
device_name = "CPU"
if HAS_TORCH and torch.cuda.is_available():
device_name = f"GPU ({torch.cuda.get_device_name(0)})"
print(f"\n{'Benchmarking System':^100}")
if HAS_TORCH:
print(f"{f'PyTorch Device: {device_name}':^100}")
print("-" * 100)
for EXECUTABLE_PATH in EXECUTABLE_PATHS_GPU:
op_name = get_op_name(EXECUTABLE_PATH)
print(f"Operation: {op_name.upper()}")
# Flexible Headers
# K = Kernel Time, T = Total Time
if HAS_TORCH:
header = (
f"{'SIZE':<6} | {'CUDA(K)':<9} | {'CUDA(T)':<9} | {'TORCH':<9} | "
f"{'CUDA GB/s':<9} | {'TORCH GB/s':<11} | {'SPEEDUP':<8}"
)
else:
header = f"{'SIZE':<6} | {'CUDA(K)':<10} | {'CUDA(T)':<10} | {'CUDA GB/s':<12}"
print(header)
print("-" * len(header))
for N in BENCHMARK_SIZES:
if HAS_TORCH and torch.cuda.is_available():
torch.cuda.empty_cache()
# 1. Run C++ Benchmark
cpp_res = run_cpp_benchmark(EXECUTABLE_PATH, [N])
if cpp_res:
cpp_k_ms, cpp_t_ms = cpp_res
else:
cpp_k_ms, cpp_t_ms = None, None
# 2. Run PyTorch Benchmark
torch_ms = run_pytorch_benchmark(op_name, N) if HAS_TORCH else None
# 3. Calculate Bandwidth (Using Kernel Time)
total_bytes = 0.0
if op_name == "trivial":
total_bytes = 8 * N * N
elif op_name == "transpose":
total_bytes = 8 * N * N
elif op_name == "concat":
total_bytes = 24 * N * N
elif op_name == "where":
total_bytes = 13 * N * N
elif op_name == "topk":
total_bytes = 4 * N * N + 16 * N
# GB/s = (Bytes/1e9) / (ms/1000)
cpp_bw = (
(total_bytes / 1e9) / (cpp_k_ms / 1000.0)
if (cpp_k_ms and cpp_k_ms > 0)
else 0.0
)
torch_bw = (
(total_bytes / 1e9) / (torch_ms / 1000.0)
if (torch_ms and torch_ms > 0)
else 0.0
)
# Formatting
c_k_str = f"{cpp_k_ms:.4f}" if cpp_k_ms else "ERR"
c_t_str = f"{cpp_t_ms:.4f}" if cpp_t_ms else "ERR"
c_bw_str = f"{cpp_bw:.2f}" if cpp_k_ms else "-"
if HAS_TORCH:
t_ms_str = f"{torch_ms:.4f}" if torch_ms else "ERR"
t_bw_str = f"{torch_bw:.2f}" if torch_ms else "-"
# Compare PyTorch Time vs C++ Kernel Time
speedup_str = "-"
if cpp_k_ms and torch_ms and cpp_k_ms > 0:
ratio = torch_ms / cpp_k_ms
speedup_str = f"{ratio:.2f}x"
print(
f"{N:<6} | {c_k_str:<9} | {c_t_str:<9} | {t_ms_str:<9} | "
f"{c_bw_str:<9} | {t_bw_str:<11} | {speedup_str:<8}"
)
else:
print(f"{N:<6} | {c_k_str:<10} | {c_t_str:<10} | {c_bw_str:<12}")
print("-" * len(header))
else:
# Build System
print(f"\n{'Build System':^100}")
print("-" * 100)
if not build_kernel_tests_cpu():
sys.exit(1)
# Benchmarking System
device_name = "CPU"
if HAS_TORCH and torch.cuda.is_available():
device_name = f"GPU ({torch.cuda.get_device_name(0)})"
print(f"\n{'Benchmarking System':^100}")
if HAS_TORCH:
print(f"{f'PyTorch Device: {device_name}':^100}")
print("-" * 100)
for EXECUTABLE_PATH in EXECUTABLE_PATHS_CPU:
op_name = get_op_name(EXECUTABLE_PATH)
print(f"Operation: {op_name.upper()}")
# Flexible Headers
# K = Kernel Time, T = Total Time
if HAS_TORCH:
header = (
f"{'SIZE':<6} | {'CPU(K)':<9} | {'CPU(T)':<9} | {'TORCH':<9} | "
f"{'CPU GB/s':<9} | {'TORCH GB/s':<11} | {'SPEEDUP':<8}"
)
else:
header = (
f"{'SIZE':<6} | {'CPU(K)':<10} | {'CPU(T)':<10} | {'CPU GB/s':<12}"
)
print(header)
print("-" * len(header))
for N in BENCHMARK_SIZES:
# 1. Run C++ Benchmark
cpp_res = run_cpp_benchmark(EXECUTABLE_PATH, [N])
if cpp_res:
cpp_k_ms, cpp_t_ms = cpp_res
else:
cpp_k_ms, cpp_t_ms = None, None
# 2. Run PyTorch Benchmark
torch_ms = run_pytorch_benchmark(op_name, N) if HAS_TORCH else None
# 3. Calculate Bandwidth (Using Kernel Time)
total_bytes = 0.0
if op_name == "trivial":
total_bytes = 8 * N * N
elif op_name == "transpose":
total_bytes = 8 * N * N
elif op_name == "concat":
total_bytes = 24 * N * N
elif op_name == "where":
total_bytes = 13 * N * N
elif op_name == "topk":
total_bytes = 4 * N * N + 16 * N
# GB/s = (Bytes/1e9) / (ms/1000)
cpp_bw = (
(total_bytes / 1e9) / (cpp_k_ms / 1000.0)
if (cpp_k_ms and cpp_k_ms > 0)
else 0.0
)
torch_bw = (
(total_bytes / 1e9) / (torch_ms / 1000.0)
if (torch_ms and torch_ms > 0)
else 0.0
)
# Formatting
c_k_str = f"{cpp_k_ms:.4f}" if cpp_k_ms else "ERR"
c_t_str = f"{cpp_t_ms:.4f}" if cpp_t_ms else "ERR"
c_bw_str = f"{cpp_bw:.2f}" if cpp_k_ms else "-"
if HAS_TORCH:
t_ms_str = f"{torch_ms:.4f}" if torch_ms else "ERR"
t_bw_str = f"{torch_bw:.2f}" if torch_ms else "-"
# Compare PyTorch Time vs C++ Kernel Time
speedup_str = "-"
if cpp_k_ms and torch_ms and cpp_k_ms > 0:
ratio = torch_ms / cpp_k_ms
speedup_str = f"{ratio:.2f}x"
print(
f"{N:<6} | {c_k_str:<9} | {c_t_str:<9} | {t_ms_str:<9} | "
f"{c_bw_str:<9} | {t_bw_str:<11} | {speedup_str:<8}"
)
else:
print(f"{N:<6} | {c_k_str:<10} | {c_t_str:<10} | {c_bw_str:<12}")
print("-" * len(header))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Benchmark runner")
parser.add_argument(
"--gpu",
help="Flag to indicate whether to benchmark GPU executables",
action="store_true",
)
args = parser.parse_args()
main(args.gpu)