-
Notifications
You must be signed in to change notification settings - Fork 2
/
generate.py
1399 lines (1231 loc) · 53.6 KB
/
generate.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 intrin
import argparse
import subprocess
import time
import template
import numpy as np
from gekko import GEKKO
from utils import mem_model
import pandas as pd
def macros():
return "#include<omp.h>\n#include<immintrin.h>\n#include<fstream>\n\n#define mymin(a,b) ((a)<(b)?(a):(b))\n#define mymax(a,b) ((a)>(b)?(a):(b))\n"
def print_parameters(bits, n, m, t, nb, mb, tb, mu, nu, tu, unroll, p, gs=-1):
res = ""
res += "void print_parameters(){\n"
res += f" std::cout << {bits} << \"bits,\" << {n} << \",\" << {m} << \",\" << {t} << \",\" << {nb} << \",\" << {mb} << \",\" << {tb} << \",\" << {nu} << \",\" << {mu} << \",\" << {tu} << \",\" << {unroll} << \",\" << {p} << \",\" << {gs} << \",\";\n"
res += "}\n"
return res
def print_parameters_module(bits, mu, nu, tu, unroll, p, gs=-1):
res = ""
res += "void print_parameters(){\n"
res += "std::ofstream outfile;\n"
res += "outfile.open(\"tmp.csv\", std::ios_base::app);\n"
res += f"outfile << {bits} << \",\" << {nu} << \",\" << {mu} << \",\" << {tu} << \",\" << {unroll} << \",\" << {p} << \",\" << {gs} << \",\";\n"
res += "}\n"
return res
def pack_in(n, m, nb, mb):
res = ""
res += "inline void pack_input(float* A, float* B){\n"
res += " // copy the full matrix A in blocked format into B\n"
res += " uint64_t idx = 0;\n"
res += f" const int N = {n};\n"
res += f" const int M = {m};\n"
res += f" const int nb = {nb};\n"
res += f" const int mb = {mb};\n"
res += " for(int i = 0; i < N; i+=nb){ \n \
for(int j = 0; j < M; j+=mb){\n \
for(int jj = j; jj < mymin(j+mb, M); jj++){\n \
for(int ii = i; ii < mymin(i+nb, N); ii++){\n \
B[idx] = A[ii*M+jj];\n \
idx++;\n \
}\n \
}\n \
}\n \
}\n \
}\n"
return res
def pack_out(n, t, nb, tb):
res = ""
res += "inline void pack_output(float* A, float* B){\n"
res += " // copy the full matrix A in blocked format into B\n"
res += " uint64_t idx = 0;\n"
res += f" const int N = {n};\n"
res += f" const int M = {t};\n"
res += f" const int nb = {nb};\n"
res += f" const int mb = {tb};\n"
res += " for(int i = 0; i < N; i+=nb){ \n \
for(int j = 0; j < M; j+=mb){\n \
for(int ii = i; ii < mymin(i+nb, N); ii++){\n \
for(int jj = j; jj < mymin(j+mb, M); jj++){\n \
B[idx] = A[ii*M+jj];\n \
idx++;\n \
}\n \
}\n \
}\n \
}\n \
}\n"
return res
def pack_qw(m, t, mb, tb, tb1, bits=4, cutoff=-1):
packed = 32 // bits
res = ""
if cutoff == -1:
cutoff = 65
if bits == 3:
res += "inline void pack_qw_inner(int* A, int* B, int cutoff){\n"
res += " // copy the full matrix A in blocked format into B\n"
res += " uint64_t idx = 0;\n"
res += f" const int N = {m // 32 * 3};\n"
res += f" const int M = {t};\n"
res += f" const int nb = {mb // 32 * 3};\n"
res += f"int mb = {int(tb)};\n"
res += " for(int j = 0, tid = 0; j < M; j+=mb, tid++){\n"
# res += "if(tid==cutoff){\n "
# res += f" mb = {tb1};\n"
# res += "}\n"
res += " for(int i = 0; i < N; i+=nb){\n \
for(int ii = i; ii < mymin(i+nb, N); ii+=3){\n \
for(int jj = j; jj < mymin(j+mb, M); jj+=8){\n \
for(int iii = ii; iii < ii + 3; iii++){\n \
for(int jjj = jj; jjj < jj + 8; jjj++){\n \
B[idx] = A[iii*M+jjj];\n \
idx++;\n \
}\n \
}\n \
}\n \
}\n \
}\n \
}\n \
}\n"
res += "inline void pack_qw(int* A, int* B){\n"
res += f" pack_qw_inner(A, B, {cutoff});\n"
res += "}\n"
return res
else:
# in case i do this for python i can just add the n,m,nb,mb as function parameters
res += "inline void pack_qw_inner(int* A, int* B, int cutoff){\n"
res += " // copy the full matrix A in blocked format into B\n"
res += " uint64_t idx = 0;\n"
res += f" const int N = {m // packed};\n"
res += f" const int M = {t};\n"
res += f" const int nb = {mb // packed};\n"
res += f"int mb = {int(tb)};\n"
res += " for(int j = 0, tid = 0; j < M; j+=mb, tid++){\n"
# res += "if(tid==cutoff){\n "
# res += f" mb = {tb1};\n"
# res += "}\n"
res += " for(int i = 0; i < N; i+=nb){\n \
for(int ii = i; ii < mymin(i+nb, N); ii++){\n \
for(int jj = j; jj < mymin(j+mb, M); jj++){\n \
B[idx] = A[ii*M+jj];\n \
idx++;\n \
}\n \
}\n \
}\n"
res += "}\n"
res += "}\n"
res += "inline void pack_qw(int* A, int* B){\n"
res += f" pack_qw_inner(A, B, {cutoff});\n"
res += "}\n"
return res
def block_gs(nu_iter, mu, tu, rho, packed, unroll, bits):
res = ""
i = 0
# unroll = 4 # number of bcasts and unpacks
if bits == 3:
for j in range(0,tu,8):
res += f"__m256i w0_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k3*tb/{packed}*3 + jw+{j*3}]);\n"
res += f"__m256i w1_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k3*tb/{packed}*3 + jw+{j*3}+8]);\n"
res += f"__m256i w2_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k3*tb/{packed}*3 + jw+{j*3}+16]);\n"
u = 0
first_off = 3
second_off = 2
wid = 0
shift = 0
while u < 32:
if u == 10:
res += f"__m256 v{i}_{u} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k3+{u})*nb + i1+{i}]);\n"
for j in range(0,tu,8):
res += f"__m256i ws{j}_10 = _mm256_srli_epi32(w0_{j}, {bits*10});\n"
res += f"__m256i temp0_{j} = _mm256_slli_epi32(w1_{j}, 2);\n"
res += f"temp0_{j} = _mm256_and_si256(temp0_{j}, mask);\n"
res += f"ws{j}_10 = _mm256_or_si256(ws{j}_10, temp0_{j});\n"
res += f"__m256i wsa{j}_{u} = _mm256_and_si256(ws{j}_{u}, mask);\n"
res += f"__m256 l{j}_{u} = _mm256_cvtepi32_ps(wsa{j}_{u});\n"
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{u}, l{j}_{u}, acc{i}_{j});\n"
wid = wid + 1
u = u + 1
elif u == 21:
res += f"__m256 v{i}_{u} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k3+{u})*nb + i1+{i}]);\n"
for j in range(0,tu,8):
res += f"__m256i ws{j}_{u} = _mm256_srli_epi32(w1_{j}, 31);\n"
res += f"__m256i temp1_{j} = _mm256_slli_epi32(w2_{j}, 1);\n"
res += f"temp1_{j} = _mm256_and_si256(temp1_{j}, mask);\n"
res += f"ws{j}_{u} = _mm256_or_si256(ws{j}_{u}, temp1_{j});\n"
res += f"__m256i wsa{j}_{u} = _mm256_and_si256(ws{j}_{u}, mask);\n"
res += f"__m256 l{j}_{u} = _mm256_cvtepi32_ps(wsa{j}_{u});\n"
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{u}, l{j}_{u}, acc{i}_{j});\n"
wid = wid + 1
u = u + 1
for k in range(u,u + second_off):
res += f"__m256 v{i}_{k} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k3+{k})*nb + i1+{i}]);\n"
for k in range(u,u + second_off):
for j in range(0,tu,8):
res += f"__m256i ws{j}_{k} = _mm256_srli_epi32(w{wid}_{j}, {bits*k-wid*32-shift});\n"
for j in range(0,tu,8):
res += f"__m256i wsa{j}_{k} = _mm256_and_si256(ws{j}_{k}, mask);\n"
for j in range(0,tu,8):
res += f"__m256 l{j}_{k} = _mm256_cvtepi32_ps(wsa{j}_{k});\n"
for j in range(0,tu,8):
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{k}, l{j}_{k}, acc{i}_{j});\n"
u = u + 2
return res
else:
for j in range(0,tu,8):
res += f"__m256i w{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed} + k*mb*tb/{packed} + k3*tb/{packed} + j1+{j}]);\n"
for u in range(packed-unroll, -1, -unroll):
for k in range(u+unroll-1,u-1,-1):
res += f"__m256 v{i}_{k} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k3+{k})*nb + i1+{i}]);\n"
for k in range(u,u+unroll):
for j in range(0,tu,8):
res += f"__m256i ws{j}_{k} = _mm256_srli_epi32(w{j}, {bits*k});\n"
for j in range(0,tu,8):
res += f"__m256i wsa{j}_{k}= _mm256_and_si256(ws{j}_{k}, mask);\n"
for j in range(0,tu,8):
res += f"__m256 l{j}_{k} = _mm256_cvtepi32_ps(wsa{j}_{k});\n"
for j in range(0,tu,8):
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{k}, l{j}_{k}, acc{i}_{j});\n"
return res
def block(nu_iter, mu, tu, rho, packed, unroll, bits):
res = ""
i = 0
# unroll = 4 # number of bcasts and unpacks
if bits == 3:
for j in range(0,tu,8):
res += f"__m256i w0_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k2*tb/{packed}*3 + jw+{j*3}]);\n"
res += f"__m256i w1_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k2*tb/{packed}*3 + jw+{j*3}+8]);\n"
res += f"__m256i w2_{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed}*3 + k*mb*tb/{packed}*3 + k2*tb/{packed}*3 + jw+{j*3}+16]);\n"
u = 0
first_off = 3
second_off = 2
wid = 0
shift = 0
while u < 32:
if u == 10:
res += f"__m256 v{i}_{u} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k2+{u})*nb + i1+{i}]);\n"
for j in range(0,tu,8):
res += f"__m256i ws{j}_10 = _mm256_srli_epi32(w0_{j}, {bits*10});\n"
res += f"__m256i temp0_{j} = _mm256_slli_epi32(w1_{j}, 2);\n"
res += f"temp0_{j} = _mm256_and_si256(temp0_{j}, mask);\n"
res += f"ws{j}_10 = _mm256_or_si256(ws{j}_10, temp0_{j});\n"
res += f"__m256i wsa{j}_{u} = _mm256_and_si256(ws{j}_{u}, mask);\n"
res += f"__m256 l{j}_{u} = _mm256_cvtepi32_ps(wsa{j}_{u});\n"
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{u}, l{j}_{u}, acc{i}_{j});\n"
wid = wid + 1
u = u + 1
elif u == 21:
res += f"__m256 v{i}_{u} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k2+{u})*nb + i1+{i}]);\n"
for j in range(0,tu,8):
res += f"__m256i ws{j}_{u} = _mm256_srli_epi32(w1_{j}, 31);\n"
res += f"__m256i temp1_{j} = _mm256_slli_epi32(w2_{j}, 1);\n"
res += f"temp1_{j} = _mm256_and_si256(temp1_{j}, mask);\n"
res += f"ws{j}_{u} = _mm256_or_si256(ws{j}_{u}, temp1_{j});\n"
res += f"__m256i wsa{j}_{u} = _mm256_and_si256(ws{j}_{u}, mask);\n"
res += f"__m256 l{j}_{u} = _mm256_cvtepi32_ps(wsa{j}_{u});\n"
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{u}, l{j}_{u}, acc{i}_{j});\n"
wid = wid + 1
u = u + 1
for k in range(u,u + second_off):
res += f"__m256 v{i}_{k} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k2+{k})*nb + i1+{i}]);\n"
for k in range(u,u + second_off):
for j in range(0,tu,8):
res += f"__m256i ws{j}_{k} = _mm256_srli_epi32(w{wid}_{j}, {bits*k-wid*32-shift});\n"
for j in range(0,tu,8):
res += f"__m256i wsa{j}_{k} = _mm256_and_si256(ws{j}_{k}, mask);\n"
for j in range(0,tu,8):
res += f"__m256 l{j}_{k} = _mm256_cvtepi32_ps(wsa{j}_{k});\n"
for j in range(0,tu,8):
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{k}, l{j}_{k}, acc{i}_{j});\n"
u = u + 2
return res
else:
for j in range(0,tu,8):
res += f"__m256i w{j} = _mm256_loadu_si256((__m256i*)&W[base_W + j*m/{packed} + k*mb*tb/{packed} + k2*tb/{packed} + j1+{j}]);\n"
for u in range(packed-unroll, -1, -unroll):
for k in range(u+unroll-1,u-1,-1):
res += f"__m256 v{i}_{k} = _mm256_set1_ps(input[(i*om+k)*mb*nb + (k2+{k})*nb + i1+{i}]);\n"
for k in range(u,u+unroll):
for j in range(0,tu,8):
res += f"__m256i ws{j}_{k} = _mm256_srli_epi32(w{j}, {bits*k});\n"
for j in range(0,tu,8):
res += f"__m256i wsa{j}_{k}= _mm256_and_si256(ws{j}_{k}, mask);\n"
for j in range(0,tu,8):
res += f"__m256 l{j}_{k} = _mm256_cvtepi32_ps(wsa{j}_{k});\n"
for j in range(0,tu,8):
res += f"acc{i}_{j} = _mm256_fmadd_ps(v{i}_{k}, l{j}_{k}, acc{i}_{j});\n"
return res
def accumulators_f(nu, tu, gs=False):
accumulators = ""
for i in range(nu):
for j in range(0,tu,8):
if gs:
accumulators += f"__m256 acc{i}_{j} = _mm256_setzero_ps();\n"
else:
accumulators += f"__m256 acc{i}_{j} = _mm256_loadu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}]);\n"
return accumulators
def stores_f(nu, tu, gs=False):
store = ""
if gs:
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 o{i}_{j} = _mm256_loadu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}]);\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 s{i}_{j} = _mm256_loadu_ps(&scales[(k*mb+k1)/gs * t + base_output + j + j1+{j}]);\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 f{i}_{j} = _mm256_fmadd_ps(acc{i}_{j}, s{i}_{j}, o{i}_{j});\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"_mm256_storeu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}], f{i}_{j});\n"
else:
for i in range(nu):
for j in range(0,tu,8):
store += f"_mm256_storeu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}], acc{i}_{j});\n"
return store
def qforward(nu, mu, tu, p, unroll, bits, n=0, m=0, t =0, nb=0, mb=0, tb=0, tt=0, cutoff=-1, gs=False, gs_val=-1, module=True):
assert(module or (gs and gs_val != -1) or (not gs and gs_val == -1))
if cutoff == -1:
cutoff = p+1
# packed = 32 // bits
if bits == 3:
packed = 32
loopguard = packed
else:
packed = 32 // bits
loopguard = packed
#compute the parameters from the model
accumulators = accumulators_f(nu, tu, gs)
store = stores_f(nu, tu, gs)
ugemm = ""
if gs:
ugemm += "int j1 = 0;\n"
if bits == 3:
ugemm += "int jw = 0;\n"
ugemm += f"for(; j1 < tb-tu+1; j1+=tu, jw+={tu*3})"
ugemm += "{\n"
else:
ugemm += "for(; j1 < tb-tu+1; j1+=tu) {\n"
ugemm += "for(int k1 = 0; k1 < mb; k1+=gs) {\n"
ugemm += accumulators
ugemm += f"for(int k2 = k1; k2 < k1+gs; k2+={loopguard})\n"
ugemm += "{\n"
ugemm += block(nu, mu, tu, 16, packed, unroll, bits)
ugemm += "}\n"
ugemm += store
ugemm += "}\n"
ugemm += "}\n"
else:
ugemm += "int j1 = 0;\n"
if bits == 3:
ugemm += "int jw = 0;\n"
ugemm += f"for(; j1 < tb-tu+1; j1+=tu, jw+={tu*3})"
ugemm += "{\n"
else:
ugemm += "for(; j1 < tb-tu+1; j1+=tu) {\n"
ugemm += accumulators
ugemm += "for(int k1 = 0; k1 < mb; k1+=mu) {\n"
ugemm += f"for(int k2 = k1; k2 < k1+mu; k2+={loopguard})"
ugemm += "{\n"
ugemm += block(nu, mu, tu, 16, packed, unroll, bits)
ugemm += "}\n"
ugemm += "}\n"
ugemm += store
ugemm += "}\n"
res = ""
res += "inline\n"
if gs:
res += f"void q{bits}gemm_gs(const float* __restrict__ input, \n"
else:
res += f"void q{bits}gemm(const float* __restrict__ input, \n"
res += "const int* __restrict__ W, \n"
res += "const float* __restrict__ scales, \n"
res += "const float* __restrict__ zeros, \n"
res +="const float* __restrict__ bias, \n "
res +="const float* __restrict__ sums, \n "
res +="float* __restrict__ output,\n\
const int n,\n\
const int m,\n\
const int t,\n\
const int nb,\n\
const int mb,\n\
const int tb,\n\
int ogtt,\n"
if gs:
res += "const int gs,\n"
res += "const int cutoff){\n"
res += f"#pragma omp parallel num_threads({p})\n"
res += "{\n"
res += "int tid;\n"
res += f"const int mu = {mu};\n"
res += f"const int nu = {nu};\n"
res += f"const int tu = {tu};\n"
res += f"const int on = n / nb;\n"
res += f"const int om = m / mb;\n"
mask = (2**bits)-1
res += f"const __m256i mask = _mm256_set1_epi32({mask});\n"
if bits == 3:
res += f"const __m256i mask4 = _mm256_set1_epi32(4);\n"
res += f"const __m256i mask6 = _mm256_set1_epi32(6);\n"
res += "tid = omp_get_thread_num();\n"
res += "int tt = ogtt;\n"
res += "if(tid >= cutoff){\n"
res += f"tt -= tb;\n"
res += "}\n"
res += f"const int base_output = tid >= cutoff ?\n \
(tid-cutoff)*tt + (tt+tb)*cutoff: \n \
tid*tt;\n" #is this >= cutoff or > cutoff?
if bits != 3:
res += f"const int base_W = tid >= cutoff ?\n \
((tid-cutoff)*tt + (tt+tb)*cutoff)*m/{packed}: \n \
tid*tt*m/{packed};\n"
else:
res += f"const int base_W = tid >= cutoff ?\n \
((tid-cutoff)*tt + (tt+tb)*cutoff)*m/{packed}*3: \n \
tid*tt*m/{packed}*3;\n"
res += "for(int j = 0; j < tt; j+=tb){\n"
res += "for(int i = 0; i < on; i++) {\n"
res += "for(int k = 0; k < om; k++) {\n"
res += "for(int i1 = 0; i1 < nb; i1+=nu) {\n"
res += ugemm
res += "}\n"
res += "}\n"
res += "}\n"
res += "}\n"
res += "#pragma omp barrier\n"
# res += "#pragma omp for\n"
if gs:
res += "const int ngs = m/gs;\n"
res += "for (int i = 0; i < n; i++) {\n"
res += f"for (int j = 0; j < tt; j+={tu})"
res += "{\n"
for i in range(0,tu,8):
res += f"__m256 acc{i} = _mm256_setzero_ps();\n"
res += "for (int i1 = 0; i1 < ngs; i1++){\n"
res += "__m256 r = _mm256_set1_ps(sums[i*ngs + i1]);\n"
for i in range(0,tu,8):
res += f"__m256 z{i} = _mm256_loadu_ps(&zeros[base_output + i1* t + j + {i}]);\n"
# if not module:
if bits != 3 or not module:
for i in range(0,tu,8):
res += f"__m256 s{i} = _mm256_loadu_ps(&scales[base_output + i1 * t + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 zs{i} = _mm256_mul_ps(z{i}, s{i});\n"
for i in range(0,tu,8):
# if module:
if bits == 3 and module:
res += f"acc{i} = _mm256_fmadd_ps(z{i}, r, acc{i});\n"
else:
res += f"acc{i} = _mm256_fmadd_ps(zs{i}, r, acc{i});\n"
res += "}\n"
for i in range(0,tu,8):
res += f"__m256 o{i} = _mm256_loadu_ps(&output[i*t + base_output + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 b{i} = _mm256_loadu_ps(&bias[base_output + j + {i}]);\n"
for i in range(0,tu,8):
if module:
res += f"__m256 o1{i} = _mm256_sub_ps(o{i}, acc{i});\n"
else:
res += f"__m256 o1{i} = _mm256_add_ps(o{i}, acc{i});\n"
for i in range(0,tu,8):
res += f"__m256 o2{i} = _mm256_add_ps(o1{i}, b{i});\n"
for i in range(0,tu,8):
res += f"_mm256_storeu_ps(&output[i*t + base_output + j + {i}], o2{i});\n"
res += "}\n"
res += "}\n"
res += "}\n"
res += "}\n"
else:
res += "for (int i = 0; i < n; i++) {\n"
res += "__m256 r = _mm256_set1_ps(sums[i]);\n"
res += f"for (int j = 0; j < tt; j+={tu})"
res += "{\n"
for i in range(0,tu,8):
res += f"__m256 o{i} = _mm256_loadu_ps(&output[i*t + base_output + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 z{i} = _mm256_loadu_ps(&zeros[base_output + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 b{i} = _mm256_loadu_ps(&bias[base_output + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 s{i} = _mm256_loadu_ps(&scales[base_output + j + {i}]);\n"
if bits == 3 and module:
for i in range(0,tu,8):
res += f"__m256 os{i} = _mm256_mul_ps(o{i}, s{i});\n"
for i in range(0,tu,8):
if module:
if bits == 3:
res += f"__m256 zr{i} = _mm256_fnmadd_ps(z{i}, r, os{i});\n"
else:
res += f"__m256 zr{i} = _mm256_fnmadd_ps(z{i}, r, o{i});\n"
else:
res += f"__m256 zr{i} = _mm256_fmadd_ps(z{i}, r, o{i});\n"
for i in range(0,tu,8):
# j res += f"__m256 o2{i} = _mm256_mul_ps(zr{i}, s{i});\n"
if bits == 3 and module:
res += f"__m256 o2{i} = _mm256_add_ps(zr{i}, b{i});\n"
else:
res += f"__m256 o2{i} = _mm256_fmadd_ps(zr{i}, s{i}, b{i});\n"
for i in range(0,tu,8):
res += f"_mm256_storeu_ps(&output[i*t + base_output + j + {i}], o2{i});\n"
res += "}\n"
res += "}\n"
res += "}\n"
res += "}\n"
# wrapper for qgemm if we call from cpp
if module:
if gs:
res += f"inline void forward{bits}_gs_cpu(\n"
else:
res += f"inline void forward{bits}_cpu(\n"
res += "torch::Tensor in, torch::Tensor weight, torch::Tensor out,\n"
res += "torch::Tensor bias, torch::Tensor scales, torch::Tensor zeros, torch::Tensor sums,\n"
if gs:
res += "int N, int M, int T, int nb, int mb, int tb, int tt, int groupsize, int cutoff){\n"
else:
res += "int N, int M, int T, int nb, int mb, int tb, int tt, int cutoff){\n"
res += "int* W = weight.data_ptr<int>();\n"
res += "float* input = in.data_ptr<float>();\n"
res += "float* b = bias.data_ptr<float>();\n"
res += "float* s = scales.data_ptr<float>();\n"
res += "float* z = zeros.data_ptr<float>();\n"
res += "float* r = sums.data_ptr<float>();\n"
res += "float* O = out.data_ptr<float>();\n"
res += "\n"
if gs:
res += f"q{bits}gemm_gs(input, W, s, z, b, r, O, N, M, T, nb, mb, tb, tt, groupsize, cutoff);\n"
else:
res += f"q{bits}gemm(input, W, s, z, b, r, O, N, M, T, nb, mb, tb, tt, cutoff);\n"
res += "}\n"
else:
res += "inline void qforward(const float* __restrict__ input, \n \
const int* __restrict__ W, \n\
const float* __restrict__ scales, \n\
const float* __restrict__ zeros, \n\
const float* __restrict__ bias, \n\
const float* __restrict__ sums, \n\
float* __restrict__ output, \n\
int n, \n \
int m, \n \
int t) {\n"
if gs:
res += f"q{bits}gemm_gs(input, W, scales, zeros, bias, sums, output, n, m, t, {nb}, {mb}, {tb}, {tt}, {gs_val}, {cutoff});\n"
else:
res += f"q{bits}gemm(input, W, scales, zeros, bias, sums, output, n, m, t, {nb}, {mb}, {tb}, {tt}, {cutoff});\n"
res += "}\n"
return res
def gen_model(n, m, t, bits, p, gs):
# get parameters
if bits == 3:
packed = 32
unroll = 3
nu = 1 #args.n
mu = 32
tu = 32
else:
packed = 32 // bits
unroll = 2
nu = 1 #args.n
mu = 16
tu = 32
#compute the parameters from the model
nb = n # it's always small for transformers
mb, tb = mem_model(n, m, t, mu, tu, bits, l1, p, gs)
split = np.ones(p)
split = split * tb
while np.sum(split) < t:
split = split + tb
idx = p - 1
while np.sum(split) > t:
split[idx] = split[idx] - tb
idx = idx - 1
assert(np.sum(split) == t)
split = split.astype(int)
tt = int(split[0])
if split[0] == split[-1]:
cutoff = int(p+1)
else:
cutoff = int(idx + 1)
if gs == -1:
code = qforward(nu, mu, tu, p, unroll, n=n, m=m, t=t, nb=nb, mb=mb, tb=tb, tt=tt, bits=bits, cutoff=cutoff, module=False)
else:
code = qforward(nu, mu, tu, p, unroll, n=n, m=m, t=t, nb=nb, mb=mb, tb=tb, tt=tt, bits=bits, cutoff=cutoff, gs=True, gs_val=gs, module=False)
code += pack_in(n, m, nb, mb)
# code += pack_qw(m, t, mb, tb, tb, bits=bits)#, cutoff=cutoff)
code += pack_qw(m, t, mb, tb, tu,bits=bits)
code += pack_out(n, t, nb, tb)
code += print_parameters(bits, n, m, t, nb, mb, tb, mu, nu, tu, unroll, p)
with open("forward.h", "w") as f:
f.write(macros())
f.write(code)
def gen_and_compile(n, m, t, nb, mb, tb, nu, mu, tu, p, unroll, bits=4, gs=-1, module=False):
split = np.ones(p)
split = split * tb
while np.sum(split) < t:
split = split + tb
idx = p - 1
while np.sum(split) > t:
split[idx] = split[idx] - tb
idx = idx - 1
assert(np.sum(split) == t)
split = split.astype(int)
tt = int(split[0])
if split[0] == split[-1]:
cutoff = int(p+1)
else:
cutoff = int(idx + 1)
if gs == -1:
code = qforward(nu, mu, tu, p, unroll, n=n, m=m, t=t, nb=nb, mb=mb, tb=tb, tt=tt, bits=bits, cutoff=cutoff, module=False)
else:
code = qforward(nu, mu, tu, p, unroll, n=n, m=m, t=t, nb=nb, mb=mb, tb=tb, tt=tt, bits=bits, cutoff=cutoff, gs=True, gs_val=gs, module=False)
code += pack_in(n, m, nb, mb)
code += pack_qw(m, t, mb, tb, tu,bits=bits)
code += pack_out(n, t, nb, tb)
if module:
code += print_parameters_module(bits, mu, nu, tu, unroll, p, gs=gs)
else:
code += print_parameters(bits, n, m, t, nb, mb, tb, mu, nu, tu, unroll, p, gs=gs)
# write the code to a file called forward.h
with open("forward.h", "w") as f:
f.write(macros())
f.write(code)
# g++ mmm_test.cpp -O3 -ftree-vectorize -mfma -mavx -mavx2 -fno-signaling-nans -fno-trapping-math -fopenmp -o mmm_test
start = time.time()
if not module:
subprocess.call(["g++", "-O3", "-o", "mmm_test", "mmm_test.cpp", "-mavx", "-mfma", "-mavx2", "-ftree-vectorize", "-fno-signaling-nans", "-fno-trapping-math", "-march=native", "-fopenmp"])
subprocess.call(["./mmm_test", f"{n}", f"{m}", f"{t}", f"{bits}", f"{gs}"])
else:
subprocess.call(["g++", "-O3", "-o", "mmm", "mmm.cpp", "-mavx", "-mfma", "-mavx2", "-ftree-vectorize", "-fno-signaling-nans", "-fno-trapping-math", "-march=native", "-fopenmp"])
subprocess.call(["./mmm", f"{n}", f"{m}", f"{t}", f"{bits}", f"{gs}"])
# subprocess.call(["./mmm", f"{n}", f"{m}", f"{t}", f"{bits}", f"{gs}", ">>", "tmp.csv"])
end = time.time() - start
return end
def grid():
tt = 64
for p in [32]:
# for n in [1, 10]:
for n in [1]:
for m in [4096]:
for t in [4096]:
# for mb in range(1,m):
# for mb in range(32,512,32):
# for mb in [64, 128, 256, 512, 1024, 2048]:
for mb in [512, 1024, 2048]:
if m % mb == 0:
# for tb in range(8,t,8):
# for tb in range(32,512,32):
# for tb in [16, 32, 64]:#, 128, 192, 256]:
# for tb in [32]:#, 128, 192, 256]:
for tb in [128, 256]:
if t % tb == 0:
# for mu in range(32,mb,32):
for mu in [16, 32]:
if mb % mu == 0:
# for tu in range(8,tb,8):
# for tu in [16, 32]:
for tu in [16, 32, 64, 128]:
if tb % tu == 0:
for gs in [-1, 128, 64, 32, 16]:
# for bits in [2, 3, 4]:
for bits in [4, 3, 2]:
if bits == 3:
for u in [5]:
gen_and_compile(n,m,t,n,mb,tb,1,mu,tu,p,u,bits=bits, gs=gs)
else:
for u in [1, 2, 4, 8]:
gen_and_compile(n,m,t,n,mb,tb,1,mu,tu,p,u,bits=bits, gs=gs)
def forward_module_gs(nu, mu, tu, p, unroll, bits):
# packed = 32 // bits
if bits == 3:
packed = 32
loopguard = packed
else:
packed = 32 // bits
loopguard = packed
#compute the parameters from the model
accumulators = ""
for i in range(nu):
for j in range(0,tu,8):
accumulators += f"__m256 acc{i}_{j} = _mm256_setzero_ps();\n"
store = ""
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 o{i}_{j} = _mm256_loadu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}]);\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 s{i}_{j} = _mm256_loadu_ps(&scales[(k*mb+k1)/gs * t + base_output + j + j1+{j}]);\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"__m256 f{i}_{j} = _mm256_fmadd_ps(acc{i}_{j}, s{i}_{j}, o{i}_{j});\n"
for i in range(nu):
for j in range(0,tu,8):
store += f"_mm256_storeu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}], f{i}_{j});\n"
ugemm = ""
if bits == 3:
ugemm += "int j1 = 0;\n"
ugemm += "int jw = 0;\n"
ugemm += f"for(; j1 < tb-tu+1; j1+=tu, jw+={tu*3})"
ugemm += "{\n"
else:
ugemm += "int j1 = 0;\n"
ugemm += "for(; j1 < tb-tu+1; j1+=tu) {\n"
ugemm += "for(int k1 = 0; k1 < mb; k1+=gs) {\n"
ugemm += accumulators
ugemm += f"for(int k2 = k1; k2 < k1+gs; k2+={loopguard})\n"
ugemm += "{\n"
ugemm += block(nu, mu, tu, 16, packed, unroll, bits)
ugemm += "}\n"
ugemm += store
ugemm += "}\n"
ugemm += "}\n"
res = ""
res += "inline\n"
res += f"void q{bits}gemm_gs(const float* __restrict__ input, \n"
res += " const int* __restrict__ W, \n \
const float* __restrict__ scales, \n"
res += "const float* __restrict__ zeros, \n"
res +=" const float* __restrict__ bias, \n "
res +=" const float* __restrict__ sums,\n"
res +=" float* __restrict__ output,\n \
const int n,\n \
const int m,\n \
const int t,\n \
const int nb,\n \
const int mb,\n \
const int tb,\n \
int ogtt,\n \
const int gs,\n\
const int cutoff){\n"
res += f"#pragma omp parallel num_threads({p})\n"
res += "{\n"
res += " int tid;\n"
res += f" const int mu = {mu};\n"
res += f" const int nu = {nu};\n"
res += f" const int tu = {tu};\n"
res += f" const int on = n / nb;\n"
res += f" const int om = m / mb;\n"
mask = (2**bits)-1
res += f"const __m256i mask = _mm256_set1_epi32({mask});\n"
if bits == 3:
res += f"const __m256i mask4 = _mm256_set1_epi32(4);\n"
res += f"const __m256i mask6 = _mm256_set1_epi32(6);\n"
res += "tid = omp_get_thread_num();\n"
res += "int tt = ogtt;\n"
res += "if(tid >= cutoff){\n"
res += f"tt -= tb;\n"
res += "}\n"
res += f"const int base_output = tid >= cutoff ?\n \
(tid-cutoff)*tt + (tt+tb)*cutoff: \n \
tid*tt;\n" #is this >= cutoff or > cutoff?
if bits != 3:
res += f"const int base_W = tid >= cutoff ?\n \
((tid-cutoff)*tt + (tt+tb)*cutoff)*m/{packed}: \n \
tid*tt*m/{packed};\n"
else:
res += f"const int base_W = tid >= cutoff ?\n \
((tid-cutoff)*tt + (tt+tb)*cutoff)*m/{packed}*3: \n \
tid*tt*m/{packed}*3;\n"
res += "for(int j = 0; j < tt; j+=tb){\n"
res += "for(int i = 0; i < on; i++) {\n"
res += "for(int k = 0; k < om; k++) {\n"
res += "for(int i1 = 0; i1 < nb; i1+=nu) {\n"
res += ugemm
res += "}\n"
res += "}\n"
res += "}\n"
res += "}\n"
res += "const int ngs = m/gs;\n"
res += "#pragma omp barrier\n"
# res += "#pragma omp for collapse(2)\n"
res += "for (int i = 0; i < n; i++) {\n"
# res += f" for (int j = 0; j < t; j+={tu})"
res += f"for (int j = 0; j < tt; j+={tu})"
res += "{\n"
# for i in range(0,tu,8):
# res += f"__m256 o{i} = _mm256_loadu_ps(&output[i*t + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 acc{i} = _mm256_setzero_ps();\n"
res += "for (int i1 = 0; i1 < ngs; i1++){\n"
res += "__m256 r = _mm256_set1_ps(sums[i*ngs + i1]);\n"
for i in range(0,tu,8):
# res += f"__m256 z{i} = _mm256_loadu_ps(&zeros[i1 * t + j + {i}]);\n"
res += f"__m256 z{i} = _mm256_loadu_ps(&zeros[base_output + i1* t + j + {i}]);\n"
# for i in range(0,tu,8):
# res += f"__m256 s{i} = _mm256_loadu_ps(&scales[i1 * t + j + {i}]);\n"
# for i in range(0,tu,8):
# res += f"__m256 zr{i} = _mm256_mul_ps(z{i}, r);\n"
# for i in range(0,tu,8):
# res += f"acc{i} = _mm256_fmadd_ps(zr{i}, s{i}, acc{i});\n"
for i in range(0,tu,8):
res += f"acc{i} = _mm256_fmadd_ps(z{i}, r, acc{i});\n"
# for i in range(0,tu,8):
# res += f"__m256 zr{i} = _mm256_mul_ps(z{i}, r);\n"
# for i in range(0,tu,8):
# res += f"o{i} = _mm256_fnmadd_ps(zr{i}, s{i}, o{i});\n"
res += "}\n"
for i in range(0,tu,8):
# res += f"__m256 o{i} = _mm256_loadu_ps(&output[i*t + j + {i}]);\n"
res += f"__m256 o{i} = _mm256_loadu_ps(&output[i*t + base_output + j + {i}]);\n"
for i in range(0,tu,8):
res += f"__m256 o1{i} = _mm256_sub_ps(o{i}, acc{i});\n"
for i in range(0,tu,8):
# res += f"_mm256_storeu_ps(&output[i*t + j + {i}], o1{i});\n"
res += f"_mm256_storeu_ps(&output[i*t + base_output + j + {i}], o1{i});\n"
res += " }\n"
res += "}\n"
res += "}\n"
res += "}\n"
# wrapper for qgemm if we call from cpp
res += f"inline void forward{bits}_gs_cpu(\n"
res += "torch::Tensor in, torch::Tensor weight, torch::Tensor out,\n"
res += "torch::Tensor bias, torch::Tensor scales, torch::Tensor zeros, torch::Tensor sums,\n"
res += "int N, int M, int T, int nb, int mb, int tb, int tt, int groupsize, int cutoff){\n"
res += "int* W = weight.data_ptr<int>();\n"
res += "float* input = in.data_ptr<float>();\n"
res += "float* b = bias.data_ptr<float>();\n"
res += "float* s = scales.data_ptr<float>();\n"
# res += "int* z = zeros.data_ptr<int>();\n"
res += "float* z = zeros.data_ptr<float>();\n"
res += "float* r = sums.data_ptr<float>();\n"
res += "float* O = out.data_ptr<float>();\n"
res += "\n"
res += f"q{bits}gemm_gs(input, W, s, z, b, r, O, N, M, T, nb, mb, tb, tt, groupsize, cutoff);\n"
res += "}\n"
return res
def forward_module(nu, mu, tu, p, unroll, bits):
# packed = 32 // bits
if bits == 3:
packed = 32
loopguard = packed
else:
packed = 32 // bits
loopguard = packed
#compute the parameters from the model
accumulators = ""
for i in range(nu):
for j in range(0,tu,8):
accumulators += f"__m256 acc{i}_{j} = _mm256_loadu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}]);\n"
store = ""
for i in range(nu):
for j in range(0,tu,8):
store += f"_mm256_storeu_ps(&output[base_output + j + (i1+{i})*t + j1+{j}], acc{i}_{j});\n"
ugemm = ""
if bits == 3:
ugemm += "int jw = 0;\n"
ugemm += f"for(; j1 < tb-tu+1; j1+=tu, jw+={tu*3})"
ugemm += "{\n"
else:
ugemm += "for(; j1 < tb-tu+1; j1+=tu) {\n"
ugemm += accumulators
ugemm += "for(int k1 = 0; k1 < mb; k1+=mu) {\n"
ugemm += f"for(int k2 = k1; k2 < k1+mu; k2+={loopguard})"
ugemm += "{\n"
ugemm += block(nu, mu, tu, 16, packed, unroll, bits)
ugemm += "}\n"
ugemm += "}\n"
ugemm += store
ugemm += "}\n"
res = ""
res += "inline\n"
res += f"void q{bits}gemm(const float* __restrict__ input, \n"
res += "const int* __restrict__ W, \n"
res += "const float* __restrict__ scales, \n"
# res += "const int* __restrict__ zeros, \n"
res += "const float* __restrict__ zeros, \n"
res +="const float* __restrict__ bias, \n "
res +="const float* __restrict__ sums,"
res +="float* __restrict__ output,\n \
const int n,\n \
const int m,\n \
const int t,\n \
const int nb,\n \
const int mb,\n \
const int tb,\n \
int ogtt,\n \
const int cutoff){\n"
res += f"#pragma omp parallel num_threads({p})\n"
res += "{\n"
res += "int tid, nthreads;\n"
res += f"const int mu = {mu};\n"
res += f"const int nu = {nu};\n"
res += f"const int tu = {tu};\n"
res += f"const int on = n / nb;\n"
res += f"const int om = m / mb;\n"
mask = (2**bits)-1
res += f"const __m256i mask = _mm256_set1_epi32({mask});\n"
if bits == 3:
res += f"const __m256i mask4 = _mm256_set1_epi32(4);\n"
res += f"const __m256i mask6 = _mm256_set1_epi32(6);\n"
res += "tid = omp_get_thread_num();\n"