-
Notifications
You must be signed in to change notification settings - Fork 24
/
matmul.py
1543 lines (1465 loc) · 62.2 KB
/
matmul.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
from utils import size
from typing import List, Tuple
from hardware_model.device import Device
from software_model.operators import Operator
from software_model.utils import Tensor, DataType
from math import ceil, log2, floor
import torch
import time
import statistics
import numpy as np
import pandas as pd
import os
from scalesim.scale_sim import scalesim
import copy
class BatchedMatmul(Operator):
def __init__(self, data_type: DataType):
super().__init__(0, 0, 0, 0, data_type)
self.input1_shape = None
self.input2_shape = None
self.output_shape = None
def __call__(self, input1: Tensor, input2: Tensor) -> Tensor:
# [b, M, K] * [b, K, N] = [b, M, N]
assert self.data_type == input1.data_type
assert self.data_type == input2.data_type
self.input1_shape = input1.shape
self.input2_shape = input2.shape
assert size(self.input1_shape[:-2]) == size(self.input2_shape[:-2])
self.bs = size(self.input1_shape[:-2])
self.M = self.input1_shape[-2]
self.K = self.input1_shape[-1]
assert self.input2_shape[-2] == self.K
self.N = self.input2_shape[-1]
self.output_shape = self.input1_shape[:-2] + [self.M, self.N]
output = Tensor(self.output_shape, self.data_type)
return output
def roofline_model(self, pcb_module: Device):
matmul = Matmul(self.data_type)
_ = matmul(Tensor([self.M, self.K]), Tensor([self.K, self.N]))
matmul_latency = matmul.roofline_model(pcb_module)
self.roofline_latency = matmul_latency * self.bs
return self.roofline_latency
# def compile_and_simulate(self, pcb_module: Device, compile_mode: str):
# matmul = Matmul(self.data_type)
# _ = matmul(Tensor([self.M, self.K]), Tensor([self.K, self.N]))
# matmul_latency = (
# matmul.compile_and_simulate(pcb_module, compile_mode)
# # - pcb_module.io_module.latency * 2
# )
# self.latency = matmul_latency * self.bs # + pcb_module.io_module.latency * 2
# return self.latency
def compile_and_simulate(self, pcb_module: Device, compile_mode: str):
matmul = Matmul(self.data_type)
_ = matmul(Tensor([self.M, self.K]), Tensor([self.K, self.N]))
matmul_latency1 = (
matmul.compile_and_simulate(pcb_module, compile_mode) * self.bs
)
matmul = Matmul(self.data_type)
_ = matmul(
Tensor([self.M, self.K * self.bs]), Tensor([self.K * self.bs, self.N])
)
matmul_latency2 = (
matmul.compile_and_simulate(pcb_module, compile_mode)
+ (self.bs - 1)
* self.M
* self.N
* self.data_type.word_size
/ pcb_module.io_module.bandwidth
)
self.latency = min(matmul_latency1, matmul_latency2)
return self.latency
def run_on_gpu(
self,
):
input1 = torch.randn(self.bs, self.M, self.K, dtype=torch.float16).cuda()
input2 = torch.randn(self.bs, self.K, self.N, dtype=torch.float16).cuda()
latencies = []
# warmup
for _ in range(3):
_ = torch.bmm(input1, input2)
torch.cuda.synchronize()
for _ in range(self.iterations):
start = time.time()
output = torch.bmm(input1, input2)
torch.cuda.synchronize()
end = time.time()
latencies.append(end - start)
self.latency_on_gpu = (
statistics.median(latencies)
# - self.gpu_kernel_launch_overhead()
# - 4e-5
# min(latencies) - 8e-6
) # GPU launch kernel overhead and PyTorch overhead
return self.latency_on_gpu
@staticmethod
def gpu_kernel_launch_overhead():
latencies = []
for _ in range(50):
a = torch.randn(1, 1, 1, device="cuda")
b = torch.randn(1, 1, 1, device="cuda")
torch.cuda.synchronize()
start = time.time()
c = torch.bmm(a, b)
torch.cuda.synchronize()
end = time.time()
latencies.append(end - start)
avg_overhead = statistics.median(latencies)
# print('GPU kernel launch overhead: ', avg_overhead*1e3, 'ms')
# print(latencies)
return avg_overhead
class Matmul(Operator):
def __init__(self, data_type: DataType):
super().__init__(0, 0, 0, 0, data_type)
self.input1_shape = None
self.input2_shape = None
self.output_shape = None
self.look_up_table = None
self.best_mapping = None
def __call__(self, input1: Tensor, input2: Tensor) -> Tensor:
# [bs, M, K] * [K, N] = [bs, M, N]
assert self.data_type == input1.data_type
assert self.data_type == input2.data_type
self.input1_shape = input1.shape
self.input2_shape = input2.shape
self.M = size(self.input1_shape[:-1])
self.K = self.input1_shape[-1]
assert self.input2_shape[-2] == self.K
self.N = self.input2_shape[-1]
if len(self.input1_shape) == 2:
self.output_shape = [self.M, self.N]
else:
self.output_shape = self.input1_shape[:-1] + [self.N]
output = Tensor(self.output_shape, self.data_type)
self.computational_graph = self.ComputationalGraph(
self.M, self.N, self.K, self.data_type
)
self.flop_count = 2 * self.M * self.K * self.N
self.io_count = self.M * self.K + self.K * self.N + self.M * self.N
# print(f'{self.M}, {self.N}, {self.K}')
return output
def roofline_model(self, pcb_module: Device):
self.roofline_latency = max(
self.flop_count / pcb_module.compute_module.total_systolic_array_flops,
self.io_count
/ min(
pcb_module.io_module.bandwidth,
pcb_module.compute_module.l2_bandwidth_per_cycle
* pcb_module.compute_module.clock_freq,
),
)
return self.roofline_latency
def print_latency(self):
print(
f"{self.computational_graph.M}, {self.computational_graph.N}, {self.computational_graph.K}, {self.best_latency*1e3:.4f}ms, {self.latency_on_gpu*1e3:.4f}ms, {self.best_latency/self.latency_on_gpu*100:.2f}%",
flush=True,
)
@staticmethod
def generate_tile_loops(loop_M: int, loop_N: int, loop_K: int, loop_order: str):
assert loop_order in ["mkn", "mnk", "nkm", "nmk", "knm", "kmn"]
if loop_order == "mnk":
for m in range(loop_M):
for n in range(loop_N):
for k in range(loop_K):
yield m, n, k
elif loop_order == "mkn":
for m in range(loop_M):
for k in range(loop_K):
for n in range(loop_N):
yield m, n, k
elif loop_order == "nmk":
for n in range(loop_N):
for m in range(loop_M):
for k in range(loop_K):
yield m, n, k
elif loop_order == "nkm":
for n in range(loop_N):
for k in range(loop_K):
for m in range(loop_M):
yield m, n, k
elif loop_order == "knm":
for k in range(loop_K):
for n in range(loop_N):
for m in range(loop_M):
yield m, n, k
elif loop_order == "kmn":
for k in range(loop_K):
for m in range(loop_M):
for n in range(loop_N):
yield m, n, k
class ComputationalGraph:
def __init__(self, M: int, N: int, K: int, data_type: DataType):
self.M = M
self.N = N
self.K = K
self.data_type = data_type
def display(self):
print("-" * 10 + " Computational Graph " + "-" * 10)
print(
f"M: {self.M}, N: {self.N}, K: {self.K}, word_size(B): {self.data_type.word_size}"
)
class Mapping:
def __init__(
self,
l2_tile_M: int,
l2_tile_N: int,
l2_tile_K: int,
is_l2_double_buffering: bool,
l1_tile_M: int,
l1_tile_N: int,
l1_tile_K: int,
l2_loop_order: str,
l1_loop_order: str,
l0_M_tiling_factor: int,
l0_N_tiling_factor: int,
l0_K_tiling_factor: int,
dataflow: str = "os",
):
self.l2_tile_M = l2_tile_M
self.l2_tile_N = l2_tile_N
self.l2_tile_K = l2_tile_K
self.is_l2_double_buffering = is_l2_double_buffering
self.l1_tile_M = l1_tile_M
self.l1_tile_N = l1_tile_N
self.l1_tile_K = l1_tile_K
self.l2_loop_order = l2_loop_order
self.l1_loop_order = l1_loop_order
self.l0_M_tiling_factor = l0_M_tiling_factor
self.l0_N_tiling_factor = l0_N_tiling_factor
self.l0_K_tiling_factor = l0_K_tiling_factor
self.dataflow = dataflow
def display(self):
print(f'{"-"*10} Mapping {"-"*10}')
print(
f"l2_tile_M: {self.l2_tile_M}, l2_tile_N: {self.l2_tile_N}, l2_tile_K: {self.l2_tile_K}, is_l2_double_buffering: {self.is_l2_double_buffering}, l2_loop_order: {self.l2_loop_order}"
)
print(
f"l1_tile_M: {self.l1_tile_M}, l1_tile_N: {self.l1_tile_N}, l1_tile_K: {self.l1_tile_K}, l1_loop_order: {self.l1_loop_order}"
)
print(
f"l0_M_tiling_factor: {self.l0_M_tiling_factor}, l0_N_tiling_factor: {self.l0_N_tiling_factor}, l0_K_tiling_factor: {self.l0_K_tiling_factor}"
)
@staticmethod
def find_permutations(n):
permutations = set()
for i in range(1, n + 1):
if n % i == 0:
for j in range(1, n + 1):
if (n // i) % j == 0:
k = n // (i * j)
permutations.add((i, j, k))
return list(permutations)
def compile_and_simulate(
self,
pcb_module: Device,
compile_mode: str = "exhaustive",
):
min_cycle_count = 2**63 - 1
best_mapping = None
M = self.computational_graph.M
N = self.computational_graph.N
K = self.computational_graph.K
if (M == 1 or N == 1) and (
compile_mode == "heuristic-GPU"
or compile_mode == "heuristic-our-throughput"
):
working_set_size = M * K + N * K + M * N
total_io_count = working_set_size * self.data_type.word_size
io_latency = total_io_count / pcb_module.io_module.bandwidth
total_flop_count = 2 * M * N * K
compute_latency = (
total_flop_count
/ pcb_module.compute_module.core.vector_unit.total_vector_flops_per_cycle
/ pcb_module.compute_module.core_count
/ pcb_module.compute_module.clock_freq
)
self.latency = max(
compute_latency, io_latency
) # + pcb_module.io_module.latency * 2
return self.latency
if compile_mode == "exhaustive":
for l2_tile_M_log2 in range(5, ceil(log2(self.computational_graph.M)) + 1):
l2_tile_M = 2**l2_tile_M_log2
for l2_tile_N_log2 in range(
5, ceil(log2(self.computational_graph.N)) + 1
):
l2_tile_N = 2**l2_tile_N_log2
for l2_tile_K_log2 in range(
5, ceil(log2(self.computational_graph.K)) + 1
):
l2_tile_K = 2**l2_tile_K_log2
working_set_size = (
l2_tile_N * l2_tile_K
+ l2_tile_M * l2_tile_K
+ l2_tile_M * l2_tile_N
)
if (
working_set_size
> pcb_module.compute_module.l2_size
// self.data_type.word_size
):
continue
elif (
working_set_size
<= pcb_module.compute_module.l2_size
// self.data_type.word_size
// 2
):
is_l2_double_buffering = True
else:
is_l2_double_buffering = False
for l1_tile_M_log2 in range(5, l2_tile_M_log2 + 1):
l1_tile_M = 2**l1_tile_M_log2
for l1_tile_N_log2 in range(5, l2_tile_N_log2 + 1):
l1_tile_N = 2**l1_tile_N_log2
for l1_tile_K_log2 in range(5, l2_tile_K_log2 + 1):
l1_tile_K = 2**l1_tile_K_log2
if (
l1_tile_M * l1_tile_N
+ l1_tile_N * l1_tile_K
+ l1_tile_M * l1_tile_K
> pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
):
continue
for l2_loop_order in [
"mkn",
"mnk",
"nkm",
"nmk",
"knm",
"kmn",
]:
for l1_loop_order in [
"mkn",
"mnk",
"nkm",
"nmk",
"knm",
"kmn",
]:
for (
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
) in self.find_permutations(
pcb_module.compute_module.core.systolic_array_count
):
mapping = self.Mapping(
l2_tile_M,
l2_tile_N,
l2_tile_K,
is_l2_double_buffering,
l1_tile_M,
l1_tile_N,
l1_tile_K,
l2_loop_order,
l1_loop_order,
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
)
cycle_count = self.simulate(
self.computational_graph,
mapping,
pcb_module,
)
if cycle_count < min_cycle_count:
min_cycle_count = cycle_count
best_mapping = mapping
elif compile_mode == "heuristic-our-throughput":
i = 0
for l2_tile_M in [32, 64, 128, 256, 512, 1024, 2048, 4096]:
for l2_tile_N in [
l2_tile_M // 4,
l2_tile_M // 2,
l2_tile_M,
l2_tile_M * 2,
l2_tile_M * 4,
l2_tile_M * 8,
l2_tile_M * 16,
l2_tile_M * 32,
]:
l2_tile_K_max = (
pcb_module.compute_module.l2_size
// self.data_type.word_size
// 2
- l2_tile_M * l2_tile_N
) // (l2_tile_M + l2_tile_N)
if l2_tile_K_max < 1:
continue
l2_tile_K = min(l2_tile_K_max, K)
l2_tile_K = floor(log2(l2_tile_K))
l2_tile_K = 2**l2_tile_K
working_set_size = (
l2_tile_N * l2_tile_K
+ l2_tile_M * l2_tile_K
+ l2_tile_M * l2_tile_N
)
if (
working_set_size
> pcb_module.compute_module.l2_size // self.data_type.word_size
):
continue
elif (
working_set_size
<= pcb_module.compute_module.l2_size
// self.data_type.word_size
// 2
):
is_l2_double_buffering = True
else:
is_l2_double_buffering = False
assert is_l2_double_buffering
for l1_tile_M in [32, 64, 128, 256]:
l1_tile_M = min(l1_tile_M, l2_tile_M, l2_tile_N)
# if l1_tile_M > min(l2_tile_M, l2_tile_N):
# continue
l1_tile_N = l1_tile_M
l1_tile_K_max = (
pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
- l1_tile_M * l1_tile_N
) // (l1_tile_M + l1_tile_N)
if l1_tile_K_max < 1:
continue
l1_tile_K = min(l1_tile_K_max, l2_tile_K)
l1_tile_K = floor(log2(l1_tile_K))
l1_tile_K = 2**l1_tile_K
if (
l1_tile_M * l1_tile_N
+ l1_tile_N * l1_tile_K
+ l1_tile_M * l1_tile_K
> pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
):
continue
l2_loop_order = "knm"
l1_loop_order = "knm"
for (
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
) in [(2, 2, 1)]:
# self.find_permutations(
# pcb_module.compute_module.core.systolic_array_count
# ):
i += 1
# start = time.time()
mapping = self.Mapping(
l2_tile_M,
l2_tile_N,
l2_tile_K,
is_l2_double_buffering,
l1_tile_M,
l1_tile_N,
l1_tile_K,
l2_loop_order,
l1_loop_order,
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
)
cycle_count = self.simulate(
self.computational_graph,
mapping,
pcb_module,
)
# end = time.time()
# if i % 1000 == 0:
# print(f"{i} simulation time: {end-start}")
if cycle_count < min_cycle_count:
min_cycle_count = cycle_count
best_mapping = mapping
elif compile_mode == "heuristic-GPU":
i = 0
for l2_tile_M in [64, 128, 256, 512, 1024, 2048]:
for l2_tile_N in [l2_tile_M // 2, l2_tile_M, l2_tile_M * 2]:
if K <= 12288:
l2_K_tiling_factor_list = [1, 2, 4, 8]
else:
l2_K_tiling_factor_list = [
K // 1024,
K // 2048,
K // 4096,
K // 8192,
]
for l2_K_tiling_factor in l2_K_tiling_factor_list:
l2_tile_K = ceil(
self.computational_graph.K / l2_K_tiling_factor
)
l2_tile_K = 2 ** floor(log2(l2_tile_K))
working_set_size = (
l2_tile_N * l2_tile_K
+ l2_tile_M * l2_tile_K
+ l2_tile_M * l2_tile_N
)
if (
working_set_size
> pcb_module.compute_module.l2_size
// self.data_type.word_size
):
continue
elif (
working_set_size
<= pcb_module.compute_module.l2_size
// self.data_type.word_size
// 2
):
is_l2_double_buffering = True
else:
is_l2_double_buffering = False
for l1_tile_M in [32, 64, 128, 256]:
if l1_tile_M > min(l2_tile_M, l2_tile_N):
continue
l1_tile_N = l1_tile_M
for l1_K_tiling_factor in [1, 2, 4, 8, 16, 32]:
l1_tile_K = ceil(l2_tile_K / l1_K_tiling_factor)
if (
l1_tile_M * l1_tile_N
+ l1_tile_N * l1_tile_K
+ l1_tile_M * l1_tile_K
> pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
):
continue
l2_loop_order = "knm"
l1_loop_order = "knm"
for (
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
) in self.find_permutations(
pcb_module.compute_module.core.systolic_array_count
):
i += 1
start = time.time()
mapping = self.Mapping(
l2_tile_M,
l2_tile_N,
l2_tile_K,
is_l2_double_buffering,
l1_tile_M,
l1_tile_N,
l1_tile_K,
l2_loop_order,
l1_loop_order,
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
)
cycle_count = self.simulate(
self.computational_graph,
mapping,
pcb_module,
)
end = time.time()
# if i % 1000 == 0:
# print(f"{i} simulation time: {end-start}")
if cycle_count < min_cycle_count:
min_cycle_count = cycle_count
best_mapping = mapping
# print("total dse times:", i)
elif compile_mode == "heuristic-TPU":
l2_tile_M = self.computational_graph.M
l2_tile_N = self.computational_graph.N
l2_tile_K = self.computational_graph.K
is_l2_double_buffering = True
for l1_tile_M in [l2_tile_M, 64, 128, 256, 512, 1024, 2048, 4096, 8192]:
if l1_tile_M > l2_tile_M * 2:
continue
for l1_tile_N in [
l1_tile_M // 2,
l1_tile_M,
l1_tile_M * 2,
l1_tile_M * 8,
l1_tile_M * 16,
l1_tile_M * 64,
l1_tile_M * 128,
l1_tile_M * 256,
]:
if l1_tile_N > l2_tile_N:
continue
if l1_tile_N <= 0:
continue
l1_tile_K_max = (
pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
- l1_tile_M * l1_tile_N
) // (l1_tile_M + l1_tile_N)
if l1_tile_K_max < 1:
continue
l1_tile_K = min(l1_tile_K_max, l2_tile_K)
l1_tile_K = floor(log2(l1_tile_K))
l1_tile_K = 2**l1_tile_K
l2_loop_order = "knm"
l1_loop_order = "knm"
for (
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
) in [(1, 2, 1)]:
mapping = self.Mapping(
l2_tile_M,
l2_tile_N,
l2_tile_K,
is_l2_double_buffering,
l1_tile_M,
l1_tile_N,
l1_tile_K,
l2_loop_order,
l1_loop_order,
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
)
# mapping.display()
# start=time.time()
cycle_count = self.simulate(
self.computational_graph,
mapping,
pcb_module,
)
# end=time.time()
# print(f'simulation time: {end-start}')
if cycle_count < min_cycle_count:
min_cycle_count = cycle_count
best_mapping = mapping
elif compile_mode == "heuristic-TPU-new":
l2_tile_M = self.computational_graph.M
l2_tile_N = self.computational_graph.N
l2_tile_K = self.computational_graph.K
is_l2_double_buffering = True
for l1_tile_M in [l2_tile_M, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192]:
if l1_tile_M > l2_tile_M * 2:
continue
for l1_tile_N in [
l1_tile_M // 2,
l1_tile_M,
l1_tile_M * 2,
l1_tile_M * 8,
l1_tile_M * 16,
l1_tile_M * 64,
l1_tile_M * 128,
l1_tile_M * 256,
]:
if l1_tile_N > l2_tile_N:
continue
if l1_tile_N <= 0:
continue
l1_tile_K_max = (
pcb_module.compute_module.core.SRAM_size
// self.data_type.word_size
// 2
- l1_tile_M * l1_tile_N
) // (l1_tile_M + l1_tile_N)
if l1_tile_K_max < 1:
continue
l1_tile_K = min(l1_tile_K_max, l2_tile_K)
l1_tile_K = floor(log2(l1_tile_K))
l1_tile_K = 2**l1_tile_K
l2_loop_order = "knm"
l1_loop_order = "knm"
for (
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
) in [(1, 1, 1)]:
mapping = self.Mapping(
l2_tile_M,
l2_tile_N,
l2_tile_K,
is_l2_double_buffering,
l1_tile_M,
l1_tile_N,
l1_tile_K,
l2_loop_order,
l1_loop_order,
l0_M_tiling_factor,
l0_N_tiling_factor,
l0_K_tiling_factor,
)
# mapping.display()
# start=time.time()
cycle_count = self.simulate(
self.computational_graph,
mapping,
pcb_module,
)
# end=time.time()
# print(f'simulation time: {end-start}')
if cycle_count < min_cycle_count:
min_cycle_count = cycle_count
best_mapping = mapping
else:
raise ValueError(f"compile_mode {compile_mode} not supported")
self.best_mapping = best_mapping
# if self.best_mapping is not None:
# self.best_mapping.display()
self.best_cycle_count = min_cycle_count
self.best_latency = min_cycle_count / pcb_module.compute_module.clock_freq
self.latency = self.best_latency
# self.best_mapping.display()
return self.latency
def simulate(
self,
computational_graph: ComputationalGraph,
mapping: Mapping,
pcb_module: Device,
) -> int:
if self.look_up_table is None:
self.look_up_table = pd.read_csv(
f"./systolic_array_model/look_up_table_{pcb_module.compute_module.core.systolic_array.array_height}_{pcb_module.compute_module.core.systolic_array.array_width}.csv",
header=None,
names=[
"M",
"N",
"K",
"ArrayHeight",
"ArrayWidth",
"Dataflow",
"cycle_count",
"util_rate",
],
)
self.look_up_table.drop_duplicates(
inplace=True,
subset=["M", "N", "K", "ArrayHeight", "ArrayWidth", "Dataflow"],
)
# self.look_up_table.reset_index(drop=True, inplace=True)
# self.look_up_table.to_csv(
# f"./systolic_array_model/look_up_table_{pcb_module.compute_module.core.systolic_array.array_height}_{pcb_module.compute_module.core.systolic_array.array_width}.csv",
# header=False,
# index=False,
# )
self.look_up_table.set_index(
["M", "N", "K", "ArrayHeight", "ArrayWidth", "Dataflow"],
inplace=True,
)
# print(self.look_up_table)
# print(self.look_up_table.loc[(32, 16, 256, 16, 16, 'os'), "cycle_count"
# ].item())
# print('sdfsdfsdfsd')
# exit()
M = computational_graph.M
N = computational_graph.N
K = computational_graph.K
data_type = computational_graph.data_type
l2_tile_M = mapping.l2_tile_M
l2_tile_N = mapping.l2_tile_N
l2_tile_K = mapping.l2_tile_K
if mapping.is_l2_double_buffering:
assert (
l2_tile_M * l2_tile_N + l2_tile_N * l2_tile_K + l2_tile_M * l2_tile_K
<= pcb_module.compute_module.l2_size // self.data_type.word_size // 2
)
else:
assert (
l2_tile_M * l2_tile_N + l2_tile_N * l2_tile_K + l2_tile_M * l2_tile_K
<= pcb_module.compute_module.l2_size // self.data_type.word_size
)
M_l2_t = M // l2_tile_M
N_l2_t = N // l2_tile_N
K_l2_t = K // l2_tile_K
M_remain = M % l2_tile_M
N_remain = N % l2_tile_N
K_remain = K % l2_tile_K
l2_tiles = np.empty(
[ceil(M / l2_tile_M), ceil(N / l2_tile_N), ceil(K / l2_tile_K)],
dtype=self.L2TileSimulator,
)
# print('-'*20)
# print(l2_tiles.shape)
if M_l2_t * N_l2_t * K_l2_t != 0:
l2_tiles[:M_l2_t, :N_l2_t, :K_l2_t] = self.L2TileSimulator(
l2_tile_M,
l2_tile_N,
l2_tile_K,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if M_remain != 0:
l2_tiles[-1, :N_l2_t, :K_l2_t] = self.L2TileSimulator(
M_remain,
l2_tile_N,
l2_tile_K,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if N_remain != 0:
l2_tiles[:M_l2_t, -1, :K_l2_t] = self.L2TileSimulator(
l2_tile_M,
N_remain,
l2_tile_K,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if K_remain != 0:
l2_tiles[:M_l2_t, :N_l2_t, -1] = self.L2TileSimulator(
l2_tile_M,
l2_tile_N,
K_remain,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if M_remain * N_remain != 0:
l2_tiles[-1, -1, :K_l2_t] = self.L2TileSimulator(
M_remain,
N_remain,
l2_tile_K,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if M_remain * K_remain != 0:
l2_tiles[-1, :N_l2_t, -1] = self.L2TileSimulator(
M_remain,
l2_tile_N,
K_remain,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if N_remain * K_remain != 0:
l2_tiles[:M_l2_t, -1, -1] = self.L2TileSimulator(
l2_tile_M,
N_remain,
K_remain,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
if M_remain * N_remain * K_remain != 0:
l2_tiles[-1, -1, -1] = self.L2TileSimulator(
M_remain,
N_remain,
K_remain,
data_type,
mapping,
pcb_module,
self.look_up_table,
)
total_cycle_count = 0
total_cycle_count += (
l2_tiles[0, 0, 0].M_K_io_cycle_count + l2_tiles[0, 0, 0].K_N_io_cycle_count
)
previous_m = 0
previous_n = 0
previous_k = 0
for m, n, k in self.generate_tile_loops(
ceil(M / l2_tile_M),
ceil(N / l2_tile_N),
ceil(K / l2_tile_K),
mapping.l2_loop_order,
):
if m == 0 and n == 0 and k == 0:
continue
l2_tile = l2_tiles[m, n, k]
previous_l2_tile = l2_tiles[previous_m, previous_n, previous_k]
# current tile read latency
if m == previous_m and k == previous_k:
current_tile_read_cycle_count = l2_tile.K_N_io_cycle_count
elif n == previous_n and k == previous_k:
current_tile_read_cycle_count = l2_tile.M_K_io_cycle_count
else:
current_tile_read_cycle_count = (
l2_tile.M_K_io_cycle_count + l2_tile.K_N_io_cycle_count
)
if k > 0 and not (m == previous_m and n == previous_n):
current_tile_read_cycle_count += l2_tile.M_N_io_cycle_count
# previous tile compute latency
previous_tile_compute_cycle_count = previous_l2_tile.compute_cycle_count
if k > 0:
previous_tile_compute_cycle_count += (
previous_l2_tile.K_reduction_cycle_count
)
# previous tile write latency
if m == previous_m and n == previous_n:
previous_tile_write_cycle_count = 0
else:
previous_tile_write_cycle_count = previous_l2_tile.M_N_io_cycle_count
# read current tile, compute previous tile, write previous tile
if mapping.is_l2_double_buffering: # pipelined
total_cycle_count += (
max(
current_tile_read_cycle_count, previous_tile_compute_cycle_count
)
+ previous_tile_write_cycle_count
)
else: # non-pipelined
total_cycle_count += (
current_tile_read_cycle_count
+ previous_tile_compute_cycle_count
+ previous_tile_write_cycle_count
)
previous_m = m
previous_n = n
previous_k = k
# compute and write last tile
total_cycle_count += (
l2_tiles[-1, -1, -1].M_N_io_cycle_count
+ l2_tiles[-1, -1, -1].compute_cycle_count
)
if previous_k > 0:
total_cycle_count += ceil(l2_tiles[-1, -1, -1].K_reduction_cycle_count)
return total_cycle_count #+ ceil(
# pcb_module.io_module.latency * 2 * pcb_module.compute_module.clock_freq
# )
class L2TileSimulator:
def __init__(
self,
M: int,
N: int,
K: int,
data_type: DataType,
mapping: "Matmul.Mapping",
pcb_module: Device,
look_up_table: pd.DataFrame,
):
# print(f'L2 tile: {M} {N} {K}')
self.M = M
self.N = N
self.K = K
self.K_reduction_cycle_count = ceil(
M * N / pcb_module.compute_module.total_vector_flops_per_cycle
) + 2 * ceil(
M
* N
* data_type.word_size
/ pcb_module.compute_module.l2_bandwidth_per_cycle
)
self.K_reduction_io_count = 2 * M * N * data_type.word_size
self.M_K_io_cycle_count = self.simulate_l2_tile_io_cycle_count(
M, K, data_type, pcb_module
)
self.K_N_io_cycle_count = self.simulate_l2_tile_io_cycle_count(
K, N, data_type, pcb_module