-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
1628 lines (1327 loc) · 63.1 KB
/
__init__.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
from pytools import memoize_in
from meshmode.array_context import EinsumTag
from decouple_domain import decouple_domain
from utils import get_domain_list
#import pyopencl as cl
#import pyopencl.array
#import pyopencl.clrandom
import loopy as lp
from grudge_tags import IsDOFArray, ParameterValue
#from loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_2
#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 bs4 import UnicodeDammit
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
# A lot of this could probably be deleted
def gen_face_mass_knl_merged(nelements, nfaces, nvol_nodes, nface_nodes, fp_format):
knl = lp.make_kernel(
"""{[iel,idof,fj]:
0<=iel<nelements and
0<=idof<nvol_nodes and
0<=fj<nf_times_j}""",
"""
result[iel,idof] = sum(fj, mat[idof, fj] * vec[iel, fj])
""",
kernel_data=[
lp.GlobalArg("result", fp_format, shape=lp.auto, order="F"),
lp.GlobalArg("vec", fp_format, shape=lp.auto, order="F"),
lp.GlobalArg("mat", fp_format, shape=lp.auto, order="C"),
"..."
],
name="face_mass")
# Gets around 470 GB/s
knl = lp.fix_parameters(knl, nelements=nelements, nf_times_j=nfaces*nface_nodes, nvol_nodes=nvol_nodes)
#knl = lp.tag_array_axes(knl, "result", "f,f")
#knl = lp.tag_array_axes(knl, "vec", "f,f")
knl = lp.split_iname(knl, "iel", 96, outer_tag="g.0", slabs=(0,1))
knl = lp.split_iname(knl, "iel_inner", 32, outer_tag="ilp", inner_tag="l.0", slabs=(0,1))
knl = lp.add_prefetch(knl, "vec", "iel_inner_outer,iel_inner_inner,fj",
temporary_name="vecf", default_tag="l.auto")
knl = lp.tag_array_axes(knl, "vecf", "f,f")
knl = lp.split_iname(knl, "idof", 20, outer_tag="g.1", slabs=(0,0))
knl = lp.split_iname(knl, "idof_inner", 2, outer_tag="ilp", inner_tag="l.1", slabs=(0,0))
knl = lp.split_iname(knl, "fj", 10, slabs=(0,0), inner_tag="unr")
return knl
def gen_face_mass_knl(nelements, nfaces, nvol_nodes, nface_nodes, fp_format):
knl = lp.make_kernel(
"""{[iel,idof,f,j]:
0<=iel<nelements and
0<=f<nfaces and
0<=idof<nvol_nodes and
0<=j<nface_nodes}""",
"""
#result[iel,idof] = sum(fj, mat[idof, fj] * vec[iel, fj])
result[iel,idof] = sum(f, sum(j, mat[idof, f, j] * vec[f, iel, j]))
""",
kernel_data=[
lp.GlobalArg("result", fp_format, shape=lp.auto),
lp.GlobalArg("vec", fp_format, shape=lp.auto),
lp.GlobalArg("mat", fp_format, shape=lp.auto),
"..."
],
name="face_mass")
knl = lp.fix_parameters(knl, nelements=nelements, nfaces=nfaces, nvol_nodes=nvol_nodes, nface_nodes=nface_nodes)
knl = lp.tag_array_axes(knl, "result", "f,f")
knl = lp.tag_array_axes(knl, "vec", "N1,N0,N2")
# Gets around 450 GB/s
knl = lp.split_iname(knl, "iel", 96, outer_tag="g.0", slabs=(0,1))
knl = lp.split_iname(knl, "iel_inner", 32, outer_tag="ilp", inner_tag="l.0", slabs=(0,1))
knl = lp.add_prefetch(knl, "vec", "j,iel_inner_outer,iel_inner_inner,f",
temporary_name="vecf", default_tag="l.auto")
knl = lp.tag_array_axes(knl, "vecf", "N1,N0,N2")
knl = lp.split_iname(knl, "idof", 20, outer_tag="g.1", slabs=(0,0))
knl = lp.split_iname(knl, "idof_inner", 4, outer_tag="ilp", inner_tag="l.1", slabs=(0,0))
knl = lp.split_iname(knl, "j", 10, slabs=(0,0))
return knl
def gen_elwise_linear_knl(n_elem, n_in, n_out, fp_format):
knl = lp.make_kernel(
"""{[iel, idof, j]:
0<=iel<nelements and
0<=idof<ndiscr_nodes_out and
0<=j<ndiscr_nodes_in}""",
"result[iel, idof] = sum(j, mat[idof, j] * vec[iel, j])",
kernel_data=[
lp.GlobalArg("result", fp_format, shape=(n_elem, n_out), order="F"),
lp.GlobalArg("vec", fp_format, shape=(n_elem, n_in), order="F"),
lp.GlobalArg("mat", fp_format, shape=(n_out, n_in), order="C")
],
name="elwise_linear")
knl = lp.fix_parameters(knl, nelements=n_elem,
ndiscr_nodes_in=n_in, ndiscr_nodes_out=n_out)
#result = lp.tag_array_axes(result, "mat", "stride:auto,stride:auto")
return knl
# Se podría usar el de Grudge.
#@memoize_method
def gen_diff_knl_fortran2(n_mat, n_elem, n_in, n_out, fp_format=np.float32,
options=None):
@memoize_in(gen_diff_knl_fortran2, "_gen_diff_knl")
def _gen_diff_knl(n_mat, n_elem, n_in, n_out, fp_format):
knl = lp.make_kernel(
"""{[imatrix,iel,idof,j]:
0<=imatrix<nmatrices and
0<=iel<nelements and
0<=idof<ndiscr_nodes_out and
0<=j<ndiscr_nodes_in}""",
"""
result[imatrix,iel,idof] = simul_reduce(sum, j, diff_mat[imatrix, idof, j] * vec[iel, j])
""",
kernel_data=[
lp.GlobalArg("result", fp_format, shape=(n_mat, n_elem, n_out),
offset=lp.auto),
lp.GlobalArg("diff_mat", fp_format, shape=(n_mat, n_out, n_in),
order="C", offset=lp.auto),
lp.GlobalArg("vec", fp_format, shape=(n_elem, n_in), order="F",
offset=lp.auto),
lp.ValueArg("nelements", tags=ParameterValue(n_elem)),
lp.ValueArg("nmatrices", tags=ParameterValue(n_mat)),
lp.ValueArg("ndiscr_nodes_out", tags=ParameterValue(n_out)),
lp.ValueArg("ndiscr_nodes_in", tags=ParameterValue(n_in))
],
assumptions="nelements > 0 \
and ndiscr_nodes_out > 0 \
and ndiscr_nodes_in > 0 and nmatrices > 0",
options=options,
name="diff_{}_axis".format(n_mat)
)
return knl
knl = _gen_diff_knl(n_mat, n_elem, n_in, n_out, fp_format)
# This should be in array context probably but need to avoid circular dependency
# Probably should split kernels out of grudge_array_context
knl = lp.tag_inames(knl, "imatrix: ilp")
knl = lp.tag_array_axes(knl, "diff_mat", "sep,c,c")
knl = lp.tag_array_axes(knl, "result", "sep,f,f")
knl = lp.tag_array_axes(knl, "vec", "f,f")
knl = lp.fix_parameters(knl, nmatrices=n_mat, nelements=n_elem,
ndiscr_nodes_in=n_in, ndiscr_nodes_out=n_out)
return knl
# Is k x i in F layout equivalent to i x k in C layout?
# If so, can we just call the gen_diff_knl?
# Pretty sure it is...
def gen_diff_knl_fortran(n_elem, n_in, n_out, fp_format=np.float32, options=None):
knl = lp.make_kernel(
"""{[k,i,j]:
0<=k<nelements and
0<=i<ndiscr_nodes_out and
0<=j<ndiscr_nodes_in}""",
"""
result1[k,i] = simul_reduce(sum, j, mat1[i, j] * vec[k, j])
result2[k,i] = simul_reduce(sum, j, mat2[i, j] * vec[k, j])
result3[k,i] = simul_reduce(sum, j, mat3[i, j] * vec[k, j])
""",
kernel_data=[
lp.GlobalArg("result1", fp_format, shape=(n_elem, n_out), order="F",
offset=lp.auto),
lp.GlobalArg("result2", fp_format, shape=(n_elem, n_out), order="F",
offset=lp.auto),
lp.GlobalArg("result3", fp_format, shape=(n_elem, n_out), order="F",
offset=lp.auto),
lp.GlobalArg("mat1", fp_format, shape=(n_out, n_in), order="C",
offset=lp.auto),
lp.GlobalArg("mat2", fp_format, shape=(n_out, n_in), order="C",
offset=lp.auto),
lp.GlobalArg("mat3", fp_format, shape=(n_out, n_in), order="C",
offset=lp.auto),
lp.GlobalArg("vec", fp_format, shape=(n_elem, n_in), order="F",
offset=lp.auto)
],
assumptions="nelements > 0 \
and ndiscr_nodes_out > 0 \
and ndiscr_nodes_in > 0",
options=options,
name="diff"
)
knl = lp.fix_parameters(knl, nelements=n_elem, ndiscr_nodes_in=n_in,
ndiscr_nodes_out=n_out)
return knl
#@memoize_method
def gen_diff_knl(n_mat, n_elem, n_in, n_out, fp_format=np.float32, options=None):
print(fp_format)
knl = lp.make_kernel(
"""{[m,k,i,j]:
0<=k<nelements and
0<=i<ndiscr_nodes_out and
0<=j<ndiscr_nodes_in and
0<=m<nmatrices}""",
"""
result[m, i ,k] = simul_reduce(sum, j, diff_mat[m, i, j] * vec[j, k])
""",
kernel_data=[
lp.GlobalArg("result", fp_format, shape=(n_mat, n_out, n_elem),
offset=lp.auto),
lp.GlobalArg("diff_mat", fp_format, shape=(n_mat, n_out, n_in),
order="C", offset=lp.auto),
lp.GlobalArg("vec", fp_format, shape=(n_in, n_elem), order="C",
offset=lp.auto)
],
#kernel_data = [
# lp.GlobalArg("result1", fp_format, shape=None, strides=(n_elem,1),
# dim_tags=None, offset=lp.auto, order="C"),
# lp.GlobalArg("result2", fp_format, shape=None, strides=(n_elem,1),
# dim_tags=None, offset=lp.auto, order="C"),
# lp.GlobalArg("result3", fp_format, shape=None, strides=(n_elem,1),
# dim_tags=None, offset=lp.auto, order="C"),
# lp.GlobalArg("mat1", fp_format, shape=lp.auto, offset=lp.auto,
# order="C"),
# lp.GlobalArg("mat2", fp_format, shape=lp.auto, offset=lp.auto,
# order="C"),
# lp.GlobalArg("mat3", fp_format, shape=lp.auto, offset=lp.auto,
# order="C"),
# lp.GlobalArg("vec", fp_format, shape=None, strides=(1, n_elem),
# offset=lp.auto, order="C")
#],
assumptions="nelements > 0 \
and ndiscr_nodes_out > 0 \
and ndiscr_nodes_in > 0 \
and nmatrices > 0",
options=options,
name="diff"
)
knl = lp.tag_array_axes(knl, "diff_mat", "sep,c,c")
knl = lp.tag_array_axes(knl, "result", "sep,c,c")
knl = lp.tag_array_axes(knl, "vec", "c,c")
knl = lp.fix_parameters(knl, nmatrices=n_mat, nelements=n_elem,
ndiscr_nodes_in=n_in, ndiscr_nodes_out=n_out)
#mat_string = ["result1", "result2", "result3", "vec"]
#for i in range(len(mat_string)):
# knl = lp.tag_array_axes(knl, mat_string, "stride:auto,stride:auto")
# knl = lp.tag_array_axes(knl, mat_string, "N1,N0")
return knl
# This is redundant with the above but is more clear than the above
# so to keep it around may be worthwhile.
'''
def gen_diff_knl(n_elem, n_in, n_out, k_inner_outer,k_inner_inner,i_inner_outer,
i_inner_inner,j_inner, fp_format=np.float32):
knl = lp.make_kernel(
"""{[k,i,j]:
0<=k<nelements and
0<=i<ndiscr_nodes_out and
0<=j<ndiscr_nodes_in}""",
"""
result1[i,k] = simul_reduce(sum, j, mat1[i, j] * vec[j, k])
result2[i,k] = simul_reduce(sum, j, mat2[i, j] * vec[j, k])
result3[i,k] = simul_reduce(sum, j, mat3[i, j] * vec[j, k])
""",
kernel_data = [
lp.GlobalArg("result1", fp_format, shape=(n_out, n_elem), order="C"),
lp.GlobalArg("result2", fp_format, shape=(n_out, n_elem), order="C"),
lp.GlobalArg("result3", fp_format, shape=(n_out, n_elem), order="C"),
lp.GlobalArg("mat1", fp_format, shape=(n_out, n_in), order="C"),
lp.GlobalArg("mat2", fp_format, shape=(n_out, n_in), order="C"),
lp.GlobalArg("mat3", fp_format, shape=(n_out, n_in), order="C"),
lp.GlobalArg("vec", fp_format, shape=(n_in, n_elem), order="C")
],
assumptions="nelements > 0 \
and ndiscr_nodes_out > 0 \
and ndiscr_nodes_in > 0",
default_offset=None,
name="diff"
)
knl = lp.fix_parameters(knl, nelements=n_elem, ndiscr_nodes_in=n_in,
ndiscr_nodes_out=n_out)
slabs0 = (0,0) if n_elem % k_inner_outer == 0 else (0,1)
knl = lp.split_iname(knl, "k", k_inner_outer, outer_tag="g.0", slabs=slabs0)
knl = lp.split_iname(knl, "k_inner", k_inner_inner, outer_tag="ilp",
inner_tag="l.0")
knl = lp.split_iname(knl, "j", j_inner)
knl = lp.split_iname(knl, "i", i_inner_outer, outer_tag="g.1")#slabs=(0,1))
knl = lp.split_iname(knl, "i_inner", i_inner_inner, outer_tag="ilp",
inner_tag="l.1")
#knl = lp.prioritize_loops(knl, "j_outer,j_inner,k_inner_outer")
knl = lp.add_prefetch(knl, "vec", "j_outer,j_inner,k_inner_outer,k_inner_inner",
temporary_name="vecf", default_tag="l.auto")
knl = lp.add_prefetch(knl, "mat1", "j_inner", temporary_name="mat1fp",
default_tag="unr")
knl = lp.add_prefetch(knl, "mat2", "j_inner", temporary_name="mat2fp",
default_tag="unr")
knl = lp.add_prefetch(knl, "mat3", "j_inner", temporary_name="mat3fp",
default_tag="unr")
return knl
'''
def load_transformations_from_file(hjson_file, indices):
od = hjson.loads(hjson_file.read())
for index in indices:
od = od[index]
return od
def generate_transformation_list_old(k_inner_outer, k_inner_inner, i_inner_outer,
i_inner_inner, j_inner):
transformations = []
# transformation name, list of args, dict of keyward args
transformations.append(("split_iname", ["k", k_inner_outer], {"outer_tag": "g.0",
"slabs": (0, 1)}))
transformations.append(("split_iname", ["k_inner", k_inner_inner],
{"outer_tag": "ilp", "inner_tag": "l.0"}))
transformations.append(("split_iname", ["j", j_inner]))
transformations.append(("split_iname", ["i", i_inner_outer],
{"outer_tag": "g.1"}))
transformations.append(("split_iname", ["i_inner", i_inner_inner],
{"outer_tag": "ilp", "inner_tag": "l.1"}))
transformations.append(("add_prefetch", ["vec",
"j_outer,j_inner,k_inner_outer,k_inner_inner"],
{"temporary_name": "vecf", "default_tag": "l.auto"}))
transformations.append(("add_prefetch", ["mat1", "j_inner"],
{"temporary_name": "mat1fp", "default_tag": "unr"}))
transformations.append(("add_prefetch", ["mat2", "j_inner"],
{"temporary_name": "mat2fp", "default_tag": "unr"}))
transformations.append(("add_prefetch", ["mat3", "j_inner"],
{"temporary_name": "mat3fp", "default_tag": "unr"}))
return tuple(transformations)
# This is rather nvidia specific at present
# And also specific to the diff kernel
# May need different ones of these for different kernels
def generate_transformation_list(k_inner_outer, k_inner_inner, i_inner_outer,
i_inner_inner, j_inner):
transformations = []
# transformation name, list of args, dict of keyward args
# Set data layouts
# This should be handled by the array context?
#transformations.append(("tag_array_axes", ["diff_mat", "sep,c,c"]))
#transformations.append(("tag_array_axes", ["result", "sep,f,f"]))
# Split and tag inames
#transformations.append(("tag_inames", [[("imatrix", "ilp")]]))
transformations.append(("split_iname", ["iel", k_inner_outer], {"outer_tag": "g.0",
"slabs": (0, 1)}))
transformations.append(("split_iname", ["iel_inner", k_inner_inner],
{"outer_tag": "ilp", "inner_tag": "l.0"}))
transformations.append(("split_iname", ["idof", i_inner_outer],
{"outer_tag": "g.1"}))
transformations.append(("split_iname", ["idof_inner", i_inner_inner],
{"outer_tag": "ilp", "inner_tag": "l.1"}))
transformations.append(("split_iname", ["j", j_inner]))
# Prefetching
transformations.append(("add_prefetch", ["vec",
"j_outer,j_inner,iel_inner_outer,iel_inner_inner"],
{"temporary_name": "vecf", "default_tag": "l.auto"}))
transformations.append(("tag_array_axes", ["vecf", "f,f"]))
transformations.append(["add_inames_for_unused_hw_axes"])
return tuple(transformations)
def get_einsums(knl):
einsums = []
for instr in knl.default_entrypoint.instructions:
if isinstance(instr, lp.Assignment):
for tag in instr.tags:
if isinstance(tag, EinsumTag):
if isinstance(instr.expression, lp.symbolic.Reduction):
einsums.append((instr.within_inames, instr.expression.inames,))
else:
einsums.append((instr.within_inames, (),))
#print(knl.default_entrypoint.name, einsums)
return einsums
def get_einsum_counts(knl):
from collections import Counter
counter = Counter(get_einsums(knl))
#print(counter)
return counter
# Obtain non-reduction and reduction inames
def get_einsum_types(knl):
return frozenset(get_einsums(knl))
def add_batch_ids(tunit, batch_size):
from meshmode.array_context import EinsumTag
assert batch_size >= 1
# Should a batch size of zero be equal to a single batch
new_instructions = []
batch_number = 0
used_batches = 0
num_in_cur_batch = 0
batch_instructions_list = []
# Could add some priority level based on the length of the chain of einsums so
# if there is a dependency chain es1 -> es2 -> es3 then es2 must be put in
# a batch higher than that of es1 and ditto with es3
batch_instructions = []
insn_mappings = {}
for instr in tunit.default_entrypoint.instructions:
# If collect the einsums in a list then the batch number should be index // batch_size?
# The below seems unneccessarily complicated.
if isinstance(instr, lp.Assignment) and any([isinstance(tag, EinsumTag) for tag in instr.tags]):
insn_mappings[instr.id] = [f"batch_{batch_number}_" + instr.id]
# Also add batch prefix to any prefetch instructions for the einsum
for dep_id in instr.depends_on:
if "fetch_rule" in dep_id:
insn_mappings[dep_id] = [f"batch_{batch_number}_" + dep_id]
new_instr = instr.copy(id=f"batch_{batch_number}_" + instr.id)
new_instructions.append(new_instr)
batch_instructions.append(new_instr)
num_in_cur_batch += 1
if num_in_cur_batch == batch_size:
batch_number += 1
num_in_cur_batch = 0
batch_instructions_list.append(batch_instructions)
batch_instructions = []
else:
new_instructions.append(instr)
# Handle a non-full final batch
if len(batch_instructions) > 0 and len(batch_instructions) < batch_size:
batch_instructions_list.append(batch_instructions)
# Need to add batch ids to the prefetch instructions
# and order the batches. The prefetching of the next batch can't begin until the current batch finishes
# Can us the group numbers to order tmpgrp__actx_in_1_0_momentum_1_0f
"""
fetch_rules = set([instr.id for instr in tunit.default_entrypoint.instructions if "fetch_rule" in instr.id])
for i, batch in enumerate(batch_instructions_list):
for einsum in batch:
fetch_rule_deps = einsum.depends_on & fetch_rules
for fetch_rule in fetch_rule_deps:
# Assume fetch_rules only fetch for a single einsum
assert fetch_rule not in fetch_rule_mapping
fetch_rule_mapping[fetch_rule] = fetch_rule.copy(id="batch_{i}_" + instr.id)
"""
#print(insn_mappings)
#print(tunit.default_entrypoint)
new_knl = lp.replace_instruction_ids(tunit.default_entrypoint, insn_mappings)
#for instr in tunit.default_entrypoint.instructions:
# print(instr)
#print()
#for instr in new_knl.instructions:
# print(instr)
#print(new_knl)
#exit()
return tunit.with_kernel(new_knl), batch_instructions_list # Maybe don't need the batch instructions list anymore?
#for i, instr in enumerate(new_instructions):
# if instr in fetch_rule_mapping:
# print("HERE")
# new_instructions[i] = fetch_rule_mapping[instr]
#exit()
#return tunit.with_kernel(tunit.default_entrypoint.copy(instructions=new_instructions)), batch_instructions_list
# Will the temporaries group automatically handle the einsum chunking problem?
#def alias_temporaries_among_batches(tunit, nbatches):
# batch_instructions = {}
# for instr in tunit.default_entrypoint.instructions:
# Just get the temporaries of each batch and alias those of the same size
"""
def get_batch_temporaries_by_size(tunit, batches):
# Assumes all of the temporaries are in local or private memory
temp_dict = tunit.default_entrypoint.temporary_variables
batch_dict_list = [] # A list of dictionaries of sets
for batch in batches:
batch_dict = {}
for einsum in batch:
for dep in einsum.dependency_names():
if dep in temp_dict:
shape = temp_dict[dep].shape
if shape not in batch_dict:
batch_dict[shape] = set([dep])
else:
batch_dict[shape] |= set([dep])
batch_dict_list.append(batch_dict)
return batch_dict_list
"""
# TODO: Make data type an argument and only alias for a single data type at a time.
# For now, assume all temporaries have the same data type.
def get_batch_temporaries_by_size(tunit, nbatches, address_space):
# Assumes all of the temporaries are in local or private memory
temp_dict = {key: val for key, val in tunit.default_entrypoint.temporary_variables.items() if val.address_space==address_space}
#print("Temp dict:", temp_dict)
#exit()
batch_dict_list = [] # A list of dictionaries (keyed by size, one for each batch) of sets of temporary ids
# Inefficient
for batch_num in range(nbatches):
batch_dict = {}
for instr in tunit.default_entrypoint.instructions:
if f"batch_{batch_num}" in instr.id:
for dep in instr.dependency_names():
if dep in temp_dict:
size = np.product(temp_dict[dep].shape)
if size not in batch_dict:
batch_dict[size] = set([dep])
else:
batch_dict[size] |= set([dep])
batch_dict_list.append(batch_dict)
return batch_dict_list
def get_alias_sets(batch_dict_list):
from itertools import combinations
import copy
sizes = set()
for batch_dict in batch_dict_list:
sizes |= set(batch_dict.keys())
alias_sets = []
for size in sizes:
arg_lists = []
arg_sets = []
for i, batch_dict in enumerate(batch_dict_list):
arg_lists.append(sorted(batch_dict[size]))
arg_sets.append((i,set(batch_dict[size],)))
#max_len = 0
#for l in arg_lists:
# max_len = max(len(l), max_len)
max_len = np.max([len(l) for l in arg_lists])
for l in arg_lists:
l += [None]*(max_len - len(l)) # Pad with None so can slice columns
#while len(l) < max_len:
# l.append(None) # Pad with None so can slice columns
# This needs to be a bit more robust, we want a variable to alias with itself.
# We also can't allow two tempories to alias if they occur in the same block (row)
# Permute so if a value is found in the current row it isn't found in the current column
# except if the value is self
# Permute so self is in current column as much as possible
# For now just assert to verify this is not the case, don't attempt to fix
arg_array = np.array(arg_lists)
#print(arg_array)
moved = []
# See if any two batches share any temporaries
set_combo_iterator = combinations(arg_sets,2)
for (row1, set1), (row2, set2) in set_combo_iterator:
intersection = set1 & set2
for temporary in intersection:
# Find the column indices of the shared temporaries
col1 = list(arg_array[row1,:]).index(temporary)
col2 = list(arg_array[row2,:]).index(temporary)
moved.append(temporary)
if col1 != col2:
#print((row1,col1), (row2,col2))
# Use row1 as the pivot row and swap the col1 and col2 in
# the rest of the rows. Need to apply to all rows
# except pivot to avoid undoing any prior pairings
# Attempting to do this using slicing and boolean
# arrays didn't work, so doing this manually.
#print(temporary, (row1,col1), (row2, col2))
#print("BEFORE")
#print(arg_array[:,[col1,col2]])
for row in np.arange(0, arg_array.shape[0]):
# Only exchange column values when necessary.
if row != row1 and arg_array[row1,col1] == arg_array[row,col2]:
holder = arg_array[row, col1]
arg_array[row,col1] = arg_array[row,col2]
arg_array[row,col2] = holder
#print("AFTER")
"""
# Check that nothing already aligned came out of alignment
subarray = arg_array[:,[col1,col2]]
for entry in subarray.flatten():
if entry is not None:
print(entry)
indices = np.argwhere(subarray == entry)
if entry in moved:
assert indices.shape[0] > 1
print(indices)
print(subarray)
assert np.all(indices[:,1] == indices[0,1])
"""
#arg_array[selected_rows,col1][:] = arg_array[selected_rows,col2][:]
#arg_array[selected_rows,col2][:] = holder[:]
#print("AFTER")
#print(arg_array[selected_rows,col1][:])
#print(arg_array[selected_rows,col2][:])
#print(arg_array[row1,:])
#print(arg_array[row2,:])
#arg_array[selected_rows,col1], arg_array[selected_rows,col2] = copy.deepcopy(arg_array[selected_rows, col2]), copy.deepcopy(arg_array[selected_rows,col1])
# Check that the re-arrangement was done properly
#assert arg_array[row1, col1] == arg_array[row2, col1]
#assert arg_array[row1, col1] != arg_array[row2, col2]
#exit()
"""
# Check that everything is properly aligned.
for entry in arg_array.flatten():
if entry is not None:
print(entry)
indices = np.argwhere(arg_array == entry)
print(indices)
assert np.all(indices[:,1] == indices[0,1])
"""
#flat_arg_array = arg_array.flatten()
#nonzero_entries = flat_arg_array[np.flatnonzero(flat_arg_array)]
#unique_entries = np.unique(nonzero_entries)
#print(unique_entries)
#print(nonzero_entries)
# Should be fixed now so this check can be disabled
#assert len(unique_entries) == len(nonzero_entries)
#for col in range(arg_array.shape[1]):
# col_set = set(arg_array[:,col].flatten())
# for row in range(arg_array.shape[0]):
# row_set = set(arg_array[row,:].flatten())
# assert col_set & row_set == set([arg_array[row,col]])
for col in range(arg_array.shape[1]):
alias_sets.append(set(arg_array[:,col]) - set([None]))
return alias_sets
from qprofile import qprofile, qinstrument
# Should probably be renamed batch_einsums_and_prefetch or similar
# these transformations seem to be linked
#@qprofile
#@qinstrument
def batch_einsums(tunit, batch_size, **kwargs):
from pyinstrument import Profiler
profiler=Profiler()
profiler.start()
print("BATCHING THE EINSUMS")
#exit()
# Or if the batch size is greater than the number of einsums?
if batch_size <= 0:
return tunit
#print(tunit)
#exit()
# Need to get the existing tags and apply them to the new loops
# Maybe have the option of batching by global inames or local inames.
# Might be less cache pollution if the batching is done at the global level.
orig_nonglobal_inames = []
#orig_inames = tunit.default_entrypoint.inames.items()
# Will need to think about the names of prefetching arrays
for name, iname in tunit.default_entrypoint.inames.items():
if not any([isinstance(tag, lp.kernel.data.GroupInameTag) for tag in iname.tags]):
orig_nonglobal_inames.append(name)
#inames_to_duplicate = sorted(inames_to_duplicate)
#inames_to_duplicate = sorted(tunit.default_entrypoint.inames.keys())
#print(len(inames_to_duplicate))
#inames_to_duplicate = sorted(inames_to_duplicate + [iname for iname in tunit.default_entrypoint.inames.keys() if "iel_" in iname])
#for iname in inames_to_duplicate:
# print(iname)
#print(tunit)
#exit()
non_fetch_rule_inames = set()
for instr in tunit.default_entrypoint.instructions:
if not "fetch_rule" in instr.id: # Could be a problem if someone overrides the inames at any point
non_fetch_rule_inames |= set(instr.within_inames)
within_inames = set()
for instr in tunit.default_entrypoint.instructions:
within_inames |= set(instr.within_inames)
additional_inames_to_duplicate = set(tunit.default_entrypoint.inames.keys()) - within_inames
# Need to rename this variable
#print(non_fetch_rule_inames)
#inames_to_duplicate = sorted([iname for iname in tunit.default_entrypoint.inames.keys() if not "actx_" in iname])
#inames_to_duplicate = sorted(non_fetch_rule_inames) # Apparently this does not include idof_ensm1
#print(inames_to_duplicate)
#print(tunit.default_entrypoint.inames.keys())
#print(non_fetch_rule_inames)
#exit()
#fetch_rules = [instr for instr in knl.instructions if "fetch_rule" in instr.id]
#fetch_rule_union_inames =
#fetch_rule_intersection_inames
# Do we really need to copy the actx_* inames? Can those go away?
#print(inames_to_duplicate)
#exit()
#inames_to_duplicate = sorted(tunit.default_entrypoint.inames.keys()) # Override to global for now
#print(inames_to_duplicate)
#orig_iname_dict = tunit.default_entrypoint.inames.items()
# Returning the batches is now unnecessary
b_tunit, batches = add_batch_ids(tunit, batch_size)
nbatches = len(batches)
knl = b_tunit.default_entrypoint
#print(knl)
#exit()
#print(knl)
#print("AFTER PREPROCESS")
#print(lp.preprocess_kernel(tunit))
# Attempt to avoid the poor scaling of add_prefetch by applying the
# prefetching to subkernels which are then recombined
# prefetch_data is a list of tuples of (argname, prefetch_str)
"""
def add_prefetches_by_batch(tunit, nbatches, prefetch_data, **kwargs):
# Seems like there are two tasks, one is getting the batch/phase
# instructions, which is particular to desired decomposition
# then, creating the subkernels with those instructions, which
# is rather generic and code can probably be re-used there.
# Obtaining the instruction domains can be done in the generic part.
# Maybe the latter part can go into Loopy.
# Could the testing be done using a single batch instead of the full kernel?
# Create the batch subkernels
def create_batch_subkernels(tunit, nbatches):
batch_instructions = [[]]*nbatches
batch_domains = [[]]*nbatches
for instr in tunit.default_entrypoint.instructions:
if "batch_" in instr.id:
batch_num = instr.id.split("_")[1]
batch_instructions[batch_num].append(instr)
batch_domains[batch_num].append(instr.within_inames)
# Replace inames with domain objects
# Move this function out of init
domain_list = get_domain_list(tunit)
for batch_num in nbatches:
domain_ids = batch_domains[batch_num]
batch_domains[batch_num] = []
for domain_names_set, domain in domain_list:
if domain_ids <= domain_names_set:
batch_domains[batch_num].append(domain)
for batch_num in nbatches:
domains = batch_domains[batch_num]
instructions = batch_instructions[batch_num]
# Can re-use some code from generate_subkernels
# In fact, phases are basically the same thing as batches,
# though they are currently indexed by barrier rather than
# a phase/batch number
# Figure out what prefetches apply to what batches
# May as well tag the prefetch instructions with the batch numbers as well
# Apply the prefetches in the batches
# Combine the subkernels
# Proceed to batching
"""
# Maybe this needs to be a separate transformation
def linearize_batches(tunit, batches):
print("Linearizing batches")
knl = tunit.default_entrypoint
nbatches = len(batches)
# See if stripping off the iname tags makes batching faster
# -- It doesn't seem to help
"""
iname_tags_dict = {}
for iname_name, iname_obj in knl.inames.items():
iname_tags_dict[iname_name] = iname_obj.tags
tagless_inames = {}
for iname_name, iname_obj in knl.inames.items():
tagless_inames[iname_name] = iname_obj.copy(tags=frozenset())
print(knl)
knl = knl.copy(inames=tagless_inames)
print(knl)
exit()
"""
# Alias local memory temporaries
#batch_temps_by_size = get_batch_temporaries_by_size(tunit, nbatches)
#alias_sets = get_alias_sets(batch_temps_by_size)
#for s in alias_sets:
# knl = lp.alias_temporaries(knl, list(s))
# Map instruction ids to fetch rules, will probably need to add this part to prefetch_and_project too
"""
fetch_rules = set([instr.id for instr in knl.instructions if "fetch_rule" in instr.id])
#print(knl)
#exit()
#kern = knl.copy(target=lp.CTarget())
#kern = b_tunit.copy(target=lp.OpenCLTarget())
#code = lp.generate_code_v2(kern).device_code()
#print(code)
#exit()
#print(type(batches))
#exit()
print("Adding dependencies")
for i, batch in enumerate(batches[1:],start=1):
'''
for einsum in batch:
j = i - 1
knl = lp.add_dependency(knl, f"id:batch_{i}_*", f"id:batch_{j}_*")
# The following is needed if batching occurs after prefetching
# Note that this will make the code non-generatable until the batch inames are duplicated
fetch_rule_deps = einsum.depends_on & fetch_rules
for fetch_rule in fetch_rule_deps:
# Make the fetch rule depend on the immediately prior batch if no prior batch already depends on it
add_dep = True
for k in range(i-1, -1, -1):
if any([fetch_rule in prior_batch_einsum.depends_on for prior_batch_einsum in batches[k]]):
add_dep = False
break
if add_dep:
knl = lp.add_dependency(knl, f"id:{fetch_rule}", f"id:batch_{j}_*")
'''
"""
# Enforcing an ordering may or may not reduce scheduling time
# Actually, is needed for aliasing
#for i in range(1, nbatches):
# j = i - 1
# knl = lp.add_dependency(knl, f"id:batch_{i}_*", f"id:batch_{j}_*")
#print(knl)
#exit()
#kern = knl.copy(target=lp.CTarget())
#kern = b_tunit.copy(target=lp.OpenCLTarget())
#code = lp.generate_code_v2(kern).device_code()
#print(code)
#exit()
# Create independent loops for each batch
import time
orig_inames = set(knl.inames.keys())
#print(knl)
# Decoupling with a frozenset puts each iname in its own set.
#print("Decoupling all inames")
#for iname in knl.inames.keys():
# print("Decoupling", iname)
# knl = decouple_domain(knl, iname, frozenset())
print("DECOUPLING")
# Decoupling the original inames seems to cause code generation problems,
# but if this isn't done then decoupling takes forever
#print(set(knl.inames.keys()) - set(inames_to_duplicate))
#exit()
#print(inames_to_duplicate)
#exit()
#knl = decouple_domain(knl, inames_to_duplicate[0:3], frozenset())
#knl = decouple_domain(knl, knl.inames, frozenset())
#knl = decouple_domain(knl, inames_to_duplicate, knl.inames.keys())
#"""
print("Duplicating inames")
# Can perhaps do another decompose -> transform -> recompose for creating the loop nests.
# Essentially rename the inames and then add each set of inames as a separate domain
# to the recomposed kernel.
for i in range(0, nbatches): # Should we keep the first batch in the original set of loops?
start = time.time()
before_inames_dict = knl.inames.copy()
batch_inames = set()
for instr in knl.instructions:
if f"batch_{i}_" in instr.id:
batch_inames |= instr.within_inames
# For some reason idof_ensm2 does not appear in batch_inames. (Maybe it is a reduction iname?)
# This is a hack to make sure it appears.
batch_inames_to_duplicate = batch_inames | additional_inames_to_duplicate
suffix = f"_b{i}"
print("HERE")
#knl = lp.duplicate_inames(knl, inames_to_duplicate, f"id:batch_{i}_*", suffix=suffix)
knl = lp.duplicate_inames(knl, batch_inames_to_duplicate, f"id:batch_{i}_*", suffix=suffix)
print("DONE HERE")
after_inames_dict = knl.inames.copy()
added_inames = set(after_inames_dict.keys()) - set(before_inames_dict.keys())
# Orig nonglobal_inames may be too big a set
# The problem is that prefetching adds a bunch of new nonglobal inames
# Need to limit this to only the inames duplicated
#parent_inames = set(inames_to_duplicate) | added_inames
#parent_inames = set(batch_inames_to_duplicate) | added_inames