-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmemoryBoundSplit.py
More file actions
executable file
·2360 lines (2016 loc) · 103 KB
/
memoryBoundSplit.py
File metadata and controls
executable file
·2360 lines (2016 loc) · 103 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 ressources as res
import math
from itertools import combinations, product, permutations
import numpy as np
import pocc
import networkx as nx
import matplotlib.pyplot as plt
from collections import deque
class memoryBound:
def __init__(self, res, folder, split, file, nlp_file, analysis, schedule, UB, LB, statements, iterators, output, headers, arguments, name_function, pragmas, pragmas_top):
self.res = res
self.folder = folder
self.split_info = split
self.file = file
self.nlp_file = nlp_file
self.analysis = analysis
self.schedule = schedule
self.cyclic_buffer = False
self.size_cyclic_buffer = 16
self.UB = UB
self.LB = LB
self.statements = statements
self.iterators = iterators
self.output = output
self.headers = headers
self.arguments = arguments
self.name_function = name_function
self.pragmas = pragmas
self.pragmas_top = pragmas_top
self.TC = {}
self.compute_TC()
self.inter_task_dependance = {}
self.compute_inter_task_dependance()
self.graph = {}
self.matrix_graph = []
self.compute_graph()
self.array_to_focus = self.analysis.array_to_focus
self.loop_body_independant = {}
self.compute_loop_body_independant()
self.info_loops = {}
self.compute_info_loops()
self.create_nlp()
# self.compute()
def bfs(self, start=0):
visited = set()
queue = deque([(start, 0)]) # Node and its level
levels = {start: 0}
while queue:
node, level = queue.popleft()
visited.add(node)
for neighbor, value in enumerate(self.matrix_graph[node]):
if value == 1 and neighbor not in visited:
is_all_dep_done = True
for k in range(len(self.matrix_graph)):
if self.matrix_graph[k][neighbor] == 1 and (k not in visited or levels[k] == level + 1):
is_all_dep_done = False
break
if is_all_dep_done:
queue.append((neighbor, level + 1))
visited.add(neighbor)
levels[neighbor] = level + 1
level_with_id_statement = {}
for key in list(levels.keys()):
level = levels[key]
if key > 0:
level_with_id_statement[key-1] = level
return level_with_id_statement
def compute_graph(self):
self.matrix_graph = np.zeros((len(self.schedule)+1, len(self.schedule)+1))
for k1 in range(len(self.schedule)):
previous_dependance = False
for k2 in range(k1):
if self.inter_task_dependance[k1][k2]:
previous_dependance = True
for k2 in range(len(self.schedule)):
if self.inter_task_dependance[k1][k2]:
if k2 > k1:
self.matrix_graph[k1+1][k2+1] = 1
for k1 in range(len(self.matrix_graph)):
for k2 in range(len(self.matrix_graph)):
for k3 in range(len(self.matrix_graph)):
if self.matrix_graph[k1][k2] == 1 and self.matrix_graph[k2][k3] == 1:
self.matrix_graph[k1][k3] = 0
# # RAR
# # FIXME need to check the polyhedron to be sure it is a RAR
read = {}
read = {0: []}
scop = pocc.scop(self.folder, self.file)
id_statement = 0
for k,line in enumerate(scop):
if "# Read access informations" in line:
k1 = k
while "# Write access informations" not in line:
stat = ""
if "##" in line:
stat = line.split("##")[1].replace("\n", "").replace("\n", "").split("[")[0]
if stat != "":
read[id_statement].append(stat)
k1+=1
line = scop[k1]
id_statement += 1
read[id_statement] = []
for sched1 in range(len(self.schedule)):
for sched2 in range(len(self.schedule)):
if sched1 < sched2:
for arr in read[sched1]:
if arr in read[sched2]:
cycle = False
for k in range(len(self.schedule)):
if self.matrix_graph[min(k+1, sched2+1)][max(k+1, sched2+1)] == 1 and self.matrix_graph[min(k+1, sched1+1)][max(k+1, sched1+1)] == 1:
cycle = True
break
if not cycle:
self.matrix_graph[sched1+1][sched2+1] = 1
for k1 in range(len(self.schedule)):
column_sum = 0
for k2 in range(len(self.schedule)):
column_sum += self.matrix_graph[k2+1][k1+1]
if column_sum == 0:
self.matrix_graph[0][k1+1] = 1
G = nx.DiGraph()
G.add_node("Root")
for i in range(len(self.schedule)):
G.add_node(f"S{i}")
for i in range(len(self.matrix_graph)):
for j in range(len(self.matrix_graph[0])):
if self.matrix_graph[i][j] == 1:
node_i = ""
node_j = ""
if i == 0:
node_i = "Root"
else:
node_i = f"S{i-1}"
if j == 0:
node_j = "Root"
else:
node_j = f"S{j-1}"
G.add_edge(node_i, node_j)
# Plot the graph
pos = nx.spring_layout(G) # positions for all nodes
nx.draw(G, pos, with_labels=True, arrows=True)
# save
plt.savefig("graph.png")
def compute_inter_task_dependance(self):
# init
for k1 in range(len(self.statements)):
self.inter_task_dependance[k1] = {}
for k2 in range(len(self.statements)):
self.inter_task_dependance[k1][k2] = False
res = pocc.candl(self.folder, self.file)
for line in res:
# if "RAW" in line or "WAR" in line or "WAW" in line:
if "RAW" in line :
id_1 = int(line.split("->")[0].replace("S", "").replace(" ", ""))
id_2 = int(line.split("->")[1].split("[")[0].replace("S", "").replace(" ", ""))
self.inter_task_dependance[min(id_1, id_2)][max(id_1, id_2)] = True
# self.inter_task_dependance[id_2][id_1] = True
def compute_TC(self):
id_loop = 0
for id_ in range(len(self.schedule)):
TC = self.analysis.dic[id_]["TC"]
for key in list(TC.keys()):
self.TC[id_loop] = TC[key]
id_loop += 1
def compute_other_loops(self, id_):
others_loops = []
for id_2 in range(len(self.schedule)):
if id_2 != id_:
loops_2 = self.schedule[id_2][1::2]
others_loops += loops_2
others_loops = list(set(others_loops))
return others_loops
def multi_split(self, str_, delimiters, delete_array=False):
for delim in delimiters:
str_ = str_.replace(delim, "@")
res = str_.split("@")
new_res = []
for r in res:
if "[" in r:
new_res.append(r)
res = new_res
new_res = []
if delete_array:
for r in res:
if "[" in r:
r = r.split("[")[0]
new_res.append(r)
while "" in res:
res.remove("")
return new_res
while "" in res:
res.remove("")
return res
def extract_array(self, statement):
out = statement.split("=")[0]
out = out.strip().split("[")[0]
inp = statement.split("=")[1]
inp = self.multi_split(inp.strip().replace(";", "").replace(" ", ""), ["+", "-", "*", "/"], True)
return out, inp
def extract_operation(self, statement):
op = []
inside_bracket = False
for s in statement:
if s == "[":
inside_bracket = True
if s == "]":
inside_bracket = False
if not inside_bracket:
if s in ["+", "-", "*", "/"]:
op.append(s)
return op
def compute_loop_body_independant(self):
for id_ in range(len(self.schedule)):
is_independant = True
loops = self.schedule[id_][1::2]
others_loops = self.compute_other_loops(id_)
for loop in loops:
if loop in others_loops:
is_independant = False
break
self.loop_body_independant[id_] = is_independant
def extract_iterators(self, out):
iterators = []
if "[" in out:
it = out[out.index("[")+1:]
iterators = it.replace("][", "@").replace("]", "").split("@")
return iterators
def compute_info_loops(self):
self.red_loop = {}
for id_ in range(len(self.schedule)):
loops = self.schedule[id_][1::2]
for loop in loops:
self.red_loop[loop] = False
for id_ in range(len(self.schedule)):
loops = self.schedule[id_][1::2]
for loop in loops:
it = self.extract_iterators(self.analysis.dic[id_]["write"][0])
if self.iterators[loop] not in it:
self.red_loop[loop] = True
for id_ in range(len(self.schedule)):
loops = self.schedule[id_][1::2]
info_loops = {}
statement = self.statements[id_]
out, inp = self.extract_array(statement)
op = self.extract_operation(statement)
info_loops["write"] = self.analysis.dic[id_]["write"]
it = self.extract_iterators(self.analysis.dic[id_]["write"][0])
reduction_loop = {}
for loop in loops:
reduction_loop[loop] = False
if self.iterators[loop] not in it:
reduction_loop[loop] = True
info_loops["reduction_loop"] = reduction_loop
info_loops["read"] = self.analysis.dic[id_]["read"]
info_loops["operation"] = self.analysis.operations[id_]
info_loops["arrays_size"] = self.analysis.arrays_size
self.info_loops[id_] = info_loops
def give_index(self, l, val, index):
first_index = l.index(val)
if index == first_index:
return 0
else:
return 1
def change_TC(self, TC):
current_burst = 16
if TC%16==0:
current_burst = 16
elif TC%8==0:
current_burst = 8
elif TC%4==0:
current_burst = 4
elif TC%2==0:
current_burst = 2
else:
current_burst = 1
original = TC / current_burst
new_TC = 0
for k in range(TC, 10*TC):
if k%16==0:
new_TC = k
break
new = new_TC / 16
if new < original:
return True, new_TC
else:
return False, new_TC
def what_is_fuse(self):
l = []
all_output = {}
for k,s in enumerate(self.statements):
output = s.split("=")[0].split("[")[0].strip()
if output not in list(all_output.keys()):
all_output[output] = []
all_output[output].append(k)
return list(all_output.values())
def first_use(self, array):
for id_sched in range(len(self.schedule)):
r = self.analysis.dic[id_sched]["read"]
w = self.analysis.dic[id_sched]["write"]
randw = r + w
for r in randw:
if array in r:
return id_sched
return -1
def all_use(self, array):
l = []
for id_sched in range(len(self.schedule)):
r = self.analysis.dic[id_sched]["read"]
w = self.analysis.dic[id_sched]["write"]
randw = r + w
for r in randw:
if array in r:
l += [id_sched]
return l
def give_it_loop(self, arr, fused_task, name_var_footprint_fused):
it_array = ""
coresponding_loop = []
for task2 in fused_task:
if arr in list(name_var_footprint_fused[task2].keys()):
r = self.info_loops[task2]["read"]
w = self.info_loops[task2]["write"]
randw = r + w
for r in randw:
if arr in r:
it_array = self.extract_iterators(r)
cur_loop = self.schedule[task2][1::2]
for loop in cur_loop:
for it in it_array:
if self.iterators[loop] == it:
coresponding_loop.append(loop)
return it_array, coresponding_loop, task2
return -1
def calculate_latency(self, node, dependencies, latency, shifts, memo):
if node in memo:
return memo[node]
if not dependencies[node]: # If there are no dependencies
memo[node] = latency[node]
return latency[node]
dependency_latencies = []
for dep in dependencies[node]:
dep_latency = self.calculate_latency(dep, dependencies, latency, shifts, memo)
shift = shifts.get((dep, node), "0")
dependency_latencies.append(f"{shift} + {latency[node]}, {dep_latency}")
if dependency_latencies:
max_dependency_latency = f"max({', '.join(dependency_latencies)})"
else:
max_dependency_latency = latency[node]
total_latency = max_dependency_latency
memo[node] = total_latency
return total_latency
def add_parameters(self):
param = [f"DSP_avail = {self.res.DSP};", f"ON_CHIP_MEM_SIZE = {self.res.ON_CHIP_MEM_SIZE};", f"MAX_BUFFER_SIZE = {self.res.MAX_BUFFER_SIZE};", f"CONSTRAINT_ARRAY_PARTITIONING_VALUE = {self.res.partitioning_max};", f"MAX_UF = {self.res.MAX_UF};"]
for nb_slr in range(self.res.SLR):
param.append(f"SLR{nb_slr}_mem = {self.res.MEM_PER_SLR};")
param.append(f"SLR{nb_slr}_DSP = {self.res.DSP_per_SLR};")
for k in range(len(self.schedule)):
param.append(f"II_S{k}_par = 1;")
param.append(f"II_S{k}_seq = 3;")
for k in list(self.TC.keys()):
tc = []
param.append(f"TC{k}_ori = {self.TC[k]};")
for k in range(len(self.schedule)):
op = self.analysis.operations[k]
loops = self.schedule[k][1::2]
is_red = False
for loop in loops:
if self.red_loop[loop]:
is_red = True
break
#FIXME suppose the red is + for now
seq = 0
par = 0
if is_red:
seq = 1 * self.res.IL["+"]
for o in op:
if o == "+":
nb = op[o]
if is_red:
nb -= 1
par += nb * self.res.IL["+"]
elif o == "-":
nb = op[o]
par += nb * self.res.IL["-"]
elif o == "*":
nb = op[o]
par += nb * self.res.IL["*"]
elif o == "/":
nb = op[o]
par += nb * self.res.IL["/"]
if par == 0:
par = 1 # assignement
param.append(f"IL_par_S{k} = {par};")
param.append(f"IL_seq_S{k} = {seq};")
DSP_used = {}
for k in range(len(self.schedule)):
dsp_used = 0
DSP_used[k] = 0
op = self.analysis.operations[k]
for o in op:
if o == "+":
nb = op[o]
dsp_used += nb * self.res.DSP_per_operation["+"]
elif o == "-":
nb = op[o]
dsp_used += nb * self.res.DSP_per_operation["-"]
elif o == "*":
nb = op[o]
dsp_used += nb * self.res.DSP_per_operation["*"]
elif o == "/":
nb = op[o]
dsp_used += nb * self.res.DSP_per_operation["/"]
DSP_used[k] = dsp_used
param.append(f"DSP_S{k} = {dsp_used};")
return param
def add_variables(self):
var = []
for k in list(self.TC.keys()):
tc = []
tc_ori = self.TC[k]
tc_ori_16 = 1
for j in range(tc_ori, tc_ori*2):
if j % 16 == 0:
tc_ori_16 = j
break
var.append(f"TC{k} integer >= {tc_ori} <= {tc_ori_16};")
what_is_fuse = self.what_is_fuse()
for k in range(len(what_is_fuse)):
for id_slr in range(self.res.SLR):
var.append(f"is_fused_task{k}_in_SLR_{id_slr} binary;")
return var
def create_nlp(self):
var = self.add_variables()
constraints = []
obj = []
comments = []
tot_buffer = []
tot_buffer_per_fused_task = {}
obj_latency_computation = []
param = self.add_parameters()
perms = {}
what_is_fuse = self.what_is_fuse()
for is_fuse in what_is_fuse:
comments.append(f"Fuse {is_fuse}")
for k in range(len(what_is_fuse)):
cons = []
for id_slr in range(self.res.SLR):
cons.append(f"is_fused_task{k}_in_SLR_{id_slr}")
constraints.append(f"{' + '.join(cons)} = 1; # only one SLR for fused task {k}")
write_dic = {}
what_statement_should_write = []
ll_array = []
for k in range(len(self.schedule)):
w = self.analysis.dic[k]["write"][0]
array = w.split("[")[0]
write_dic[k] = array
ll_array.append(array)
ll_array = list(set(ll_array))
for array in ll_array:
last_one = 0
for k in range(len(self.schedule)):
if write_dic[k] == array:
last_one = k
what_statement_should_write.append(last_one)
comments.append(f"Task {last_one} writes {array} to off-chip")
lat_comp_per_stat = {}
for k in range(len(self.schedule)):
str_ = f"Statement {k}: {self.statements[k]}"
if str_ not in comments:
comments.append(str_)
for k in range(len(self.iterators)):
str_ = f"Loop_{k}: {self.iterators[k]}"
if str_ not in comments:
comments.append(str_)
for k in range(len(self.arguments)):
str_ = f"Argument {k}: {self.arguments[k]}"
if str_ not in comments:
comments.append(str_)
for k in range(len(self.schedule)):
perms[k] = []
loops = self.schedule[k][1::2]
all_perms = []
all_perms1 = list(permutations(loops)) # for the two splited loops
# all_perms2 = list(permutations(loops)) # for the two splited loops
# for perm1 in all_perms1:
# for perm2 in all_perms2:
# all_perms.append(perm1 + perm2)
all_perms = all_perms1.copy()
# all_perms_ = list(permutations(loops + loops))
# for perm in all_perms_:
# if perm not in all_perms:
# all_perms.append(perm)
possibilities = []
curr_cons = []
tot_latency = []
for i, perm in enumerate(all_perms):
perms[k].append(perm)
perm_str = [k]
for p in perm:
perm_str.append(p)
perm_str.append(0)
# for second tile level
for p in perm:
perm_str.append(p)
perm_str.append(0)
var.append(f"perm{i}_S{k} binary; # {perm_str}")
possibilities.append(f"perm{i}_S{k}")
curr_loop = list(perm)
curr_TC = []
last_loop = curr_loop[-1]
if self.red_loop[last_loop]:
II = f"II_S{k}_seq"
else:
II = f"II_S{k}_par"
for r, loop in enumerate(curr_loop[:-1]):
curr_TC.append(f"TC{loop}_{self.give_index(curr_loop, loop, r)}")
tot_latency += [f"perm{i}_S{k} * (IL_par_S{k} + IL_seq_S{k} + {II} * (TC{last_loop}_1 - 1)) * {' * '.join(curr_TC)}"]
next_statements = []
arr_dep_for_each_statement = []
succesors = False
for k2 in range(len(self.matrix_graph)):
if k2 > k:
if self.matrix_graph[k+1][k2]==1:
succesors = True
next_statements.append(k2-1)
curr_arr_dep_for_each_statement = []
read_k = self.info_loops[k]["read"]
write_k = self.info_loops[k]["write"]
read_k2 = self.info_loops[k2-1]["read"]
write_k2 = self.info_loops[k2-1]["write"]
# randw_k = read_k + write_k
randw_k2 = read_k2 + write_k2
randw_k = write_k
# randw_k2 = write_k2
for r_k in randw_k:
for r_k2 in randw_k2:
if r_k.split("[")[0] == r_k2.split("[")[0]:
if r_k.split("[")[0] not in curr_arr_dep_for_each_statement:
curr_arr_dep_for_each_statement.append(r_k.split("[")[0])
same_fused_task = False
for fused_task in what_is_fuse:
if k in fused_task and k2-1 in fused_task:
same_fused_task = True
break
if not same_fused_task:
str_1 = f"Task {k} gives {r_k.split('[')[0]} to Task {k2-1}"
str_2 = f"Task {k2-1} received {r_k.split('[')[0]} from Task {k}"
if str_1 not in comments:
comments.append(str_1)
if str_2 not in comments:
comments.append(str_2)
# we need to force the tiling factor to be the same:
loops_1 = self.schedule[k][1::2]
loops_2 = self.schedule[k2-1][1::2]
it_1 = []
it_2 = []
l_1_per_dim = []
l_2_per_dim = []
w_1 = self.info_loops[k]["write"]
w_2 = self.info_loops[k2-1]["write"]
r_1 = self.info_loops[k]["read"]
r_2 = self.info_loops[k2-1]["read"]
for r__1 in r_1+w_1:
if r_k.split("[")[0] in r__1:
it_1 = self.extract_iterators(r__1)
break
for r__2 in r_2+w_2:
if r_k2.split("[")[0] in r__2:
it_2 = self.extract_iterators(r__2)
break
for it__1 in it_1:
for l_1 in loops_1:
if self.iterators[l_1] == it__1:
if not self.red_loop[l_1]:
l_1_per_dim.append(l_1)
break
else:
l_1_per_dim.append(-1)
break
for it__2 in it_2:
for l_2 in loops_2:
if self.iterators[l_2] == it__2:
if not self.red_loop[l_2]:
l_2_per_dim.append(l_2)
break
else:
l_2_per_dim.append(-1)
break
for dd in range(len(l_1_per_dim)):
if l_1_per_dim[dd] != -1 and l_2_per_dim[dd] != -1:
constraints.append(f"TC{l_1_per_dim[dd]}_1 = TC{l_2_per_dim[dd]}_1; # same tiling factor")
# comments.append(f"Task {k} gives {r_k.split('[')[0]} to Task {k2-1}")
# comments.append(f"Task {k2-1} received {r_k.split('[')[0]} from Task {k}")
arr_dep_for_each_statement.append(curr_arr_dep_for_each_statement)
# if f"Lat_comp_S{k}_for_S{k2-1} >= 0;" not in var:
# var.append(f"Lat_comp_S{k}_for_S{k2-1} >= 0;")
# var.append(f"debit_S{k}_to_S{k2-1} >= 0;")
# var.append(f"debit_S{k2-1}_from_S{k} >= 0;")
arrays_to_give = []
is_write_in_the_current_statement = False
for r_k in randw_k:
for r_k2 in randw_k2:
if r_k.split("[")[0] == r_k2.split("[")[0]:
if r_k in write_k:
is_write_in_the_current_statement = True
if r_k.split("[")[0] not in arrays_to_give:
arrays_to_give.append(r_k.split("[")[0])
for j, cl in enumerate(curr_loop):
shift = ""
if self.red_loop[cl]:
# shift += np.prod([self.TC[cl_] for cl_ in curr_loop[j:]])
shift += " * ".join([f"TC{cl_}_0" for cl_ in curr_loop[j:]])
break
curr_cons = ["0"]
if f"Lat_comp_S{k}_for_S{k2-1}" not in list(lat_comp_per_stat.keys()):
if len(shift) > 0:
lat_comp_per_stat[f"Lat_comp_S{k}_for_S{k2-1}"] = [f"perm{i}_S{k} * {shift}" ]
else:
lat_comp_per_stat[f"Lat_comp_S{k}_for_S{k2-1}"] = [f"perm{i}_S{k}" ]
else:
if len(shift) > 0:
lat_comp_per_stat[f"Lat_comp_S{k}_for_S{k2-1}"] += [f"perm{i}_S{k} * {shift}" ]
else:
lat_comp_per_stat[f"Lat_comp_S{k}_for_S{k2-1}"] += [f"perm{i}_S{k}" ]
# constraints.append(f"{key} = {' + '.join(lat_comp_per_stat[key])}; # stall between task")
if not succesors:
if f"Lat_comp_S{k}_for_off_chip >= 0;" not in var:
var.append(f"Lat_comp_S{k}_for_off_chip >= 0;")
array_to_write = self.info_loops[k]["write"][0]
name_array = array_to_write.split("[")[0]
it = self.extract_iterators(array_to_write)
shift = []
for j, loop in enumerate(curr_loop):
if self.red_loop[loop]:
shift += [f"TC{cl_}_{self.give_index(curr_loop[j:], cl_, g)}" for g, cl_ in enumerate(curr_loop[j:])]
break
last_loop = curr_loop[-1]
if self.red_loop[last_loop]:
shift += [f"II_S{k}_seq"]
else:
shift += [f"II_S{k}_par"]
# IO
read = self.info_loops[k]["read"]
write = self.info_loops[k]["write"]
randw = read + write
io_ = []
for r in randw:
its = self.extract_iterators(r)
for it in its:
for ll in curr_loop:
if self.iterators[ll] == it:
io_ += [f"TC{ll}"]
break
time_btw_copy = []
# shift = f"max(1, {shift})"
if f"Lat_comp_S{k}_for_off_chip" not in list(lat_comp_per_stat.keys()):
lat_comp_per_stat[f"Lat_comp_S{k}_for_off_chip"] = [f"perm{i}_S{k} * {' * '.join(shift)}" ]
else:
lat_comp_per_stat[f"Lat_comp_S{k}_for_off_chip"] += [f"perm{i}_S{k} * {' * '.join(shift)}" ]
for j, cl in enumerate(curr_loop):
shift = 0
if self.red_loop[cl]:
shift += np.prod([self.TC[cl_] for cl_ in curr_loop[j:]])
break
curr_cons.append(f"perm{i}_S{k} * {shift}")
# constraints.append(f"Lat_comp_S{k} = {' + '.join(curr_cons)}; # stall between task")
constraints.append(f"{' + '.join(possibilities)} = 1; # only one permutation")
# constraints.append(f"tot_latency_S{k} = {' + '.join(tot_latency)}; # total latency of the task")
# DONE intra-tile latency
for k in range(len(self.schedule)):
var.append(f"Lat_comp_S{k}_intra_tile >= 0;")
loops = self.schedule[k][1::2]
red_prod = []
for loop in loops:
if self.red_loop[loop]:
red_prod.append(f"TC{loop}_1")
if len(red_prod) > 0:
constraints.append(f"Lat_comp_S{k}_intra_tile = IL_par_S{k} + IL_seq_S{k} * log({' * '.join(red_prod)})/log(2); # latency of the intra-tile S{k}")
else:
constraints.append(f"Lat_comp_S{k}_intra_tile = IL_par_S{k} + IL_seq_S{k}; # latency of the intra-tile S{k}")
# TODO constraint on perm for fused task
# fuse task have the same output
to_zero = []
for id_fused_task, fused_task in enumerate(what_is_fuse):
list_iterator_of_output = []
for task in fused_task:
list_iterator_of_output.append(self.extract_iterators(self.info_loops[task]["write"][0]))
# we need output stationnary
n = len(list_iterator_of_output[0]) # number of dimension of output
for j, task in enumerate(fused_task):
loop_iterate_output = list_iterator_of_output[j]
loops = self.schedule[task][1::2]
loops_which_iterate = []
for l in loops:
if self.iterators[l] in loop_iterate_output:
loops_which_iterate.append(l)
loops_which_iterate.sort()
for id_perm, pp in enumerate(perms[task]):
begin_perm = list(pp[:len(loops_which_iterate)])
begin_perm.sort()
if begin_perm == loops_which_iterate:
pass
else:
constraints.append(f"perm{id_perm}_S{task} = 0; # because of the fused task {id_fused_task}")
to_zero.append(f"perm{id_perm}_S{task}")
# fused_task should have same schedule to iterate output
for id_fused_task, fused_task in enumerate(what_is_fuse):
output_nb_dim = self.info_loops[fused_task[0]]["write"][0].count("[")
pos_it = [d for d in range(output_nb_dim)]
# factorielle
all_pos_it = list(permutations(pos_it))
for pp in all_pos_it:
matched = []
for task in fused_task:
for id_perm, perm in enumerate(perms[task]):
if f"perm{id_perm}_S{task}" not in to_zero:
convert_to_output_order = []
it = self.extract_iterators(self.info_loops[task]["write"][0])
for id_loop, loop in enumerate(perm):
for r, it_ in enumerate(it):
if self.iterators[loop] == it_:
it[r] = id_loop
if it == list(pp[:len(it)]):
matched.append(f"perm{id_perm}_S{task}")
if len(matched) > 1:
all_pair = list(combinations(matched, 2))
for pair in all_pair:
constraints.append(f"{pair[0]} = {pair[1]}; # same iteration of output in FT {id_fused_task}")
arr_per_stat_fused = {}
for key in list(self.analysis.dic.keys()):
read = self.analysis.dic[key]["read"]
write = self.analysis.dic[key]["write"]
# reduce in order
randw = []
for r in read:
if r not in randw:
randw.append(r)
for w in write:
if w not in randw:
randw.append(w)
for r in randw:
it = self.extract_iterators(r)
tc = []
for loop in self.schedule[key][1::2]:
if self.iterators[loop] in it:
tc += [f"TC{loop}_1"]
if len(tc)>0:
r = r.split("[")[0]
if r not in list(arr_per_stat_fused.keys()):
arr_per_stat_fused[r] = []
arr_per_stat_fused[r] += [key]
name_var_footprint_fused = {}
for fused_task in what_is_fuse:
for task in fused_task:
name_var_footprint_fused[task] = {}
for arr in list(arr_per_stat_fused.keys()):
if task in arr_per_stat_fused[arr]:
name_var_footprint_fused[task][arr] = ""
for id_fused_task, fused_task in enumerate(what_is_fuse):
array_in_commun = {}
for arr in list(arr_per_stat_fused.keys()):
iterate_arr = arr_per_stat_fused[arr]
if len(iterate_arr) == 1 and iterate_arr[0] in fused_task:
array_in_commun[arr] = arr_per_stat_fused[arr]
else:
for ite in iterate_arr:
if ite in fused_task:
if arr not in array_in_commun:
array_in_commun[arr] = []
array_in_commun[arr].append(ite)
for arr in list(array_in_commun.keys()):
name = ""
for n in array_in_commun[arr]:
name += f"S{n}_"
name = name[:-1]
tot_buffer += [f"footprint_{arr}_{name}_reuse"]
if id_fused_task not in list(tot_buffer_per_fused_task.keys()):
tot_buffer_per_fused_task[id_fused_task] = []
tot_buffer_per_fused_task[id_fused_task].append(f"footprint_{arr}_{name}_reuse")
for n in range(len(array_in_commun[arr])):
name_var_footprint_fused[array_in_commun[arr][n]][arr] = f"footprint_{arr}_{name}"
var.append(f"footprint_{arr}_{name} integer >= 0;")
var.append(f"footprint_{arr}_{name}_reuse integer >= 0;")
#per SLR
for id_slr in range(self.res.SLR):
cons = []
for id_fused_task, fused_task in enumerate(what_is_fuse):
cons_str = f"is_fused_task{id_fused_task}_in_SLR_{id_slr} * ("
cons_str += " + ".join(tot_buffer_per_fused_task[id_fused_task])
cons_str += ")"
cons.append(cons_str)
constraints.append(f"{' + '.join(cons)} <= SLR{id_slr}_mem; # memory constraint per SLR")
###
for id_fused_task, fused_task in enumerate(what_is_fuse):
name = ""
for task in fused_task:
name += f"S{task}_"
name = name[:-1]
var.append(f"Lat_comp_fused_{name} >= 0;")
lat = []
# for now it is reduce to parallel loop
max_loop = 0
max_loop = len(self.extract_iterators(self.info_loops[fused_task[0]]["write"][0]))
# for task in fused_task:
# loops = self.schedule[task][1::2]
# if len(loops) > max_loop:
# max_loop = len(loops)
all_array_for_this_fused_task = []
for task in fused_task:
tmp_lat = ["Lat_comp_S"+str(task)+"_intra_tile"]
all_array_for_this_task = []
it_for_this_task = {}
read = self.info_loops[task]["read"]
write = self.info_loops[task]["write"]
randw = read + write
# loops which iterate output can't be pipeline
for r in randw:
if "[0]" in r or "[" not in r:
pass
elif r.split("[")[0] not in all_array_for_this_task:
all_array_for_this_task.append(r.split("[")[0])
if r.split("[")[0] not in all_array_for_this_fused_task:
all_array_for_this_fused_task.append(r.split("[")[0])
if r.split("[")[0] not in list(it_for_this_task.keys()):
it_for_this_task[r.split("[")[0]] = {}
it = self.extract_iterators(r)
it_for_this_task[r.split("[")[0]][task] = it
for arr in all_array_for_this_task:
l1 = []
l2 = []
no_reuse = True
it = it_for_this_task[arr][task]
for loop in self.schedule[task][1::2][:max_loop]:
if self.iterators[loop] not in it:
no_reuse = False
break
for nb in range(max_loop+1):
str_1 = f"level_transfer_{arr}_FT{id_fused_task}_under{nb} binary;" # for latency
# 0 it is full transfer
# 1 under first loop
# etc
str_2 = f"level_reuse_{arr}_FT{id_fused_task}_under{nb} binary;" # for mem on chip
if str_1 not in var:
var.append(str_1)
l1 += [f"level_transfer_{arr}_FT{id_fused_task}_under{nb}"]
if str_2 not in var:
var.append(str_2)
l2 += [f"level_reuse_{arr}_FT{id_fused_task}_under{nb}"]
l_ = []
for nb2 in range(nb+1):
l_.append(f"level_reuse_{arr}_FT{id_fused_task}_under{nb2}")
# if arr in write[0] or no_reuse:
if no_reuse:
constraints.append(f"level_reuse_{arr}_FT{id_fused_task}_under{nb} = level_transfer_{arr}_FT{id_fused_task}_under{nb}; # reuse level have to be outermost or equal to transfer")
else:
constraints.append(f"{' + '.join(l_)} >= level_transfer_{arr}_FT{id_fused_task}_under{nb}; # reuse level have to be outermost or equal to transfer")
if arr in write[0]: