-
Notifications
You must be signed in to change notification settings - Fork 11
/
catseye_llm.h
2993 lines (2727 loc) · 101 KB
/
catseye_llm.h
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
//---------------------------------------------------------
// Cat's eye
//
// ©2016-2023 Yuichiro Nakada
//---------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <fcntl.h>
#if defined _WIN32
//#include "win.h"
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
#if defined(__SSE__) || defined(__AVX__)
#include <xmmintrin.h>
#include <immintrin.h>
#endif
#ifdef GPGPU
#include "gpgpu_matmul.h"
#endif
#ifdef DTYPE
typedef DTYPE real; // _Float16
#else
#define real float
#endif
#if 1
#define ALIGN 256
#if defined(_MSC_VER) || defined(__MINGW32__)
#define malloc(size) _aligned_malloc(size, ALIGN)
#define free(p) _aligned_free(p)
#else
#define malloc(size) ({ void* _p; posix_memalign((void**) &_p, ALIGN, (size))==0 ? _p : NULL; })
#define free(p) free(p)
#endif /* _MSC_VER */
//#define calloc(n, size) ({ uint64_t _s = n * size; void* _p = malloc(_s); memset(_p, 0, _s)!=0 ? _p : NULL; })
#define calloc(n, size) ({ uint64_t _s = n * size; void* _p; posix_memalign((void**) &_p, ALIGN, (_s))==0 ? _p : NULL; })
#else
#include "alloc.h"
#endif
#undef MIN
#undef MAX
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
//---------------------------------------------------------
// Tables
// precomputed silu table for f16 (128 KB)
static uint16_t table_silu_f16[1 << 16];
// precomputed f32 table for f16 (256 KB)
//static float table_f32_f16[1 << 16];
// On ARM NEON, it's quicker to directly convert x -> x instead of calling into ggml_lookup_fp16_to_fp32,
// so we define GGML_FP16_TO_FP32 and GGML_FP32_TO_FP16 elsewhere for NEON.
// This is also true for POWER9.
//---------------------------------------------------------
// Quantize
#define QK4_0 32
#define QK8 32
// FP16 <-> FP32
#ifdef __F16C__
#ifdef _MSC_VER
#define cats_fp16_to_fp32(x) _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(x)))
#define cats_fp32_to_fp16(x) _mm_extract_epi16(_mm_cvtps_ph(_mm_set_ss(x), 0), 0)
#else
#define cats_fp16_to_fp32(x) _cvtsh_ss(x)
#define cats_fp32_to_fp16(x) _cvtss_sh(x, 0)
#endif
#else
// ref: https://github.com/Maratyszcza/FP16
static inline float fp32_from_bits(uint32_t w)
{
union {
uint32_t as_bits;
float as_value;
} fp32;
fp32.as_bits = w;
return fp32.as_value;
}
static inline uint32_t fp32_to_bits(real f)
{
union {
float as_value;
uint32_t as_bits;
} fp32;
fp32.as_value = f;
return fp32.as_bits;
}
static inline float cats_fp16_to_fp32(uint16_t h)
{
const uint32_t w = (uint32_t) h << 16;
const uint32_t sign = w & UINT32_C(0x80000000);
const uint32_t two_w = w + w;
const uint32_t exp_offset = UINT32_C(0xE0) << 23;
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float exp_scale = 0x1.0p-112f;
#else
const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
#endif
const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
const uint32_t magic_mask = UINT32_C(126) << 23;
const float magic_bias = 0.5f;
const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
const uint32_t result = sign |
(two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
return fp32_from_bits(result);
}
static inline uint16_t cats_fp32_to_fp16(real f)
{
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float scale_to_inf = 0x1.0p+112f;
const float scale_to_zero = 0x1.0p-110f;
#else
const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
#endif
float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
const uint32_t w = fp32_to_bits(f);
const uint32_t shl1_w = w + w;
const uint32_t sign = w & UINT32_C(0x80000000);
uint32_t bias = shl1_w & UINT32_C(0xFF000000);
if (bias < UINT32_C(0x71000000)) {
bias = UINT32_C(0x71000000);
}
base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
const uint32_t bits = fp32_to_bits(base);
const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
const uint32_t nonsign = exp_bits + mantissa_bits;
return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
}
#endif
#ifdef __AVX__
static void quantize_q8(int8_t* p, real* x, int n)
{
int nb = n>>5; // QK8: 32
do {
// Load elements into 4 AVX vectors
__m256 v0 = _mm256_load_ps(x);
__m256 v1 = _mm256_load_ps(x+8);
__m256 v2 = _mm256_load_ps(x+16);
__m256 v3 = _mm256_load_ps(x+24);
x += 32;
// Compute max(abs(e)) for the block
const __m256 signBit = _mm256_set1_ps(-0.0);
__m256 maxAbs = _mm256_andnot_ps(signBit, v0);
maxAbs = _mm256_max_ps(maxAbs, _mm256_andnot_ps(signBit, v1));
maxAbs = _mm256_max_ps(maxAbs, _mm256_andnot_ps(signBit, v2));
maxAbs = _mm256_max_ps(maxAbs, _mm256_andnot_ps(signBit, v3));
__m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maxAbs, 1), _mm256_castps256_ps128(maxAbs));
max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4));
max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4));
const float maxScalar = _mm_cvtss_f32(max4);
// Quantize these floats
const float d = maxScalar / 127.;
const float id = ( maxScalar != 0.0 ) ? 127. / maxScalar : 0.0;
const __m256 mul = _mm256_broadcast_ss(&id);
// Apply the multiplier
v0 = _mm256_mul_ps(v0, mul);
v1 = _mm256_mul_ps(v1, mul);
v2 = _mm256_mul_ps(v2, mul);
v3 = _mm256_mul_ps(v3, mul);
// Round to nearest integer
v0 = _mm256_round_ps(v0, _MM_ROUND_NEAREST);
v1 = _mm256_round_ps(v1, _MM_ROUND_NEAREST);
v2 = _mm256_round_ps(v2, _MM_ROUND_NEAREST);
v3 = _mm256_round_ps(v3, _MM_ROUND_NEAREST);
// Convert floats to integers
__m256i i0 = _mm256_cvtps_epi32(v0);
__m256i i1 = _mm256_cvtps_epi32(v1);
__m256i i2 = _mm256_cvtps_epi32(v2);
__m256i i3 = _mm256_cvtps_epi32(v3);
__m128i ni0 = _mm256_castsi256_si128(i0);
__m128i ni1 = _mm256_extractf128_si256(i0, 1);
__m128i ni2 = _mm256_castsi256_si128(i1);
__m128i ni3 = _mm256_extractf128_si256(i1, 1);
__m128i ni4 = _mm256_castsi256_si128(i2);
__m128i ni5 = _mm256_extractf128_si256(i2, 1);
__m128i ni6 = _mm256_castsi256_si128(i3);
__m128i ni7 = _mm256_extractf128_si256(i3, 1);
// Convert int32 to int16
ni0 = _mm_packs_epi32(ni0, ni1);
ni2 = _mm_packs_epi32(ni2, ni3);
ni4 = _mm_packs_epi32(ni4, ni5);
ni6 = _mm_packs_epi32(ni6, ni7);
// Convert int16 to int8
ni0 = _mm_packs_epi16(ni0, ni2);
ni4 = _mm_packs_epi16(ni4, ni6);
// int8_t *p = q + i*(32+sizeof(float));
_mm_storeu_si128((__m128i *)(p + 0), ni0);
_mm_storeu_si128((__m128i *)(p + 16), ni4);
*(float*)(p + 32) = d;
p += 36;
} while (--nb > 0);
}
#else
static void quantize_q8(int8_t* q, real* x, int n)
{
int num_groups = n / QK8;
for (int group=0; group<num_groups; group++) {
// find the max absolute value in the current group
real amax = 0.0;
for (int i=0; i<QK8; i++) {
real v = fabsf(x[group * QK8 + i]);
amax = MAX(amax, v);
}
// calculate and write the scaling factor
int8_t* p = q + group * (32+sizeof(float));
const float d = amax / 127.0;
const float id = d ? 1.0/d : 0.0;
// calculate and write the quantized values
for (int i=0; i<QK8; i++) {
float quant_value = x[group * QK8 + i] * id;
*p++ = roundf(quant_value); // round and clamp
}
*((float*)p) = d;
p += sizeof(float);
}
}
#endif
static void no_quantize(int8_t* q, real* x, int n) {}
static inline int nearest_int(float fval)
{
// assert(fval <= 4194303.f);
float val = fval + 12582912.f;
int i; memcpy(&i, &val, sizeof(int));
return (i & 0x007fffff) - 0x00400000;
}
static inline void quantize_q8_K(int8_t* y, real* x, int k)
{
const int nb = k>>8; // 256
for (int i=0; i<nb; i++) {
float max = 0;
float amax = 0;
for (int j=0; j<256; ++j) {
float ax = fabsf(x[j]);
if (ax > amax) {
amax = ax; max = x[j];
}
}
if (!amax) {
memset(y, 0, 256+4);
x += 256;
y += 256+4;
continue;
}
const float iscale = -128./max;
for (int j=0; j<256; ++j) {
int v = nearest_int(iscale*x[j]);
*y++ = MIN(127, v);
}
/*for (int j=0; j<256/16; ++j) {
int sum = 0;
for (int ii = 0; ii < 16; ++ii) {
sum += y[i].qs[j*16 + ii];
}
y[i].bsums[j] = sum;
}*/
*(float*)y = 1/iscale;
y += sizeof(float);
x += 256;
}
}
/*static void quantize_q8_K(int8_t* p, real* x, int n)
{
int nb = n>>8; // 256
do {
__m256 v[32];
for (int i=0; i<32; i++) v[i] = _mm256_load_ps(x+i*8);
x += 256;
// Compute max(abs(e)) for the block
const __m256 signBit = _mm256_set1_ps(-0.0);
__m256 maxAbs = _mm256_andnot_ps(signBit, v[0]);
for (int i=1; i<32; i++) _mm256_max_ps(maxAbs, _mm256_andnot_ps(signBit, v[i]));
__m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maxAbs, 1), _mm256_castps256_ps128(maxAbs));
max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4));
max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4));
const float maxScalar = _mm_cvtss_f32(max4);
// Quantize these floats
const float d = maxScalar / 127.;
const float id = ( maxScalar != 0.0 ) ? 127. / maxScalar : 0.0;
const __m256 mul = _mm256_broadcast_ss(&id);
for (int i=0; i<32; i+=2) {
// Apply the multiplier
__m256 v0 = _mm256_mul_ps(v[i], mul);
__m256 v1 = _mm256_mul_ps(v[i+1], mul);
// Round to nearest integer
v0 = _mm256_round_ps(v0, _MM_ROUND_NEAREST);
v1 = _mm256_round_ps(v1, _MM_ROUND_NEAREST);
// Convert floats to integers
__m256i i0 = _mm256_cvtps_epi32(v0);
__m256i i1 = _mm256_cvtps_epi32(v1);
__m128i ni0 = _mm256_castsi256_si128(i0);
__m128i ni1 = _mm256_extractf128_si256(i0, 1);
__m128i ni2 = _mm256_castsi256_si128(i1);
__m128i ni3 = _mm256_extractf128_si256(i1, 1);
// Convert int32 to int16
ni0 = _mm_packs_epi32(ni0, ni1);
ni2 = _mm_packs_epi32(ni2, ni3);
// Convert int16 to int8
ni0 = _mm_packs_epi16(ni0, ni2);
_mm_storeu_si128((__m128i *)p, ni0);
p += 16;
}
*(float*)p = d;
p += 4;
} while (--nb > 0);
}*/
static inline void* dequantize_q3_K(void * restrict _y, const void * restrict x, size_t k)
{
const int nb = k>>8; // 256
float * restrict y = (float*)_y;
const uint32_t kmask1 = 0x03030303;
const uint32_t kmask2 = 0x0f0f0f0f;
uint32_t aux[4];
const int8_t * scales = (const int8_t*)aux;
for (int i=0; i<nb; i++) {
uint8_t *p = (uint8_t*)(x + i*(256/8 +256/4 +12 +2));
const float d_all = cats_fp16_to_fp32(*((uint16_t*)(p +256/8 +256/4 +12)));
const uint8_t * restrict q = p +256/8;
const uint8_t * restrict hm = p;
uint8_t m = 1;
const int8_t * restrict sc = (const int8_t*)p +256/8 +256/4;
memcpy(aux, sc, 12);
uint32_t tmp = aux[2];
aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);
aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);
aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);
aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);
int is = 0;
float dl;
for (int n=0; n<256; n += 128) {
int shift = 0;
for (int j=0; j<4; ++j) {
dl = d_all * (scales[is++] - 32);
for (int l=0; l<16; ++l) {
*y++ = dl * ((int8_t)((q[l+ 0] >> shift) & 3) - ((hm[l+ 0] & m) ? 0 : 4));
}
dl = d_all * (scales[is++] - 32);
for (int l=0; l<16; ++l) {
*y++ = dl * ((int8_t)((q[l+16] >> shift) & 3) - ((hm[l+16] & m) ? 0 : 4));
}
shift += 2;
m <<= 1;
}
q += 32;
}
}
return 0;
}
static inline void* dequantize_q6_K(void * restrict _y, const void * restrict x, size_t k)
{
const int nb = k>>8; // 256
float * restrict y = (float*)_y;
for (int i=0; i<nb; i++) {
uint8_t *p = (uint8_t*)(x + i*(256/2 +256/4 +256/16 +2));
const float d = cats_fp16_to_fp32(*((uint16_t*)(p +256/2 +256/4 +256/16)));
const uint8_t * restrict ql = p;
const uint8_t * restrict qh = p +256/2;
const int8_t * restrict sc = (const int8_t*)p +256/2 +256/4;
for (int n=0; n<2; n++) {
for (int l=0; l<32; ++l) {
int is = l/16;
const int8_t q1 = (int8_t)((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32;
const int8_t q3 = (int8_t)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
const int8_t q2 = (int8_t)((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32;
const int8_t q4 = (int8_t)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
y[l + 0] = d * sc[is + 0] * q1;
y[l + 32] = d * sc[is + 2] * q2;
y[l + 64] = d * sc[is + 4] * q3;
y[l + 96] = d * sc[is + 6] * q4;
}
y += 128;
ql += 64;
qh += 32;
sc += 8;
}
}
return 0;
}
static inline void* dequantize_q4_0(void * restrict y, const void * restrict x, size_t k)
{
const int nb = k>>5; // 32
for (int i=0; i<nb; i++) {
uint8_t *p = (uint8_t*)(x + i*18);
const float delta = cats_fp16_to_fp32(*((uint16_t*)p));
p += 2;
float *y0 = (float*)(y + i*32*sizeof(float));
float *y1 = y0 + 16;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
*y0++ = ((*p & 0x0F) - 8)*delta;
*y1++ = ((*p++ >> 4) - 8)*delta;
}
return 0;
}
static void* _dequantize_q3_K(void * restrict a, const void * restrict b, int n, int k)
{
return dequantize_q3_K(a, b +n*k/256*110, k);
}
static void* _dequantize_q6_K(void * restrict a, const void * restrict b, int n, int k)
{
return dequantize_q6_K(a, b +n*k/256*(256/2 +256/4 +256/16 +2), k);
}
static void* _dequantize_q4_0(void * restrict a, const void * restrict b, int n, int k)
{
return dequantize_q4_0(a, b +n*(k/32*18), k);
}
static void* _dequantize_memcpy(void * restrict a, const void * restrict b, int n, int k)
{
return memcpy(a, b +n*k*sizeof(real), k*sizeof(real));
}
//---------------------------------------------------------
// utilities
static long time_in_ms()
{
// return time in milliseconds, for benchmarking the model speed
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
return time.tv_sec * 1000 + time.tv_nsec / 1000000;
}
uint64_t rng_seed;
static uint32_t random_u32()
{
// xorshift rng: https://en.wikipedia.org/wiki/Xorshift#xorshift.2A
rng_seed ^= rng_seed >> 12;
rng_seed ^= rng_seed << 25;
rng_seed ^= rng_seed >> 27;
return (rng_seed * 0x2545F4914F6CDD1Dull) >> 32;
}
static float random_f32()
{
// random float32 in [0,1)
return (random_u32() >> 8) / 16777216.0;
}
//---------------------------------------------------------
// define struct
static void* (*dequantize)(void * restrict, const void * restrict, int, int) = _dequantize_memcpy;
static void (*quantize)(int8_t*, real*, int) = no_quantize;
static void (*matmul)(real* restrict, void* restrict, void* restrict, int, int);
#define CATS_NAME_MAX 48
#define CATS_MAX_DIM 4
typedef struct {
char name[CATS_NAME_MAX];
int type;
uint32_t n_dim;
uint64_t dim[CATS_MAX_DIM];
void *data;
void (*quantize)(int8_t*, real*, int);
void (*matmul)(real* restrict, void* restrict, void* restrict, int, int);
uint64_t size; // size of the file
size_t offset; // offset of the file
} cats_tensor;
#define CATS_LLAMA_LAYER 256 // 32
typedef struct {
// GGML header
uint32_t n_vocab; // vocab size: 32000
uint32_t n_embd; // dimention: 4096
uint32_t n_mult; // 256
uint32_t n_head; // 32
uint32_t n_layer; // 32
uint32_t n_rot; // 128
uint32_t ftype;
// optional data
uint32_t n_hidden; // hidden dimention
uint32_t n_kv_head;
uint32_t seq_len; // max sequence length
// vocab
char **vocab;
real *score;
uint8_t byte_pieces[512]; // stores all single-byte strings
uint32_t max_token_length;
// weights
cats_tensor tensor[3+9*CATS_LLAMA_LAYER];
cats_tensor *token_embedding_table; // (vocab_size, dim)
cats_tensor *rms_att_weight[CATS_LLAMA_LAYER]; // (layer, dim) rmsnorm weights
cats_tensor *rms_ffn_weight[CATS_LLAMA_LAYER]; // (layer, dim)
cats_tensor *wq[CATS_LLAMA_LAYER]; // (layer, dim, n_heads * head_size)
cats_tensor *wk[CATS_LLAMA_LAYER]; // (layer, dim, n_kv_heads * head_size)
cats_tensor *wv[CATS_LLAMA_LAYER]; // (layer, dim, n_kv_heads * head_size)
cats_tensor *wo[CATS_LLAMA_LAYER]; // (layer, n_heads * head_size, dim)
cats_tensor *w1[CATS_LLAMA_LAYER]; // (layer, hidden_dim, dim)
cats_tensor *w2[CATS_LLAMA_LAYER]; // (layer, dim, hidden_dim)
cats_tensor *w3[CATS_LLAMA_LAYER]; // (layer, hidden_dim, dim)
cats_tensor *rms_final_weight; // (dim,)
cats_tensor *wcls; // (optional) classifier weights for the logits, on the last layer
// state
real *x; // activation at current time stamp (dim,)
real *xb; // same, but inside a residual branch (dim,)
real *xb2; // an additional buffer just for convenience (dim,)
real *hb; // buffer for hidden dimension in the ffn (hidden_dim,)
real *hb2; // buffer for hidden dimension in the ffn (hidden_dim,)
real *q; // query (dim,)
// real *k; // key (dim,)
// real *v; // value (dim,)
real *att; // buffer for scores/attention values (n_heads, seq_len)
real *logits; // output logits
real *key_cache; // (layer, seq_len, dim)
real *value_cache; // (layer, seq_len, dim)
// parameter
int steps; // max number of steps to run for, 0: use seq_len
real temperature; // 0.0 = greedy deterministic. 1.0 = original. don't set higher
real topk; // top-k sampling
real topp; // top-p in nucleus sampling. 1.0 = off. 0.9 works well
//
int* prompt_tokens;
int num_prompt_tokens;
int next;
int token;
int pos;
} cats_llm_model;
//---------------------------------------------------------
static void cats_llm_malloc(cats_llm_model* m)
{
// we calloc instead of malloc to keep valgrind happy
int kv_dim = (m->n_embd * m->n_kv_head) / m->n_head;
m->x = calloc(m->n_embd, sizeof(real));
m->xb = calloc(m->n_embd, sizeof(real));
m->xb2 = calloc(m->n_embd, sizeof(real));
m->hb = calloc(m->n_hidden, sizeof(real));
m->hb2 = calloc(m->n_hidden, sizeof(real));
m->q = calloc(m->n_embd, sizeof(real));
// m->k = calloc(kv_dim, sizeof(real));
// m->v = calloc(kv_dim, sizeof(real));
m->att = calloc(m->n_head * m->seq_len, sizeof(real));
m->logits = calloc(m->n_vocab, sizeof(real));
m->key_cache = calloc(m->n_layer * m->seq_len * kv_dim, sizeof(real));
m->value_cache = calloc(m->n_layer * m->seq_len * kv_dim, sizeof(real));
// ensure all mallocs went fine
if (!m->x || !m->xb || !m->xb2 || !m->hb || !m->hb2 || !m->q
|| /*!m->k || !m->v ||*/ !m->att || !m->logits || !m->key_cache
|| !m->value_cache) {
fprintf(stderr, "malloc_run_state: malloc failed!\n");
exit(1);
}
size_t size;
size = m->n_embd*4 +m->n_hidden*2 +m->n_embd +m->n_embd*m->seq_len +m->n_vocab +m->n_layer * m->seq_len * kv_dim *2;
printf("memory: %6.2f MB (%ld bytes)\n", size/(1024.0*1024.0), size);
#ifdef GPGPU
matmul_gpu_init();
#endif
}
static void cats_llm_free(cats_llm_model* m)
{
#ifdef GPGPU
matmul_gpu_term();
#endif
free(m->x);
free(m->xb);
free(m->xb2);
free(m->hb);
free(m->hb2);
free(m->q);
// free(m->k);
// free(m->v);
free(m->att);
free(m->logits);
free(m->key_cache);
free(m->value_cache);
for (int i=0; i<m->n_vocab; i++) {
free(m->vocab[i]);
}
free(m->vocab);
free(m->score);
free(m->token_embedding_table->data);
m->token_embedding_table->data = NULL;
free(m->rms_final_weight->data);
if (m->wcls->data) free(m->wcls->data);
for (int i=0; i<m->n_layer; i++) {
free(m->rms_att_weight[i]->data);
free(m->wq[i]->data);
free(m->wk[i]->data);
free(m->wv[i]->data);
free(m->wo[i]->data);
free(m->rms_ffn_weight[i]->data);
free(m->w1[i]->data);
free(m->w2[i]->data);
free(m->w3[i]->data);
}
}
//---------------------------------------------------------
// neural net blocks
// Root Mean Square Normalization
static inline void rmsnorm(real* o, real* x, real* weight, int size)
{
// calculate sum of squares
real ss = 0.0;
for (int j=0; j<size; j++) {
ss += x[j] * x[j];
}
ss /= size;
ss += 1e-5;
ss = 1.0 / sqrtf(ss);
// normalize and scale
for (int j=0; j<size; j++) {
o[j] = weight[j] * (ss * x[j]);
}
}
static inline void softmax(real* x, int size)
{
// find max value (for numerical stability)
real max_val = x[0];
for (int i=1; i<size; i++) {
if (x[i] > max_val) {
max_val = x[i];
}
}
// exp and sum
real sum = 0.0;
for (int i=0; i<size; i++) {
x[i] = expf(x[i] - max_val);
sum += x[i];
}
// normalize
real inv_sum = 1.0 / sum;
for (int i=0; i<size; i++) {
// x[i] /= sum;
x[i] *= inv_sum;
}
}
#ifdef __AVX__
//#include "catseye_llama2_matmul.h"
static inline void sgemm7_(const int M, const int N, const int K, const float *A, const float *B, float *C)
{
int j, k;
int nn = N>>1<<1;
int kk = K&~(8-1);
memset(C, 0, M*N*sizeof(real));
#pragma omp parallel for
for (int i=0; i<M; i+=2) {
for (j=0; j<nn; j+=2) {
/*static*/ __attribute__((aligned(32))) real c[4] = {0};
for (int k=0; k<K; k++) {
float A0k = A[i*K+k];
float A1k = A[(i+1)*K+k];
float Bk0 = B[k*N+j];
float Bk1 = B[k*N+j+1];
c[0] += A0k * Bk0;
c[1] += A0k * Bk1;
c[2] += A1k * Bk0;
c[3] += A1k * Bk1;
}
C[i *N+j ] += c[0];
C[i *N+j+1] += c[1];
C[(i+1)*N+j ] += c[2];
C[(i+1)*N+j+1] += c[3];
}
for (; j<N; j++) {
__m256 sum0_vec = _mm256_setzero_ps(); // for AVX2, sum of 8 reals
__m256 sum1_vec = _mm256_setzero_ps();
for (k=0; k<kk; k+=8) {
__m256 a0_vec = _mm256_load_ps(&A[i*K+k]);
__m256 a1_vec = _mm256_load_ps(&A[(i+1)*K+k]);
__m256 b_vec = _mm256_load_ps(&B[k*N+j]);
sum0_vec = _mm256_add_ps(sum0_vec, _mm256_mul_ps(a0_vec, b_vec));
sum1_vec = _mm256_add_ps(sum1_vec, _mm256_mul_ps(a1_vec, b_vec));
}
sum0_vec = _mm256_hadd_ps(sum0_vec, sum0_vec);
sum0_vec = _mm256_hadd_ps(sum0_vec, sum0_vec);
sum1_vec = _mm256_hadd_ps(sum1_vec, sum1_vec);
sum1_vec = _mm256_hadd_ps(sum1_vec, sum1_vec);
static __attribute__((aligned(32))) real c[2];
static __attribute__((aligned(32))) real vals[8];
_mm256_store_ps(vals, sum0_vec);
c[0] = vals[0] + vals[4];
_mm256_store_ps(vals, sum1_vec);
c[1] = vals[0] + vals[4];
// __attribute__((aligned(32))) real c[2] = {0};
for (; k<K; k++) {
float A0k = A[i*K+k];
float A1k = A[(i+1)*K+k];
float Bk0 = B[k*N+j];
c[0] += A0k * Bk0;
c[1] += A1k * Bk0;
}
C[i *N+j ] += c[0];
C[(i+1)*N+j ] += c[1];
}
}
}
// gcc -I/usr/include/openblas/ -lopenblas -o llama2 -Ofast -fopenmp -march=native -mfpmath=both -mavx -ffast-math -funroll-loops llama2.c -lm
//#include <cblas.h>
/*static void matmul(real* o, const real* x, const real* w, int n, int d)
{
sgemm7_(d, 1, n, w, x, o); // 500
// sgemm_block_parallel(d, 1, n, w, x, o);
// cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, d, 1, n, 1.0, w, n, x, 1, 0.0, o, 1); // slow
// cblas_sgemv(CblasRowMajor, CblasNoTrans, d, n, 1.0, w, n, x, 1, 0.0, o, 1);
}*/
// multiply int8_t, add results pairwise twice
static inline __m128i mul_sum_i8_pairs(const __m128i x, const __m128i y)
{
// Get absolute values of x vectors
const __m128i ax = _mm_sign_epi8(x, x);
// Sign the values of the y vectors
const __m128i sy = _mm_sign_epi8(y, x);
// Perform multiplication and create 16-bit values
const __m128i dot = _mm_maddubs_epi16(ax, sy);
const __m128i ones = _mm_set1_epi16(1);
return _mm_madd_epi16(ones, dot);
}
// horizontally add 8 floats
/*static inline float hsum_float_8(const __m256 x)
{
__m128 res = _mm256_extractf128_ps(x, 1);
res = _mm_add_ps(res, _mm256_castps256_ps128(x)); // ( x3+x7, x2+x6, x1+x5, x0+x4 )
res = _mm_add_ps(res, _mm_movehl_ps(res, res)); // ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 )
res = _mm_add_ss(res, _mm_movehdup_ps(res)); // ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 )
return _mm_cvtss_f32(res);
}*/
static inline float hsum_float_8(__m256 acc)
{
/* acc = _mm256_hadd_ps(acc, acc);
acc = _mm256_hadd_ps(acc, acc);
static __attribute__((aligned(32))) float vals[8];
_mm256_store_ps(vals, acc);
return vals[0] + vals[4];*/
acc = _mm256_hadd_ps(acc, acc);
acc = _mm256_hadd_ps(acc, acc);
return _mm_cvtss_f32(_mm_add_ps(_mm256_extractf128_ps(acc, 1), _mm256_castps256_ps128(acc)));
}
static inline __m256i __mm256_cvtepi8_epi32(__m128i v)
{
// expand signed 16bit
__m128i lo = _mm_srai_epi16(v, 8);
// expand 32bit
__m128i lo32_0 = _mm_cvtepi16_epi32(lo);
__m128i lo32_1 = _mm_cvtepi16_epi32(_mm_shuffle_epi32(lo, 0xee));
// convert to __m256i
__m256i lo256 = _mm256_insertf128_si256(_mm256_castsi128_si256(lo32_0), lo32_1, 1);
return lo256;
}
//#define MM256_SET_M128I(a, b) _mm256_insertf128_si256(_mm256_castsi128_si256(b), (a), 1)
#define MM256_SET_M128I(a, b) _mm256_set_m128i((a), (b))
static inline float dot_q4_0_q8_avx(uint8_t* __restrict x, int8_t* __restrict y, int n)
{
const __m128i lowMask = _mm_set1_epi8(0xF);
const __m128i off = _mm_set1_epi8(8);
int nb = n>>5; // 32
__m256 acc = _mm256_setzero_ps();
do {
// Compute combined scale for the block
float delta = cats_fp16_to_fp32(*(uint16_t*)x);
const __m128i tmp = _mm_loadu_si128((const __m128i *)(x+2)); // 4bit * 16 = 32byte
x += 16+2;
__m128i bx = _mm_and_si128(lowMask, tmp); // 4bit -> 8 bit
__m128i by = _mm_loadu_si128((const __m128i *)y); // 8bit * 16 = 128byte
bx = _mm_sub_epi8(bx, off);
const __m128i i32_0 = mul_sum_i8_pairs(bx, by);
bx = _mm_and_si128(lowMask, _mm_srli_epi64(tmp, 4));
by = _mm_loadu_si128((const __m128i *)(y +16));
bx = _mm_sub_epi8(bx, off);
const __m128i i32_1 = mul_sum_i8_pairs(bx, by);
// Convert int32_t to float
__m256 p = _mm256_cvtepi32_ps(MM256_SET_M128I(i32_0, i32_1));
// Apply the scale, and accumulate
delta *= *((float*)(y +32));
y += 32+4;
const __m256 d = _mm256_broadcast_ss(&delta);
acc = _mm256_add_ps(acc, _mm256_mul_ps(d, p));
} while (--nb > 0);
return hsum_float_8(acc);
}
static inline float dot_avx_q4_0(uint8_t* __restrict a, real* __restrict b, int n)
{
int nn = n>>5; // 32
__m256 *b_ptr = (__m256*)b;
const __m128i lowMask = _mm_set1_epi8(0xF);
const __m128i off = _mm_set1_epi8(8);
__m256 acc = _mm256_setzero_ps();
_mm_prefetch(b_ptr, _MM_HINT_T0);
for (int i=0; i<nn; i++) {
uint8_t *p = a +i*18;
_mm_prefetch(p, _MM_HINT_T0);
const __m256 d = _mm256_set1_ps(cats_fp16_to_fp32(*((uint16_t*)p)));
p += 2;
const __m128i w = _mm_loadu_si128((const __m128i *)p); // 16 byte
// _mm_prefetch(b_ptr, _MM_HINT_T0);
__m128i iw0 = _mm_and_si128(lowMask, w); // ((*p & 0x0F) - 8)
iw0 = _mm_sub_epi8(iw0, off);
__m128i iw1 = _mm_and_si128(lowMask, _mm_srli_epi64(w, 4)); // ((*p++ >> 4) - 8)
iw1 = _mm_sub_epi8(iw1, off);
__m256 w0 = _mm256_mul_ps(_mm256_cvtepi32_ps(__mm256_cvtepi8_epi32(_mm_unpacklo_epi8(iw0, iw0))), d);
__m256 w1 = _mm256_mul_ps(_mm256_cvtepi32_ps(__mm256_cvtepi8_epi32(_mm_unpackhi_epi8(iw0, iw0))), d);
__m256 w2 = _mm256_mul_ps(_mm256_cvtepi32_ps(__mm256_cvtepi8_epi32(_mm_unpacklo_epi8(iw1, iw1))), d);
__m256 w3 = _mm256_mul_ps(_mm256_cvtepi32_ps(__mm256_cvtepi8_epi32(_mm_unpackhi_epi8(iw1, iw1))), d);
acc = _mm256_add_ps(acc, _mm256_mul_ps(w0, *b_ptr++));
acc = _mm256_add_ps(acc, _mm256_mul_ps(w1, *b_ptr++));
acc = _mm256_add_ps(acc, _mm256_mul_ps(w2, *b_ptr++));
acc = _mm256_add_ps(acc, _mm256_mul_ps(w3, *b_ptr++));
}
return hsum_float_8(acc);
}
#else
static inline real dot_q4_0_q8(uint8_t* __restrict a, int8_t* __restrict b, int n)
{
int nn = n>>5; // 32
real val = 0.0;
for (int i=0; i<nn; i++) {
uint8_t *p = a +i*18;
real delta = cats_fp16_to_fp32(*((uint16_t*)p));
p += sizeof(uint16_t);
int8_t *b0 = b +i*(32+sizeof(float));
// delta *= *((float*)b0);
// b0 += 4;//sizeof(float);
int8_t *b1 = b0+16;
int32_t ival;
ival = ((int32_t)((*p & 0x0F) - 8) * *b0++); // 0
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
ival += ((int32_t)((*p & 0x0F) - 8) * *b0++);
ival += ((int32_t)((*p++ >> 4) - 8) * *b1++);
delta *= *((float*)b1);
// b1 += 4;//sizeof(float);
val += ival * delta;
}
return val;
}
static inline real dot_q4_0(uint8_t* __restrict a, real* __restrict b, int n)
{
int nn = n>>5; // 32
static __attribute__((aligned(32))) real w[32];
real val = 0.0;
for (int i=0; i<nn; i++) {
uint8_t *p = a +i*18;
real delta = cats_fp16_to_fp32(*((uint16_t*)p));
p += 2;
w[ 0] = (((*p & 0x0F) - 8)*delta);
w[ 1] = (((*p++ >> 4) - 8)*delta);
w[ 2] = (((*p & 0x0F) - 8)*delta);
w[ 3] = (((*p++ >> 4) - 8)*delta);
w[ 4] = (((*p & 0x0F) - 8)*delta);
w[ 5] = (((*p++ >> 4) - 8)*delta);
w[ 6] = (((*p & 0x0F) - 8)*delta);
w[ 7] = (((*p++ >> 4) - 8)*delta);
w[ 8] = (((*p & 0x0F) - 8)*delta);
w[ 9] = (((*p++ >> 4) - 8)*delta);
w[10] = (((*p & 0x0F) - 8)*delta);
w[11] = (((*p++ >> 4) - 8)*delta);
w[12] = (((*p & 0x0F) - 8)*delta);
w[13] = (((*p++ >> 4) - 8)*delta);
w[14] = (((*p & 0x0F) - 8)*delta);
w[15] = (((*p++ >> 4) - 8)*delta);
w[16] = (((*p & 0x0F) - 8)*delta);