-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_tests.py
1779 lines (1474 loc) · 73.9 KB
/
run_tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import pyopencl as cl
import pyopencl.array
import pyopencl.clrandom
import loopy as lp
from loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_2
from pyopencl.tools import ImmediateAllocator, MemoryPool
from frozendict import frozendict
from pebble import concurrent, ProcessExpired
from pebble.concurrent.process import _process_wrapper
from concurrent.futures import TimeoutError, BrokenExecutor
import multiprocessing as mp
import base64
from func_timeout import func_timeout, FunctionTimedOut
from multiprocessing import shared_memory
max_double = np.finfo('f').max
#from loopy.kernel.data import AddressSpace
"""
import pycuda.gpuarray as cuarray
import pycuda.driver as drv
import pycuda.tools
import pycuda.autoinit
from pycuda.compiler import SourceModule
from pycuda.curandom import rand as curand
"""
from modepy import equidistant_nodes
from pytools.obj_array import make_obj_array
import hjson
import time
#from math import ceil
import sys
# setup
# -----
lp.set_caching_enabled(False)
import loopy.options
loopy.options.ALLOW_TERMINAL_COLORS = False
from __init__ import (gen_diff_knl, gen_diff_knl_fortran2,
apply_transformation_list, gen_elwise_linear_knl, gen_face_mass_knl, gen_face_mass_knl_merged)
from grudge_tags import (IsDOFArray, IsSepVecDOFArray, IsOpArray,
IsSepVecOpArray, IsFaceDOFArray, IsFaceMassOpArray, IsVecDOFArray, IsVecOpArray, IsFourAxisDOFArray)
#import grudge.grudge_array_context as gac#import set_memory_layout
def testBandwidth(fp_format=np.float32, nruns=100):
from pyopencl.array import sum as clsum
platform = cl.get_platforms()
my_gpu_devices = platform[0].get_devices(device_type=cl.device_type.GPU)
#ctx = cl.Context(devices=my_gpu_devices)
ctx = cl.create_some_context(interactive=True)
queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
from pyopencl.tools import ImmediateAllocator, MemoryPool
allocator = ImmediateAllocator(queue)
mem_pool = MemoryPool(allocator)
knl = lp.make_copy_kernel("c,c", old_dim_tags="c,c")
knl = lp.add_dtypes(knl, {"input": fp_format, "output": fp_format})
#knl = knl.copy(target=lp.PyOpenCLTarget(my_gpu_devices[0]))
n0 = 2
#knl = lp.split_iname(knl, "i1", 1024//2, inner_tag="l.0", outer_tag="g.0", slabs=(0,1))
knl = lp.split_iname(knl, "i1", 256, inner_tag="l.0", outer_tag="g.0", slabs=(0,1))
#knl = lp.split_iname(knl, "i1", 6*16, outer_tag="g.0")
#knl = lp.split_iname(knl, "i1_inner", 16, outer_tag="ilp", inner_tag="l.0", slabs=(0,1))
#knl = lp.split_iname(knl, "i0", n0, inner_tag="l.1", outer_tag="g.1", slabs=(0,0))
fp_bytes = 8 if fp_format == np.float64 else 4
# This assumes fp32
len_list = []
float_count = 2
max_floats = 2**28
while float_count <= max_floats:
len_list.append(float_count)
float_count = int(np.ceil(float_count*1.5))
for i in range(1,29):
len_list.append(2**i)
len_list = sorted(list(set(len_list)))
#data = np.random.randint(-127, 128, (1,max_bytes), dtype=np.int8)
#inpt = cl.array.to_device(queue, data, allocator=mem_pool)
print(len_list)
for n in len_list:
#for i in range(29):
#n = 2**i
kern = lp.fix_parameters(knl, n0=n0, n1=n)
#data = np.random.randint(-127, 128, (1,n), dtype=np.int8)
#inpt = cl.array.to_device(queue, data, allocator=mem_pool)
inpt = cl.clrandom.rand(queue, (n0, n), dtype=fp_format)
outpt = cl.array.Array(queue, (n0, n), dtype=fp_format, allocator=mem_pool)
kern = lp.set_options(kern, "write_code") # Output code before editing it
for j in range(2):
kern(queue, input=inpt, output=outpt)
dt = 0
events = []
for j in range(nruns):
evt, _ = kern(queue, input=inpt, output=outpt)
events.append(evt)
cl.wait_for_events(events)
for evt in events:
dt += evt.profile.end - evt.profile.start
#queue.finish()
dt = dt / nruns / 1e9
nbytes_transferred = 2*fp_bytes*n*n0
bandwidth = nbytes_transferred / dt / 1e9
print("{} {}".format(nbytes_transferred, bandwidth))
#print((inpt - outpt))
#diff = (inpt - outpt)
#if clsum(inpt - outpt) != 0:
# print("INCORRECT COPY")
def test_face_mass_merged(kern, backend="OPENCL", nruns=10, warmup=True):
#kern = gen_diff_knl(n_elem, n_in, n_out, k_inner_outer, k_inner_inner,
# i_inner_outer, i_inner_inner, j_inner)
kern = lp.set_options(kern, "no_numpy")
kern = lp.set_options(kern, "return_dict")
for arg in kern.args:
if arg.name == "vec":
fp_format = arg.dtype
n_elem, n_in = arg.shape
elif arg.name == "mat":
n_out, _ = arg.shape
CUDA = (backend == "CUDA")
OPENCL = not CUDA
if CUDA:
print("Not supported")
exit()
elif OPENCL:
platform = cl.get_platforms()
my_gpu_devices = platform[0].get_devices(device_type=cl.device_type.GPU)
#ctx = cl.Context(devices=my_gpu_devices)
ctx = cl.create_some_context(interactive=True)
queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
#kern = lp.set_options(kern, edit_code=False) #Only works for OpenCL?
kern = lp.set_options(kern, "write_code") # Output code before editing it
# Print the Code
kern = kern.copy(target=lp.PyOpenCLTarget(my_gpu_devices[0]))
code = lp.generate_code_v2(kern).device_code()
prog = cl.Program(ctx, code)
prog = prog.build()
ptx = prog.get_info(cl.program_info.BINARIES)[0]#.decode(
#errors="ignore") #Breaks pocl
from bs4 import UnicodeDammit
dammit = UnicodeDammit(ptx)
#print(dammit.unicode_markup)
f = open("ptx.ptx", "w")
f.write(dammit.unicode_markup)
f.close()
from pyopencl.tools import ImmediateAllocator, MemoryPool
allocator = ImmediateAllocator(queue)
mem_pool = MemoryPool(allocator)
X_dev = cl.array.Array(queue, (n_elem, n_in), dtype=fp_format, order="F", allocator=mem_pool)
cl.clrandom.fill_rand(X_dev, queue=queue)
B_dev = cl.array.Array(queue, (n_elem, n_out), dtype=fp_format, allocator=mem_pool,order="F")
A_dev = cl.clrandom.rand(queue, (n_out, n_in), dtype=fp_format)
if warmup:
for i in range(2):
kern(queue, result=B_dev, mat=A_dev, vec=X_dev)
queue.finish()
sum_time = 0.0
events = []
for i in range(nruns):
evt, _ = kern(queue, result=B_dev, mat=A_dev, vec=X_dev)
events.append(evt)
cl.wait_for_events(events)
for evt in events:
sum_time += evt.profile.end - evt.profile.start
sum_time = sum_time / 1e9
#queue.finish()
avg_time = sum_time / nruns
return (B_dev, A_dev, X_dev), avg_time
def measure_execution_time(queue, tunit, arg_dict, nruns, warmup_runs):
print("Warming up")
#print(tunit)
#exit()
for i in range(warmup_runs):
tunit(queue, **arg_dict)
#queue.finish()
sum_time = 0.0
events = []
# Should the cache be polluted between runs?
print("Executing")
for i in range(nruns):
evt, out = tunit(queue, **arg_dict)
events.append(evt)
cl.wait_for_events(events)
for evt in events:
sum_time += evt.profile.end - evt.profile.start
avg_time = sum_time / 1e9 / nruns
return avg_time
# Strips out instructions and executes kernel to see how long the
# argument setting, etc, requires. This assumes there is only
# one kernel or function in the generated code
def measure_execution_latency(queue, tunit, arg_dict, nruns, warmup_runs):
args = arg_dict.items()
arg_names = [entry[0] for entry in args]
arg_vals = [entry[1].data for entry in args]
otunit = lp.set_argument_order(tunit, arg_names)
code = lp.generate_code_v2(otunit).device_code()
#print(code)
#exit()
# This isn't generally true actually. Some kernels define helper functions within them.
null_kernel_code = code.split("{")[0] + "{}"
search_str = "reqd_work_group_size("
start_ind = null_kernel_code.index(search_str) + len(search_str)
sub_str = null_kernel_code[start_ind:].split(",")
lwork_size = []
for i in range(3):
lwork_size.append(np.int32(sub_str[i].split(")")[0].replace(" ", "")))
print(null_kernel_code)
print(lwork_size)
program = cl.Program(queue.context, null_kernel_code).build()
cl_knl = program.all_kernels()[0]
#nargs = cl_knl.num_args
#name_to_ind = {cl_knl.get_arg_info(ind, cl.kernel_arg_info.NAME): ind for ind in range(nargs)}
cl_knl.set_args(*arg_vals)
#for key, val in arg_dict.items():
# ind = name_to_ind[key]
# cl_knl.set_arg(ind, val)
for i in range(warmup_runs):
cl.enqueue_nd_range_kernel(queue, cl_knl, lwork_size, lwork_size)
events = []
for i in range(warmup_runs):
events.append(cl.enqueue_nd_range_kernel(queue, cl_knl, lwork_size, lwork_size))
cl.wait_for_events(events)
sum_time = 0.0
min_latency = np.inf
for evt in events:
lat_val = evt.profile.end - evt.profile.start
sum_time += lat_val
if lat_val < min_latency:
min_latency = lat_val
min_latency = min_latency / 1e9
avg_latency = sum_time / 1e9 / nruns
return min_latency
# Maybe the queue could also be a cuda stream? Could use the type of that to
# distinguish between CUDA and OpenCL possibly
# This hardcodes the memory layout, should probably instead retrieve it from somewhere on a per
# tag basis
#cache_arg_dict = {}
def generic_test(queue, kern, backend="OPENCL", nruns=10, warmup_runs=2):
kern = lp.set_options(kern, "no_numpy")
kern = lp.set_options(kern, "return_dict")
CUDA = (backend == "CUDA")
OPENCL = not CUDA
if CUDA:
print("CUDA not supported")
exit()
elif OPENCL:
"""
platform = cl.get_platforms()
my_gpu_devices = platform[0].get_devices(device_type=cl.device_type.GPU)
ctx = cl.Context(devices=my_gpu_devices)
#ctx = cl.create_some_context(interactive=True)
#queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
#kern = lp.set_options(kern, edit_code=False) #Only works for OpenCL?
kern = lp.set_options(kern, "write_code") # Output code before editing it
# Print the Code
kern = kern.copy(target=lp.PyOpenCLTarget(my_gpu_devices[0]))
code = lp.generate_code_v2(kern).device_code()
prog = cl.Program(ctx, code)
prog = prog.build()
ptx = prog.get_info(cl.program_info.BINARIES)[0]#.decode(
#errors="ignore") #Breaks pocl
dammit = UnicodeDammit(ptx)
print(dammit.unicode_markup)
f = open("ptx.ptx", "w")
f.write(dammit.unicode_markup)
f.close()
"""
print("STARTING ALLOCATION")
start = time.time()
allocator = ImmediateAllocator(queue)
mem_pool = MemoryPool(allocator)
arg_dict = {}
# Fill arrays with random data
# Could probably just read the strides from the kernel to get ordering
for arg in kern.default_entrypoint.args:
if True:#str(arg) not in cache_arg_dict:
#print(arg)
fp_bytes = arg.dtype.numpy_dtype.itemsize
if IsDOFArray() in arg.tags:
array = cl.array.Array(queue, arg.shape, arg.dtype, order="F", allocator=mem_pool)
#if not arg.is_output:
# cl.clrandom.fill_rand(array, queue)
elif IsSepVecDOFArray() in arg.tags:
#if arg.is_output:
obj_array = [cl.array.Array(queue, arg.shape[1:], dtype=arg.dtype, allocator=mem_pool, order="F") for i in range(arg.shape[0])]
array = make_obj_array(obj_array)
#else:
# print("Input SepVecDOFArrays are not currently supported")
# exit()
elif IsFaceDOFArray() in arg.tags:
#fp_bytes = arg.dtype.numpy_dtype.itemsize
nfaces, nelements, nface_nodes = arg.shape
strides = (fp_bytes*nelements, fp_bytes*1, fp_bytes*nelements*nfaces) #original
array = cl.array.Array(queue, arg.shape, dtype=arg.dtype,
strides=strides, allocator=mem_pool)
#cl.clrandom.fill_rand(array, queue=queue)
elif IsVecDOFArray() in arg.tags:
#fp_bytes = arg.dtype.numpy_dtype.itemsize
nr, nelements, ndofs = arg.shape
strides = (fp_bytes*nelements*ndofs, fp_bytes, fp_bytes*nelements) #original
array = cl.array.Array(queue, arg.shape, dtype=arg.dtype,
strides=strides, allocator=mem_pool)
#cl.clrandom.fill_rand(array, queue=queue)
elif IsFourAxisDOFArray() in arg.tags:
#fp_bytes = arg.dtype.numpy_dtype.itemsize
nx, nr, nelements, ndofs = arg.shape
strides = (fp_bytes*nelements*ndofs*nr, fp_bytes*nelements*ndofs,
fp_bytes, fp_bytes*nelements)
array = cl.array.Array(queue, arg.shape, dtype=arg.dtype,
strides=strides, allocator=mem_pool)
#cl.clrandom.fill_rand(array, queue=queue)
elif IsSepVecOpArray() in arg.tags:
#obj_array = [cl.clrandom.rand(queue, arg.shape[1:], dtype=arg.dtype) for i in range(arg.shape[0])]
obj_array = [cl.array.Array(queue, arg.shape[1:], dtype=arg.dtype, order="C", allocator=mem_pool) for i in range(arg.shape[0])]
#if not arg.is_output:
# cl.clrandom.fill_rand(arg_dict[arg.name], queue)
#obj_array = []
#for i in range(arg.shape[0]):
#clarray = cl.array.Array(queue, arg.shape[1:], arg.dtype, order="C", allocator=mem_pool)
#cl.clrandom.fill_rand(clarray, queue=queue)
#obj_array.append(clarray)
array = make_obj_array(obj_array)
#elif IsFaceMassOpArray() in arg.tags:
# Are these strides correct?
#array = cl.clrandom.rand(queue, arg.shape, dtype=arg.dtype)
elif IsOpArray() in arg.tags or IsVecOpArray() in arg.tags or IsFaceMassOpArray in arg.tags:
array = cl.array.Array(queue, arg.shape, arg.dtype, order="C", allocator=mem_pool)
#cl.clrandom.fill_rand(array, queue=queue)
#array = cl.clrandom.rand(queue, arg.shape, dtype=arg.dtype)
elif isinstance(arg, lp.ArrayArg):
array = cl.array.Array(queue, arg.shape, arg.dtype, order="C", allocator=mem_pool)
#cl.clrandom.fill_rand(array, queue=queue)
print(arg.name, "No tags recognized. Assuming default data layout")
# Assume default layout
#array = cl.clrandom.rand(queue, arg.shape, dtype=arg.dtype)
if not arg.is_output:
if isinstance(array, cl.array.Array):
try:
cl.clrandom.fill_rand(array, queue=queue)
except TypeError:
print("clrandom cannot fill array of this dtype")
elif isinstance(array[0], cl.array.Array):
for entry in array:
cl.clrandom.fill_rand(entry, queue=queue)
else:
raise TypeError
#cache_arg_dict[str(arg)] = array
#print(arg.name)
#print(arg.tags)
#print("Unknown Tag")
#exit()
#arg_dict[arg.name] = cache_arg_dict[str(arg)]
arg_dict[arg.name] = array
end = time.time()
print("ENDING ALLOCATION", end - start, "seconds" )
print("STARTING EXECUTION")
start = time.time()
print("Setting execution latency to zero")
measured_latency = 0#measure_execution_latency(queue, kern, arg_dict, nruns, warmup_runs)
avg_time = measure_execution_time(queue, kern, arg_dict, nruns, warmup_runs)
end = time.time()
print("FINISHING EXECUTION", end - start, "seconds")
#queue.finish()
#sum_time = 1.0
return arg_dict, avg_time, measured_latency
def get_knl_device_memory_bytes(knl):
nbytes = 0
# What if the output is not in the input arguments?
#print(knl.default_entrypoint.args)
# Would probably be better to use the memory footprint
# if can get it to work.
args_and_temps = knl.default_entrypoint.args + list(knl.default_entrypoint.temporary_variables.values())
for arg in args_and_temps:
if arg.address_space == lp.AddressSpace.GLOBAL:
#print(arg.name)
#print(arg.shape)
#print(type(arg.dtype))
nbytes += np.prod((arg.shape))*arg.dtype.dtype.itemsize
return nbytes
# avg_time in seconds
def analyze_knl_bandwidth(knl, avg_time, device_latency=None):
# This bandwidth calculation assumes data in global memory need only be accessed once
# from global memory and is otherwise served from a cache or local memory that is
# fast enough to be considered free
if device_latency is None:
device_latency = 0
nbytes = get_knl_device_memory_bytes(knl)
bw = nbytes / (avg_time - device_latency)
# Seems lp.gather_access_footprint_bytes breaks
#footprint = lp.gather_access_footprint_bytes(knl)
#footprint_bytes = 0
#for val in footprint.values():
# footprint_bytes += val.eval_with_dict({})
#footprint_bw = footprint_bytes / avg_time / 1e9
#print(f"Time: {avg_time}, Bytes: {nbytes}, Bandwidth: {bw} GB/s Footprint BW: {footprint_bw} GB/s")
Gbps = bw*1e-9
print(f"Time: {avg_time}, Bytes: {nbytes}, Bandwidth: {Gbps} GB/s")
return frozendict({"observed_bandwidth": bw,
"nbytes_global": nbytes,
"device_latency": device_latency})
def get_knl_flops(knl):
op_map = lp.get_op_map(knl, count_within_subscripts=False, subgroup_size=1)
map_flops = 0
for val in op_map.values():
map_flops += val.eval_with_dict({})
return map_flops
# Avg time in seconds, max_flop_rate in flops per second
def analyze_flop_rate(knl, avg_time, max_flop_rate=None, latency=None):
map_flops = get_knl_flops(knl)
flop_rate = map_flops / avg_time
if latency is None:
latency = 0
"""
n_mat = 1
nfaces = 1
for arg in knl.default_entrypoint.args:
if IsDOFArray() in arg.tags:
n_elem, n_out = arg.shape
fp_bytes = arg.dtype.dtype.itemsize
elif IsSepVecOpArray() in arg.tags or IsVecOpArray() in arg.tags:
n_mat, n_out, n_in = arg.shape
elif IsOpArray() in arg.tags:
n_out, n_in = arg.shape
elif IsFaceDOFArray() in arg.tags:
nfaces, n_elem, n_in = arg.shape
flops = nfaces*n_mat*2*(n_out * n_in * n_elem)
"""
assert latency >= 0
assert avg_time - latency > 0
# Subtract memory latency from flop_rate if known
flop_rate = map_flops / (avg_time - latency)
print("GFLOP/s: " + str(flop_rate*1e-9))
#print("Map GFLOP/s: " + str(map_gflop_rate))
#print(flops)
#print(map_flops)
"""
frac_peak_gflops = None
if max_gflops is not None:
print("Peak GFLOP/s: " + str(max_gflops))
frac_peak_gflops = gflop_rate / max_gflops
print("Percent peak: " + str(100*(frac_peak_gflops)))
"""
# Calculate bandwidth
# Assumes each element only read once
#ideal_total_bytes_transferred = fp_bytes*(3*(n_out * n_elem) + (n_in * n_elem)
# + 3*(n_out * n_in))
#GBps = (ideal_total_bytes_transferred / avg_time) / 1e9
#frac_peak_GBps = GBps / device_memory_bandwidth
#print("GB/s: " + str(GBps))
#print("Peak GB/s: " + str(device_memory_bandwidth))
#print("Percent peak: " + str(100*(frac_peak_GBps)))
#print()
return frozendict({"observed_flop_rate": flop_rate, "flops": map_flops})#gflop_rate, frac_peak_gflops
def get_knl_device_memory_roofline(knl, max_flop_rate, device_latency, device_memory_bandwidth):
device_memory_bytes = get_knl_device_memory_bytes(knl)
flops_per_byte = get_knl_flops(knl) / device_memory_bytes
effective_bandwidth = device_memory_bytes / (device_latency + device_memory_bytes / device_memory_bandwidth)
roofline_flop_rate = min(flops_per_byte*effective_bandwidth, max_flop_rate)
return roofline_flop_rate
def verifyResult(B_dev1, B_dev2, B_dev3, A_dev1, A_dev2, A_dev3, X_dev):
A_host1 = A_dev1.get()
A_host2 = A_dev2.get()
A_host3 = A_dev3.get()
X_host = X_dev.get()
B_host1 = B_dev1.get()
B_host2 = B_dev2.get()
B_host3 = B_dev3.get()
np.set_printoptions(threshold=sys.maxsize)
errMat = ((A_host1 @ X_host) - B_host1) / np.linalg.norm(A_host1 @ X_host)
print("Fraction Nonzero: " + str(np.count_nonzero(errMat)/(n_out*n_elem)))
print("Norm1: " + str(np.linalg.norm((A_host1 @ X_host) - B_host1)
/ np.linalg.norm(A_host1 @ X_host)))
print("Norm2: " + str(np.linalg.norm((A_host2 @ X_host) - B_host2)
/ np.linalg.norm(A_host2 @ X_host)))
print("Norm3: " + str(np.linalg.norm((A_host3 @ X_host) - B_host3)
/ np.linalg.norm(A_host3 @ X_host)))
def verifyResultFortran(B_dev1, B_dev2, B_dev3, A_dev1, A_dev2, A_dev3, X_dev):
A_host1 = A_dev1.get()
A_host2 = A_dev2.get()
A_host3 = A_dev3.get()
X_host = X_dev.get().T
B_host1 = B_dev1.get()
B_host2 = B_dev2.get()
B_host3 = B_dev3.get()
np.set_printoptions(threshold=sys.maxsize)
errMat = ((A_host1 @ X_host).T - B_host1) / np.linalg.norm(A_host1 @ X_host)
print("Fraction Nonzero: " + str(np.count_nonzero(errMat)/(n_out*n_elem)))
print("Norm1: " + str(np.linalg.norm((A_host1 @ X_host).T - B_host1)
/ np.linalg.norm(A_host1 @ X_host)))
print("Norm2: " + str(np.linalg.norm((A_host2 @ X_host).T - B_host2)
/ np.linalg.norm(A_host2 @ X_host)))
print("Norm3: " + str(np.linalg.norm((A_host3 @ X_host).T - B_host3)
/ np.linalg.norm(A_host3 @ X_host)))
# This can be removed eventually
def apply_transformations_and_run_test(queue, knl, test_fn, params, tgenerator, max_gflops=None,
device_memory_bandwidth=None, gflops_cutoff=0.95, bandwidth_cutoff=0.95, start_param=None):
kio, kii, iio, iii, ji = params
# Transform and run
#knl = gac.set_memory_layout(knl)
if applicator is not None:
trans_list = tgenerator(params)
else:
# Should probably read in eligible transformations from a file instead of using if-statements
trans_list = []
if "diff" in knl.default_entrypoint.name:
trans_list.append(["tag_inames", ["imatrix: ilp"]])
trans_list.append(["split_iname", ["iel", kio], {"outer_tag": "g.0", "slabs":(0,1)}])
trans_list.append(["split_iname", ["iel_inner", kii],
{"outer_tag": "ilp", "inner_tag":"l.0", "slabs":(0,1)}])
trans_list.append(["split_iname", ["idof", iio], {"outer_tag": "g.1", "slabs":(0,0)}])
trans_list.append(["split_iname", ["idof_inner", iii],
{"outer_tag": "ilp", "inner_tag":"l.1", "slabs":(0,1)}])
if knl.default_entrypoint.name == "face_mass":
pass
#trans_list.append(["add_prefetch", ["vec", "f,j,iel_inner_outer,iel_inner_inner"],
# {"temporary_name":"vecf", "default_tag":"l.auto"}])
#trans_list.append(["tag_array_axes", ["vecf", "N1,N0,N2"]])
elif knl.default_entrypoint.name == "nodes":
trans_list.append(["add_prefetch", ["nodes", "j,iel_inner_outer,iel_inner_inner"],
{"temporary_name":"vecf", "default_tag":"l.auto"}])
trans_list.append(["tag_array_axes", ["vecf", "f,f"]])
elif "resample_by_mat" in knl.default_entrypoint.name:
# Indirection may prevent prefetching
pass
else:
trans_list.append(["add_prefetch", ["vec", "j,iel_inner_outer,iel_inner_inner"],
{"temporary_name":"vecf", "default_tag":"l.auto"}])
trans_list.append(["tag_array_axes", ["vecf", "f,f"]])
trans_list.append(["split_iname", ["j", ji], {"outer_tag":"for", "inner_tag":"for"}])
trans_list.append(["add_inames_for_unused_hw_axes"])
knl = apply_transformation_list(knl, trans_list)
#print(knl.default_entrypoint.name)
#print(trans_list)
# Execute and analyze the results
dev_arrays, avg_time = test_fn(queue, knl)
#avg_time = np.random.rand()
return avg_time, trans_list
"""
# The analysis should be done elsewhere
bw = None
flop_rate = None
if device_memory_bandwidth is not None: # noqa
bw = analyze_knl_bandwidth(knl, avg_time)
frac_peak_GBps = bw / device_memory_bandwidth
if frac_peak_GBps >= bandwidth_cutoff: # noqa
# Should validate result here
print("Performance is within tolerance of peak bandwith. Terminating search") # noqa
return avg_time, params
# Einsum complicates this. This depends on the kernel being called.
if max_gflops is not None:
frac_peak_gflops = analyze_FLOPS(knl, max_gflops, avg_time)
if frac_peak_gflops >= gflops_cutoff:
# Should validate result here
print("Performance is within tolerance of peak bandwith or flop rate. Terminating search") # noqa
return choices
if device_memory_bandwidth is not None and max_gflops is not None:
data = (avg_time,
frac_peak_GBps*device_memory_bandwidth,
frac_peak_gflops*max_gflops,
frac_peak_GBps,
frac_peak_gflops,
(kio, kii, iio, iii, ji))
result_list.append(data)
f.write(str(data) + "\n")
if avg_time < avg_time_saved:
avg_time_saved = avg_time
result_saved = choices
result_saved_list = trans_list
if time.time() - start > time_limit:
result_list.sort()
print("Avg_time, Peak_BW, Peak_GFLOPS, Frac_peak_bandwidth, Frac_peak_GFlops")
for entry in result_list:
print(entry)
print()
#return result_saved_list
return result_saved
"""
def run_single_param_set(queue, knl_base, tlist_generator, params, test_fn, max_gflops=None, device_memory_bandwidth=None):
trans_list = tlist_generator(params, knl=knl_base)
knl = apply_transformation_list(knl_base, trans_list)
dev_arrays, avg_time = test_fn(queue, knl)
# Should this return the fraction of peak of should that be calculated in this function?
gflops, frac_peak_gflops = analyze_FLOPS(knl, avg_time, max_gflops=max_gflops)
bw = analyze_knl_bandwidth(knl, avg_time)
if device_memory_bandwidth is not None: # noqa
#bw = analyze_knl_bandwidth(knl, avg_time)
frac_peak_GBps = bw / device_memory_bandwidth
if frac_peak_GBps >= bandwidth_cutoff: # noqa
# Should validate result here
print("Performance is within tolerance of peak bandwith. Terminating search") # noqa
return choices
# This is incorrect for general einsum kernels
if max_gflops is not None:
frac_peak_gflops = gflops / max_gflops#analyze_FLOPS(knl, max_gflops, avg_time)
if frac_peak_gflops >= gflops_cutoff:
# Should validate result here
print("Performance is within tolerance of peak bandwith or flop rate. Terminating search") # noqa
return choices
data = {"avg_time": avg_time, "observed_GBps": bw, "observed_gflop_rate": gflops}
if device_memory_bandwidth is not None and max_gflops is not None:
data.update({"max_gflops": max_gflops,
"device_memory_GBps": device_memory_bandwidth,
"frac_peak_GBps": frac_peak_GBps,
"frac_peak_gflops": frac_peak_gflops
})
retval = {"transformations": trans_list, "data": data}
return retval
# Useful elsewhere. Maybe move to utils or as a utility function in pyopencl
def get_queue_from_bus_id(bus_id):
for platform in cl.get_platforms():
for d in platform.get_devices():
if "NVIDIA" in d.vendor:
d_bus_id = d.pci_bus_id_nv
elif "Advanced Micro Devices" in d.vendor:
d_bus_id = d.topology_amd.bus
else:
d_bus_id = None
if d_bus_id == bus_id:
ctx = cl.Context(devices=[d])
my_queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
return my_queue
raise RuntimeError(f"No device with bus_id {bus_id} found")
# Useful elsewhere. Maybe move to utils or as a utility function in pyopencl
def get_bus_id_from_queue(queue):
d = queue.device
if "NVIDIA" in d.vendor:
d_bus_id = d.pci_bus_id_nv
elif "Advanced Micro Devices" in d.vendor:
d_bus_id = d.topology_amd.bus
else:
raise RuntimeError("Can't query bus id")
return d_bus_id
def run_subprocess_with_timeout(queue, knl, test_fn, timeout=None):
import os
import uuid
from pickle import dump, dumps
from subprocess import run, TimeoutExpired, CalledProcessError, Popen, PIPE, STDOUT
#pickled_knl = base64.b85encode(dumps(knl)).decode('ASCII')
#pickled_test_fn = base64.b85encode(dumps(test_fn)).decode('ASCII')
bus_id = get_bus_id_from_queue(queue)
#filename = str(uuid.uuid4()) + ".tmp"
#out_file = open(filename, "wb")
#dump(tuple([knl, test_fn, bus_id]), out_file)
#out_file.close()
pickled_data = dumps([knl, test_fn, bus_id])
shm = shared_memory.SharedMemory(create=True, size=len(pickled_data))
shm.buf[:] = pickled_data[:]
#unpickle_and_run_test(filename)
start = time.time()
proc = Popen(["python", "run_tests.py", shm.name], stdout=PIPE, stderr=STDOUT, text=True)
shm.close()
#proc = Popen(["python", "run_tests.py", filename], stdout=PIPE, stderr=STDOUT, text=True)
try:
output, err = proc.communicate(timeout=timeout)
if proc.returncode != 0:
raise CalledProcessError(proc.returncode, proc.args, output=output)
split_output = output.split("|")
end = time.time()
retval = float(split_output[-3]), float(split_output[-1]), end - start
except TimeoutExpired:
print("Subprocess timed out")
proc.kill()
#with proc:
# proc.kill()
retval = max_double, None, 0
#out, err = proc.communicate()
#try:
# start = time.time()
# #completed = run(["python", "run_tests.py", str(bus_id), pickled_knl, pickled_test_fn],
# # capture_output=True, check=True, timeout=timeout, text=True)
# end = time.time()
# output = completed.stdout
# split_output = output.split("|")
# return float(split_output[-3]), float(split_output[-1]), end - start
#except TimeoutExpired as e:
# print("Subprocess timed out")
# return max_double, max_double, 0
except CalledProcessError as e:
print("Subprocess failed with the following output:")
print(e.output)
#os.remove(filename)
proc.kill()
retval = max_double, None, 0
exit()
#os.remove(filename)
return retval
def unpickle_and_run_test(sh_mem_name):
from pickle import loads
sh_mem = shared_memory.SharedMemory(sh_mem_name)
knl, test_fn, bus_id = loads(sh_mem.buf)
sh_mem.close()
sh_mem.unlink()
#in_file = open(filename, "rb")
#knl, test_fn, bus_id = load(in_file)
#in_file.close()
#knl = loads(base64.b85decode(pickled_knl.encode('ASCII')))
#test_fn = loads(base64.b85decode(pickled_test_fn.encode('ASCII')))
queue = get_queue_from_bus_id(int(bus_id))
dev_arrays, avg_time, measured_latency = test_fn(queue, knl)
print("|Average execution time|", avg_time, "|Average execution latency|", measured_latency)
"""
def unpickle_and_run_test(filename):
from pickle import load
in_file = open(filename, "rb")
knl, test_fn, bus_id = load(in_file)
in_file.close()
#knl = loads(base64.b85decode(pickled_knl.encode('ASCII')))
#test_fn = loads(base64.b85decode(pickled_test_fn.encode('ASCII')))
queue = get_queue_from_bus_id(int(bus_id))
dev_arrays, avg_time, measured_latency = test_fn(queue, knl)
print("|Average execution time|", avg_time, "|Average execution latency|", measured_latency)
"""
# Need to change the timeout so can't use this decorate (and can't decorating
# a function while using 'spawn' is not support inside another function)
#@concurrent.process(context=mp.get_context('spawn'), timeout=autotune_timeout)
def test_fn_wrapper(bus_id, knl, test_fn):
queue = get_queue_from_bus_id(bus_id)
dev_arrays, avg_time, measured_latency = test_fn(queue,knl)
return avg_time, measured_latency
#mp_context = mp.get_context('spawn')
mp_context = mp.get_context('forkserver')
def run_concurrent_test_with_timeout(queue, knl, test_fn, timeout=None, method="threadpool"):
# Cuda initialization fails with fork, but spawn and forkserver may also not play well with mpi
bus_id = get_bus_id_from_queue(queue)
if method == "pebble":
wrapped_fn = _process_wrapper(test_fn_wrapper, timeout, None, None, mp_context)
future = wrapped_fn(bus_id, knl, test_fn)
executor = None
else:
if method == "processpool":
from concurrent.futures import ProcessPoolExecutor as Executor
executor = Executor(max_workers=1, mp_context=mp_context)
else:
from concurrent.futures import ThreadPoolExecutor as Executor
executor = Executor(max_workers=1)
future = executor.submit(test_fn_wrapper, bus_id, knl, test_fn)
start = time.time()
try:
avg_time, measured_latency = future.result(timeout=timeout)
except TimeoutError as error:
print("Test function timed out. Time limit %f seconds. Returning null result" % float(error.args[1]))
avg_time, measured_latency = max_double, 0
except BrokenExecutor as error:
print("Executor broke. This may be due to the GPU code crashing the process.")
print(error)
avg_time, measured_latency = max_double, 0
except ProcessExpired as error:
print("%s. Exit code: %d" % (error, error.exitcode))
avg_time, measured_latency = max_double, 0
except Exception as error:
print("Test function raised %s" % error)
print(error.traceback) # traceback of the function
end = time.time()
if executor is not None:
executor.shutdown(wait=True, cancel_futures=True)
wall_clock_time = end - start if avg_time != max_double else max_double
return avg_time, measured_latency, wall_clock_time
def run_single_param_set_v2(queue, knl_base, trans_list, test_fn, max_flop_rate=np.inf, device_memory_bandwidth=np.inf, device_latency=0, timeout=None, method=None):#, method="thread"):
# Timeout won't prevent applying transformations from hanging
print("PRINTING 1")
print(knl_base)
print("BEGINNING KERNEL TRANSFORMATION")
transformed = True
if True:
knl = apply_transformation_list(knl_base, trans_list)
else:
try:
start = time.time()
#import pdb; pdb.set_trace()
knl = func_timeout(timeout, apply_transformation_list, args=(knl_base, trans_list,))
#knl = apply_transformation_list(knl_base, trans_list)
end = time.time()
print("Transformation required", end - start, "seconds")
#exit()
except FunctionTimedOut as e:
print("Transformation timed out")
transformed = False
knl = knl_base
print("PRINTING 2")
print(knl)
exit()
local_sizes = set()
for trans in trans_list:
if trans[0] == "split_iname" and "inner" in trans[1][0]:
local_sizes |= {trans[1][1]}
print(local_sizes)
assert len(local_sizes) <= 2
workitems = np.product(list(local_sizes))
# AMD does something weird with max_work_group_size so using
# max_work_item_sizes[0] here instead
max_work_group_size = queue.device.max_work_item_sizes[0]
temp_dict = {key: val for key, val in knl.default_entrypoint.temporary_variables.items() if val.address_space == lp.AddressSpace.LOCAL or val.address_space == lp.auto}
base_storage_dict = {}
for temp, tarray in temp_dict.items():
if tarray.base_storage not in base_storage_dict:
base_storage_dict[tarray.base_storage] = np.product(tarray.shape)*tarray.dtype.dtype.itemsize
elif np.product(tarray.shape) > base_storage_dict[tarray.base_storage]:
base_storage_dict[tarray.base_storage] = np.product(tarray.shape)*tarray.dtype.dtype.itemsize
local_memory_used = np.sum(list(base_storage_dict.values()))
local_memory_avail = queue.device.local_mem_size
print(f"KERNEL USING {local_memory_used} out of {local_memory_avail} bytes of local memory")
# Could also look at the amount of cache space used and forbid running those that spill
print("BEGINNING KERNEL EXECUTION")
measured_latency = None
if local_memory_used <= queue.device.local_mem_size and workitems <= max_work_group_size and transformed: # Don't allow complete filling of local memory
# Should check what the performance difference is between None, subprocess, and thread
if method is None:
start = time.time()
_, avg_time, measured_latency = test_fn(queue, knl)
end = time.time()
wall_clock_time = end - start
elif method == "subprocess":
print("Executing test with timeout of", timeout, "seconds")
avg_time, measured_latency, wall_clock_time = run_subprocess_with_timeout(queue, knl, test_fn, timeout=timeout)
elif method == "thread":
# Concurrent futures with threads should do the same thing
try:
start = time.time()
_, avg_time, measured_latency = func_timeout(timeout, test_fn, args=(queue, knl,))
end = time.time()
wall_clock_time = end - start
except FunctionTimedOut as e:
print("Execution timed out")
avg_time, wall_clock_time = max_double, max_double # Don't run and return return an infinite run time
else: # processpool and pebble concurrent processes will break with MPI, use subprocess instead
avg_time, measured_latency, wall_clock_time = run_concurrent_test_with_timeout(queue, knl, test_fn, timeout=timeout, method=method)
else:
print("Invalid kernel: too much local memory used")
avg_time, wall_clock_time = max_double, max_double # Don't run and return return an infinite run time