-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqnn_gguf.c
More file actions
2166 lines (2010 loc) · 76.5 KB
/
qnn_gguf.c
File metadata and controls
2166 lines (2010 loc) · 76.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Сборка
$ gcc -DTEST_GGUF -O3 -march=native -o test qnn_gguf.c qnn_png.c xxh64.c quarks.c `pkgconf --cflags --libs glib-2.0` -lz -lpng
$ gcc -DTEST_GGUF -O3 -march=native -o test qnn_gguf.c qnn_png.c xxh64.c sha256_ni.c shake256.c quarks.c hmac.c `pkgconf --cflags --libs glib-2.0` -lz -lpng
Тестирование
$ ./test.exe ../../llama.cpp/models/Rombos-Coder-V2.5-Qwen-14b-Q8_0.gguf -v -n blk.1.attn_q.weight -o test.png
Чего надо
Ограничить коэффициенты при квантизации на уровне 1e-5, BF8 (E5M2)
Реализовать кодирование и декодирование BitNet.cpp `I2S`, BitCPM4 `TQ2_0`
Описать высоко производительный CPU+NPU backend __bf16 и __fp16
Загрузка моделей и построение графа, экспорт графа
*/
#define FINITE_ONLY // не проверять NAN
#include "qnn.h"
#include "quarks.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <inttypes.h>
#include <assert.h>
#include <glib.h>
#define GGUF_MAGIC "GGUF"
#define GGUF_VERSION 3
#define GGUF_DEFAULT_ALIGNMENT 32
#define GGUF_MAX_DIMS 4// максимальный размер в файле может отличаться от макс. размерности при вычислениях GGUF_MAX_DIMS>=GGML_MAX_DIMS
// private структура должна приводиться к типу tensor_t и tensor_weight_t.
struct gguf_tensor_info {
uint64_t sdnv; //!< SDNV идентификатор имени тензора (убрать в структуру ggml_tensor)
enum ggml_type type; //!< type of data: FP32, INT32, ...
enum ggml_type op; //!< compute opcode: OP_NONE
size_t ne[GGUF_MAX_DIMS];//!< размеры тензора
//uint32_t n_dims; -- убрал
uint64_t offset; //!< смещение массива данных в файле GGUF, must be a multiple of `ALIGNMENT`, см. параметр модели `general.alignment`
void * data; //!< pointer to data в памяти
size_t size; //!< size of `data` in bytes
struct gguf_str name;// убрать в хеш таблицу .dynstr
// uint64_t hash[4];// 256 битный хеш от тензора в формате SHA256 и xxh64
// uint64_t uuid[2]; // уникальный идентификатор UUIDv5
};
// static_assert(offsetof(struct gguf_tensor_info,ne)==offsetof(tensor_weight_t, ne));
// static_assert(sizeof(struct gguf_tensor_info)==sizeof(tensor_weight_t));
// -------------------
struct {
uint16_t blck_size;
uint16_t type_size;
} type_info[GGML_TYPE_COUNT] = {
[GGML_TYPE_F64] ={1,8},
[GGML_TYPE_F32] ={1,4},
[GGML_TYPE_F16] ={1,2},
[GGML_TYPE_BF16]={1,2},
[GGML_TYPE_I32 ]={1,4},
[GGML_TYPE_Q8_0]={QK8_0, sizeof(block_q8_0)},
[GGML_TYPE_Q8_1]={QK8_1, sizeof(block_q8_1)},
[GGML_TYPE_Q4_0]={QK4_0, sizeof(block_q4_0)},
[GGML_TYPE_Q4_K]={QK_K, sizeof(block_q4_K)},
[GGML_TYPE_Q5_K]={QK_K, sizeof(block_q5_K)},
[GGML_TYPE_Q6_K]={QK_K, sizeof(block_q6_K)},
[GGML_TYPE_Q8_K]={QK_K, sizeof(block_q8_K)},
};
const char* GGML_TYPE_NAME[GGML_TYPE_COUNT] = {
[GGML_TYPE_F64 ] = "F64",
[GGML_TYPE_F32 ] = "F32",
[GGML_TYPE_F16 ] = "F16",
[GGML_TYPE_BF16] = "BF16",
// QNN
[GGML_TYPE_HF8 ] = "HF8", // E4M3 (Intel conversion rules https://www.intel.com/content/www/us/en/developer/articles/technical/introduction-to-oneapi-ml-common-extensions.html)
[GGML_TYPE_BF8 ] = "BF8", // E5M2
// [GGML_TYPE_E4M3FN] = "E4M3FN",// E4M3FN
[GGML_TYPE_Q4_0] = "Q4_0",
[GGML_TYPE_Q4_1] = "Q4_1",
[GGML_TYPE_Q5_0] = "Q5_0",
[GGML_TYPE_Q5_1] = "Q5_1",
[GGML_TYPE_Q8_0] = "Q8_0",
[GGML_TYPE_Q8_1] = "Q8_1",
[GGML_TYPE_Q2_K] = "Q2_K",
[GGML_TYPE_Q3_K] = "Q3_K",
[GGML_TYPE_Q4_K] = "Q4_K",
[GGML_TYPE_Q5_K] = "Q5_K",
[GGML_TYPE_Q6_K] = "Q6_K",
[GGML_TYPE_Q8_K] = "Q8_K",
[GGML_TYPE_IQ2_XXS] = "IQ2_XXS",
[GGML_TYPE_IQ2_XS ] = "IQ2_XS",
[GGML_TYPE_IQ3_XXS] = "IQ3_XXS",
[GGML_TYPE_IQ1_S ] = "IQ1_S",
[GGML_TYPE_IQ4_NL] = "IQ4_NL",
[GGML_TYPE_IQ3_S ] = "IQ3_S",
[GGML_TYPE_IQ2_S ] = "IQ2_S",
[GGML_TYPE_IQ4_XS] = "IQ4_XS",
[GGML_TYPE_I8 ] = "I8",
[GGML_TYPE_I16] = "I16",
[GGML_TYPE_I32] = "I32",
[GGML_TYPE_I64] = "I64",
[GGML_TYPE_IQ1_M] = "IQ1_M",
[GGML_TYPE_I2_S] = "I2_S",
[GGML_TYPE_I8_S] = "I8_S",
[GGML_TYPE_TL1] = "TL1",
// [GGML_TYPE_TL2] = "TL2",
[GGML_TYPE_I2_S] = "I2_S",// BitNet
[GGML_TYPE_TQ1_0] = "TQ1_0",
[GGML_TYPE_TQ2_0] = "TQ2_0",
[GGML_TYPE_MXFP4] = "MXFP4"
};
const size_t GGUF_TYPE_SIZE[GGUF_TYPE_COUNT] = {
[GGUF_TYPE_UINT8 ] = sizeof(uint8_t),
[GGUF_TYPE_INT8 ] = sizeof(int8_t),
[GGUF_TYPE_UINT16] = sizeof(uint16_t),
[GGUF_TYPE_INT16 ] = sizeof(int16_t),
[GGUF_TYPE_UINT32] = sizeof(uint32_t),
[GGUF_TYPE_INT32 ] = sizeof(int32_t),
[GGUF_TYPE_FLOAT32] = sizeof(float),
[GGUF_TYPE_BOOL ] = sizeof(bool),
[GGUF_TYPE_STRING] = sizeof(struct gguf_str),
[GGUF_TYPE_UINT64] = sizeof(uint64_t),
[GGUF_TYPE_INT64 ] = sizeof(int64_t),
[GGUF_TYPE_FLOAT64] = sizeof(double),
[GGUF_TYPE_ARRAY ] = 0, // undefined
};
/* Из FP8 (E4M3) можно сделать FP4 (E2M1) см. CUDA 10.x */
/* Понижение разрядности
FP32 (E8M23) можно разложить на два/три BF16(E8M7) или два FP16 (E5M10)
v2BF16.s0 = FP32_to_BF16(x) // понижение разрядности
v2BF16.s1 = FP32_to_BF16(x-BF16_to_FP32) // _gradient_
BF16 (E8M7) можно представить парой v2FP8_e4m3fn (E4M3) и множитель (E8M0):
v2FP8.s0 = BF16_to_FP8(x, e_max) // понижение разрядности
v2FP8.s1 = BF16_to_FP8(x-FP8_to_BF16(v2FP4.s0) , e_max+4) // остаток
Аналогично:
FP8 (E4M3) можно представить v2FP4 и множитель (E4M0):
v2FP4.s0 = FP8_to_FP4(x, e_max) // понижение разрядности
v2FP4.s1 = FP8_to_FP4(x-FP4_to_FP8(v2FP4.s0) , e_max+2) // остаток
Замечание. При проектировании алгоритмов можно использовать _gradient_ на следующем проходе (timeshift)
в составе операции FMA или MMA. Компенсация ошибки округления!
Вместе с понижением разрядности надо рассматривать методы BLAS
\see <https://docs.nvidia.com/cuda/cublas/>
\see GSF <>
\see (LINALG.md)
Для теста надо выполнять Би-диагонализацию матрицы, QR- и LUP- разложения.
*/
// размер тензора с учетом выравнивания
static size_t _tensor_info_nbytes(struct gguf_tensor_info* info){
return (info->ne[0]*type_info[info->type].type_size/type_info[info->type].blck_size)*info->ne[1];
}
gguf_cxt_t * gguf_init_empty(void) {
gguf_cxt_t * ctx = g_malloc0(sizeof(struct gguf_context));
if (!ctx) {
fprintf(stderr, "%s: failed to allocate memory for context\n", __func__);
return NULL;
}
__builtin_memcpy(ctx->header.magic, GGUF_MAGIC, sizeof(ctx->header.magic));
ctx->header.version = GGUF_VERSION;
ctx->header.n_tensors = 0;
ctx->header.n_kv = 0;
ctx->kv = NULL;
ctx->infos = NULL;
ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
ctx->offset = 0;
ctx->size = 0;
ctx->data = NULL;
return ctx;
}
static bool gguf_fread(FILE * file, void * dst, size_t size, uint64_t *offset) {
size_t res = fread(dst, 1, size, file);
*offset += res;
return res == size;
}
/*! \brief выделяет шаблон имени и индекс
Планируется использовать в RPC протоколе для формирования SDNV идентификаторов объектов `cname_id.index`.
Для идентификации объектов нужен словарь из `cname` - шаблонов имен.
Имя объекта восстанавливается по шаблону путем подстановки индекса в шаблон.
*/
static int _cname_idx(char* name){
int index = 0;
char* s = name;
while (*s!='\0' && !(s[0]=='.' && isdigit(s[1]))) s++;
if (*s!='\0'){
s++;
char * cname = s;
while (isdigit(*s)) index = index*10+(*s++ -'0');
*cname++ = '*';
do {*cname++ = *s++; } while (*s!='\0');// до конца строки
return index;
} else
return -1;
}
/*! \brief кодирование имени тензора в SDNV, сохраняет шаблон имени в хэш таблицу
Критерий выделения индекса - наличие символа '.' и цифры после него. В шаблоне индекс заменяется на '*'.
Возможно тоит модифицировать под два и более индексов.
\note В реализации Quarks используется QUARK_UNDEF=0, как признак неопределенного значения.
Метод _lookup() возвращает 0, если имя не найдено. В структуре хэш таблицы идентификатору 0 соответствует имя "undefined" или пустая строка.
Значение 0 не может быть использовано в качестве идентификатора тензора.
\param ht - указатель на хэш таблицу
\param p - указатель на строку в формате GGUF
\return SDNV - идентификатор содержащий {cname_id, index}, где cname_id - идентификатор шаблона имени, index - индекс слоя
*/
static uint64_t _cname_to_sdnv(QTable_t * ht, const struct gguf_str * p){
int index = 0;
char buf[p->n+2]; // выделить на стеке или выделить в таблице dynstr
char* cname = buf;
const char* s = p->data;
const char* e = p->data+p->n;
while (s<e && !(s[0]=='.' && isdigit(s[1]))) *cname++ = *s++;
if (s<e){
*cname++ = *s++;// '.'
while (s<e && isdigit(*s)) index = index*10+(*s++ -'0');
*cname++ = '*';
while (s<e) {*cname++ = *s++; } ;// до конца строки
} else
index = -1;
*cname++='\0';
uint32_t cname_id = _quark_lookup(ht, buf);
//printf("cname %s idx=%d %d\n", buf, index, cname_id);
if (cname_id==QUARK_UNDEF) {
cname_id = _quark_insert(ht, buf);
//printf("add cname %s\n", buf);
}
uint64_t sdnv=0;
uint8_t *v = (uint8_t *)&sdnv;
v = _sdnv_encode(v, cname_id);
if (index>=0)
v = _sdnv_encode(v, index);
return sdnv;
}
#define STN_UNDEF (~0u)
#define Nbucket 256
/*! \brief Структура хеш таблицы для поиска тензоров в файле GGUF */
typedef struct _HTable HTable_t;
struct _HTable {
uint32_t nbucket; // число признаков, ограничимся 256 например
uint32_t nchain; // длинный список например 1024-256
uint32_t bucket[Nbucket];// два массива подряд =nbucket+nchain
};
// не применяется
static bool gguf_fread_cname(FILE * file, uint8_t * sdnv, uint64_t *offset, QTable_t* ht) {
int64_t len;
bool ok;
ok = gguf_fread(file, &len, sizeof(len), offset);
char buf[len+2];
ok = ok && gguf_fread(file, buf, len, offset);
buf[len]='\0';
int index = _cname_idx(buf);
uint32_t cname_id = _quark_lookup(ht, buf);
if (cname_id==0) cname_id = _quark_insert(ht, buf);
uint8_t *s = sdnv;
s = _sdnv_encode(s, cname_id);
if (index>=0)
s = _sdnv_encode(s, index);
// printf("SDNV %02X%02X%02X%02X\n", sdnv[2],sdnv[1],sdnv[0]);
return ok;
}
static bool gguf_fread_str(FILE * file, struct gguf_str * p, uint64_t *offset) {
p->n = 0;
p->data = NULL;
bool ok;
ok = gguf_fread(file, &p->n, sizeof(p->n), offset);
// early exit if string length is invalid, prevents from integer overflow
if (p->n == SIZE_MAX) {
fprintf(stderr, "%s: invalid string length (%" PRIu64 ")\n", __func__, p->n);
return false;
}
p->data = g_malloc(p->n + 1);
if (p->data==NULL) {
fprintf(stderr, "%s: failed to allocate memory for string of length %" PRIu64 "\n", __func__, p->n);
return false;
}
ok = ok && gguf_fread(file, p->data, p->n, offset);
return ok;
}
/*
uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int key_id) {
// GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
// GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT32);
return ctx->kv[key_id].value.uint32;
}*/
const char * gguf_get_key(const struct gguf_context * ctx, int key_id) {
// GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
return ctx->kv[key_id].key.data;
}
int gguf_find_key(const struct gguf_context * ctx, const char * key) {
int keyfound = -1;// return -1 if key not found
int key_len = strlen(key);
const int n_kv = ctx->header.n_kv;//gguf_get_n_kv(ctx);
for (int i = 0; i < n_kv; ++i) {
if (ctx->kv[i].key.n==key_len && strncmp(key, ctx->kv[i].key.data, key_len) == 0) {
keyfound = i;
break;
}
}
return keyfound;
}
void gguf_free(gguf_cxt_t* ctx){
if(ctx->header.n_tensors)
if(ctx->header.n_kv)
if(ctx->kv)
g_free(ctx->kv);
if(ctx->infos)
g_free(ctx->infos);
g_free(ctx);
}
//#define MWCx_A 0xFFEA
/*
A=FFEA i=7ff4fffe ( 21), P mod 24 =23, A mod 3 =0
A=FFD7 i=7feb7ffe ( 40), P mod 24 = 7, A mod 3 =2
A=FFBD i=7fde7ffe ( 66), P mod 24 =23, A mod 3 =0
A=FFA8 i=7fd3fffe ( 87), P mod 24 =23, A mod 3 =0
A=FF9B i=7fcd7ffe (100), P mod 24 = 7, A mod 3 =2
A=FF81 i=7fc07ffe (126), P mod 24 =23, A mod 3 =0
A=FF80 i=7fbffffe (127), P mod 24 = 7, A mod 3 =2
A=FF7B i=7fbd7ffe (132), P mod 24 =23, A mod 3 =0
A=FF75 i=7fba7ffe (138), P mod 24 =23, A mod 3 =0
A=FF48 i=7fa3fffe (183), P mod 24 =23, A mod 3 =0
A=FF3F i=7f9f7ffe (192), P mod 24 =23, A mod 3 =0
A=FF3C i=7f9dfffe (195), P mod 24 =23, A mod 3 =0
A=FF2C i=7f95fffe (211), P mod 24 = 7, A mod 3 =2
A=FF09 i=7f847ffe (246), P mod 24 =23, A mod 3 =0
A=FF03 i=7f817ffe (252), P mod 24 =23, A mod 3 =0
A=FF00 i=7f7ffffe (255), P mod 24 =23, A mod 3 =0
A=FEEB i=7f757ffe (276), P mod 24 =23, A mod 3 =0
A=FEE4 i=7f71fffe (283), P mod 24 = 7, A mod 3 =2
A=FEA8 i=7f53fffe (343), P mod 24 = 7, A mod 3 =2
A=FEA5 i=7f527ffe (346), P mod 24 = 7, A mod 3 =2
A=FEA0 i=7f4ffffe (351), P mod 24 =23, A mod 3 =0
A=FE94 i=7f49fffe (363), P mod 24 =23, A mod 3 =0
A=FE8B i=7f457ffe (372), P mod 24 =23, A mod 3 =0
A=FE72 i=7f38fffe (397), P mod 24 = 7, A mod 3 =2
A=FE4E i=7f26fffe (433), P mod 24 = 7, A mod 3 =2
A=FE30 i=7f17fffe (463), P mod 24 = 7, A mod 3 =2
A=FE22 i=7f10fffe (477), P mod 24 =23, A mod 3 =0
A=FE15 i=7f0a7ffe (490), P mod 24 = 7, A mod 3 =2
A=FE04 i=7f01fffe (507), P mod 24 =23, A mod 3 =0
*/
#define MWCx_A 0xFF75 // 13 66 66
//#define MWCx_A 0xFF81
//#define MWCx_A 0xFFA8
//#define MWCx_A 0xFE15 18
// #define MWCx_A 0xFEA5 19
uint32_t mwc32_hash (uint8_t *data, int length, const uint32_t A){
//uint32_t P = (A<<16)-1;
uint32_t h = 0xFFFF;
for (int i=0 ; i < length ; i++){
h = h + data[i];
h = (h&0xFFFF)*(MWCx_A) + (h>>16);
// h = ((uint8_t)h)*(MWCx_A<<8) + (h>>8);
}
return h;
}
static
void _htable_init(HTable_t *htable, uint32_t nbucket)
{
htable->nbucket = nbucket;
htable->nchain = 0;
uint32_t i;
for (i=0; i<nbucket; i++){
htable->bucket[i]=STN_UNDEF;
}
}
static
HTable_t * _htable_new(uint32_t nchain)
{
HTable_t *htable = (HTable_t *)malloc(sizeof(HTable_t) + nchain * sizeof(uint32_t));
_htable_init(htable, Nbucket) ;
return htable;
}
static
int32_t _htable_lookup_tensor_info(HTable_t *htable, const struct gguf_str *name, struct gguf_tensor_info * infos)
{
// uint32_t key = fnv_hash(name->data, name->n);
uint32_t key = mwc32_hash(name->data, name->n, MWCx_A);
uint32_t y = htable->bucket[key % (htable->nbucket)];
const uint32_t *chain = htable->bucket + htable->nbucket;
while (y<htable->nchain && y!=STN_UNDEF) {
if (name->n==infos[y].name.n && strncmp(infos[y].name.data, name->data, name->n)==0)
return y;//infos[y].value;
y = chain[y];
}
return -1;
}
static int hyst[Nbucket]={0};
static
uint32_t _htable_insert_tensor_info(HTable_t *htable, const struct gguf_str *name)
{
// uint32_t key = fnv_hash(name->data, name->n);
uint32_t key = mwc32_hash(name->data, name->n, MWCx_A);
hyst[key%Nbucket]++;
uint32_t *chain = htable->bucket + htable->nbucket;
uint32_t y = htable->nchain++;
uint32_t* head = &htable->bucket[key % htable->nbucket];
chain[y] = *head;
*head = y;
return y;
}
/*! \brief
Составляет таблицу информации по файлу
*/
gguf_cxt_t * gguf_init_from_file(const char * fname, uint32_t/* struct gguf_init_params */params) {
FILE * file = fopen(fname, "rb");
if (file==NULL) {
fprintf(stderr, "%s: failed to open '%s': '%s'\n", __func__, fname, strerror(errno));
return NULL;
}
// offset from start of file
uint64_t offset = 0;
int res;
gguf_cxt_t * ctx = g_malloc0(sizeof(struct gguf_context));
if (!ctx) {
fprintf(stderr, "%s: failed to allocate memory for context\n", __func__);
fclose(file);
return NULL;
}
res = gguf_fread(file, &ctx->header, sizeof(ctx->header), &offset);
// read the header
{
ctx->kv = NULL;// key value pairs
ctx->infos = NULL;
ctx->data = NULL;
if (ctx->header.version == 1 ) {
fprintf(stderr, "%s: GGUFv1 is no longer supported. please use a more up-to-date version\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
// sanity-checks to prevent from integer/buffer overflows
res = res && (ctx->header.n_tensors < (SIZE_MAX/2)/sizeof(struct gguf_tensor_info));
// res = res && (ctx->header.n_tensors < (SIZE_MAX/2)/ggml_tensor_overhead());
res = res && (ctx->header.n_kv < (SIZE_MAX/2)/sizeof(struct gguf_kv));
if (!res) {
fprintf(stderr, "%s: failed to read header\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
}
// read the key-value pairs
{
const uint64_t n_kv = ctx->header.n_kv;
ctx->kv = g_malloc0(n_kv* sizeof(struct gguf_kv));
for (uint64_t i = 0; i < n_kv; ++i) {
struct gguf_kv * kv = &ctx->kv[i];
// fprintf(stderr, "%s: reading kv %d\n", __func__, i);
gguf_fread_str(file, &kv->key, &offset);
uint32_t type = 0;
gguf_fread (file, &type, sizeof(type), &offset);
kv->type = type;
// fprintf(stderr, "%s: %3d| %-.29s|\n", __func__, i, kv->key.data);
switch (kv->type) {
case GGUF_TYPE_UINT8:
case GGUF_TYPE_INT8:
case GGUF_TYPE_UINT16:
case GGUF_TYPE_INT16:
case GGUF_TYPE_UINT32:
case GGUF_TYPE_INT32:
case GGUF_TYPE_FLOAT32:
case GGUF_TYPE_UINT64:
case GGUF_TYPE_INT64:
case GGUF_TYPE_FLOAT64:
case GGUF_TYPE_BOOL:
res = res && gguf_fread(file, &kv->value.int32, gguf_type_size(kv->type), &offset); break;
case GGUF_TYPE_STRING:
res = res && gguf_fread_str(file, &kv->value.str, &offset); break;
case GGUF_TYPE_ARRAY:
{
res = res && gguf_fread(file, &kv->value.arr.type, sizeof(kv->value.arr.type), &offset);
res = res && gguf_fread(file, &kv->value.arr.n, sizeof(kv->value.arr.n), &offset);
switch (kv->value.arr.type) {
case GGUF_TYPE_UINT8:
case GGUF_TYPE_INT8:
case GGUF_TYPE_UINT16:
case GGUF_TYPE_INT16:
case GGUF_TYPE_UINT32:
case GGUF_TYPE_INT32:
case GGUF_TYPE_FLOAT32:
case GGUF_TYPE_UINT64:
case GGUF_TYPE_INT64:
case GGUF_TYPE_FLOAT64:
case GGUF_TYPE_BOOL:
{
kv->value.arr.data = g_malloc(kv->value.arr.n* gguf_type_size(kv->value.arr.type));
if (!kv->value.arr.data) {
fprintf(stderr, "%s: failed to allocate memory for array\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
res = res && gguf_fread(file, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type), &offset);
} break;
case GGUF_TYPE_STRING:
{
kv->value.arr.data = g_malloc(kv->value.arr.n* sizeof(struct gguf_str));
if (!kv->value.arr.data) {
fprintf(stderr, "%s: failed to allocate memory for array\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
res = res && gguf_fread_str(file, &((struct gguf_str *) kv->value.arr.data)[j], &offset);
}
} break;
case GGUF_TYPE_ARRAY:
default:
{
fprintf(stderr, "%s: invalid array type %d\n", __func__, kv->value.arr.type);
res = false;
} break;
}
} break;
default:
{
fprintf(stderr, "%s: invalid type %d\n", __func__, kv->type);
res = 0;
} break;
}
if (!res) {
break;
}
}
if (!res) {
fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
}
fprintf(stdout, "info offset: %lu kB\n", (offset/1024));
// read the tensor infos
QTable_t* qt = _quark_new(256, 512);
ctx->qt = qt;
if (ctx->header.n_tensors > 0) {
HTable_t* ht = _htable_new(ctx->header.n_tensors);
ctx->htable = ht;
ctx->infos = g_malloc0(ctx->header.n_tensors * sizeof(struct gguf_tensor_info));
if (!ctx->infos) {
fprintf(stderr, "%s: failed to allocate memory for tensor infos\n", __func__);
fclose(file);
gguf_free(ctx);
return NULL;
}
for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
struct gguf_tensor_info * info = &ctx->infos[i];
for (int j = 0; j < GGUF_MAX_DIMS; ++j) info->ne[j] = 1;
// сразу в струтуру quarks записать
res = res && gguf_fread_str(file, &info->name, &offset);
//res = res && gguf_fread_cname(file, (uint8_t)&info->sdnv, &offset);
info->sdnv = _cname_to_sdnv(qt, &info->name);
uint32_t n_dims = 0;
res = res && gguf_fread (file, &n_dims, sizeof(n_dims), &offset);
res = res && (n_dims <= GGUF_MAX_DIMS);
uint32_t j;
for (j = 0; j < n_dims; ++j) {
uint64_t ne = 0;
res = res && gguf_fread(file, &ne, sizeof(ne), &offset);
info->ne[j] = ne;
}
//for (; j < GGUF_MAX_DIMS; ++j) info->ne[j] = 1;
uint32_t type = 0; // enum может кодироваться в меньшее число байт
res = res && gguf_fread (file, &type, sizeof(type), &offset);
info->type = type;
res = res && gguf_fread (file, &info->offset, sizeof(info->offset), &offset);
// make sure there is no duplicated tensor names
int32_t id = _htable_lookup_tensor_info(ht, &info->name, ctx->infos);
if (id>=0) {res = false;
fprintf(stderr, "%s: tensor already exists #%ld\n", __func__, i);
}
_htable_insert_tensor_info(ht, &info->name);
if (0) for (uint64_t j = 0; j < i && res; ++j) {
if (info->name.n==ctx->infos[j].name.n && strncmp(info->name.data, ctx->infos[j].name.data, info->name.n) == 0) {
fprintf(stderr, "%s: duplicated tensor name %s\n", __func__, info->name.data);
res = false;
}
}
if (!res) {
fprintf(stderr, "%s: failed to read tensor info #%ld\n", __func__, i);
fclose(file);
gguf_free(ctx);
return NULL;
}
}
// тестирование хеш функции - построить гистограмму
printf("=== HTABLE HYST ===\n");
int hh[16] = {0};
for(int k=0;k<Nbucket;k++)
if (ht->bucket[k]!=STN_UNDEF) {
// uint8_t y = ht->bucket[k];
// printf("%3d:%2d '%*s'\n", k, hyst[k], ctx->infos[y].name.n, ctx->infos[y].name.data);
hh[hyst[k]%16] ++;
} else hh[0] ++;
printf("=== HTABLE H HYST ===\n");
for(int k=0;k<16;k++) {
if (hh[k]!=0)
printf("%3d:%2d\n", k, hh[k]);
}
//free(ht);
//_Exit(1);
}
fprintf(stdout, "data offset: %d kB\n", (uint32_t)(ctx->offset/1024));
ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
int alignment_idx = gguf_find_key(ctx, "general.alignment");
if (alignment_idx != -1) {
ctx->alignment = gguf_get_val_u32(ctx, alignment_idx);
}
// we require the data section to be aligned, so take into account any padding
{
const size_t offset_pad = offset % ctx->alignment;
if (offset_pad != 0) {
offset += ctx->alignment - offset_pad;
fseeko(file, offset, SEEK_SET);
}
}
// store the current file offset - this is where the data section starts
ctx->offset = offset;
// compute the total size of the data section, taking into account the alignment
// load the tensor data only if requested
// fprintf(stdout, "data offset: %d kB\n", ctx->offset/1024);
fclose(file);
//_quark_to_csv(qt);
return ctx;
}
/*! \brief построить таблицу имен */
QTable_t* gguf_quarks(gguf_cxt_t* ctx) {
QTable_t* qt = _quark_new(256, 512);
for(int i=0; i< ctx->header.n_tensors; i++){
struct gguf_tensor_info * info = &ctx->infos[i];
uint64_t sdnv = _cname_to_sdnv(qt, &info->name);
info->sdnv = sdnv;
//printf ("SDNV %04llx\n", sdnv);
}
_quark_to_csv(qt);
return qt;
}
/*! \brief вывод в терминал структуры файла */
void gguf_print_header(gguf_cxt_t* ctx){
for(uint64_t i=0; i<ctx->header.n_kv; ++i){
struct gguf_kv *kv = &ctx->kv[i];
fprintf(stdout, "%3ld| %-36.*s|", i, (int)kv->key.n, kv->key.data);
switch(kv->type){
case GGUF_TYPE_BOOL:
fprintf(stdout, "%s\n", kv->value.bool_?"true":"false"); break;
case GGUF_TYPE_UINT8:
case GGUF_TYPE_UINT16:
case GGUF_TYPE_UINT32:
case GGUF_TYPE_UINT64:
fprintf(stdout, "%lu\n", kv->value.uint64); break;
case GGUF_TYPE_INT8:
case GGUF_TYPE_INT16:
case GGUF_TYPE_INT32:
case GGUF_TYPE_INT64:
fprintf(stdout, "%ld\n", kv->value.int64); break;
case GGUF_TYPE_STRING:
fprintf(stdout, "\"%-.*s\"\n", (int)kv->value.str.n, kv->value.str.data); break;
case GGUF_TYPE_FLOAT32:
fprintf(stdout, "%f\n", kv->value.float32); break;
case GGUF_TYPE_FLOAT64:
fprintf(stdout, "%g\n", kv->value.float64); break;
case GGUF_TYPE_ARRAY: {
fprintf(stdout, "%ld[",kv->value.arr.n);
switch (kv->value.arr.type){
case GGUF_TYPE_BOOL:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %s", ((uint8_t *) kv->value.arr.data)[k]?"1":"0");
break;
case GGUF_TYPE_UINT8:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %u", ((uint8_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_INT8:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %d", ((int8_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_UINT16:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %u", ((uint16_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_INT16:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %d", ((int16_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_UINT32:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %u", ((uint32_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_INT32:// этот вариант
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %d", ((int32_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_FLOAT32:// этот вариант
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %f", ((float *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_UINT64:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ )
fprintf(stdout, " %ld", ((uint64_t *) kv->value.arr.data)[k]);
break;
case GGUF_TYPE_STRING:
for (int k=0, offs=0;k< kv->value.arr.n && k<10; k++ ){
struct gguf_str *str =&((struct gguf_str *) kv->value.arr.data)[k];
fprintf(stdout, " \"%-.*s\"", (int)str->n, str->data);
}
break;
default:
fprintf(stdout, "..."); break;
}
fprintf(stdout, "]\n"); break;
} break;
default:
fprintf(stdout, "\n"); break;
}
}
}
#undef GGML_ASSERT
#define GGML_ASSERT(x) if (!(x)) _Exit(0);
enum llama_token_type {
LLAMA_TOKEN_TYPE_UNDEFINED = 0,
LLAMA_TOKEN_TYPE_NORMAL = 1,
LLAMA_TOKEN_TYPE_UNKNOWN = 2,
LLAMA_TOKEN_TYPE_CONTROL = 3,
LLAMA_TOKEN_TYPE_USER_DEFINED = 4,
LLAMA_TOKEN_TYPE_UNUSED = 5,
LLAMA_TOKEN_TYPE_BYTE = 6,
};
void gguf_vocab_token_types(gguf_cxt_t* ctx){
int key = gguf_find_key(ctx, "tokenizer.ggml.token_type");
int key_tokens = gguf_find_key(ctx, "tokenizer.ggml.tokens");
GGML_ASSERT(key>=0);
struct gguf_kv *kv = &ctx->kv[key];
struct gguf_kv *ts = &ctx->kv[key_tokens];
uint32_t hist[8]={0};
uint32_t n_tokens = kv->value.arr.n;
// printf("type=%d\n", kv->value.arr.type);
GGML_ASSERT(kv->value.arr.type==GGUF_TYPE_INT32);
const uint32_t * ttypes = kv->value.arr.data;
for(uint32_t i=0;i<n_tokens; i++){
unsigned tt = ttypes[i];
if (tt<8)
hist[tt]++;
if (tt==LLAMA_TOKEN_TYPE_CONTROL) {
struct gguf_str *str =&((struct gguf_str *) ts->value.arr.data)[i];
printf(" `%-.*s`", (int)str->n, str->data);
}
}
printf("=== T.TYPE HYST [%d]===\n", n_tokens);
for (int i=0; i<8; i++) printf("%d: %d\n", i, hist[i]);
}
static int gguf_debug(gguf_cxt_t* ctx){
gguf_print_header(ctx);
fprintf(stdout, "2. model info:\n");
fprintf(stdout, "| %-30.30s| %-6s| %s | \n", "Name", "quants", "dims");
fprintf(stdout, "|:--- |:--- |:--- |\n");
char buf[32];
for(uint64_t i=0; i<ctx->header.n_tensors; ++i){
struct gguf_tensor_info * info = &ctx->infos[i];
const char* type_name = GGML_TYPE_NAME[info->type];
if (type_name==NULL) {
sprintf(buf, "%d", info->type);
type_name = buf;
}
fprintf(stdout, "| %-30.*s| %-6s| 0x%010lx ", (int)info->name.n,info->name.data, (type_name!=NULL? type_name: "??"), info->offset);
char ch='[';
int n_dims = info->ne[3]==1? info->ne[2]==1? info->ne[1]==1? 1: 2: 3: 4;
for (uint32_t j = 0; j < n_dims; ++j, ch=',') {
fprintf(stdout, "%c%zd", ch, info->ne[j]);
}
fprintf(stdout, "]\n" );
}
// Статистика по типу квантизации и по
fprintf(stdout, "num tensors: %ld\n", ctx->header.n_tensors);
fprintf(stdout, "data offset: %d kB\n", (uint32_t)(ctx->offset/1024));
}
static uint8_t hex2bin(uint8_t c0, uint8_t c1){// 0x30-0x39 0x41-46 0x61-66
unsigned v0 = c0>='a'?c0-'a'+10: (c0>='A'? c0-'A'+10: c0-'0');
unsigned v1 = c1>='a'?c1-'a'+10: (c1>='A'? c1-'A'+10: c1-'0');
return (v1<<0)|(v0<<4);
}
//
static int strtohash(uint8_t* hash, char *s, char** tail, int tlen){
while (isspace(*s)) s++;
for (int i = 0; i<tlen; i+=8){
if (!isxdigit(s[0]) || !isxdigit(s[1])) return -1;
*hash++ = hex2bin(s[0],s[1]);
s+=2;
}
*tail = s;
return 0; // SUCCESS
}
uint8_t* blk_load(const char* path, struct gguf_str * name, uint64_t offset, size_t size );
/*! \brief Загрузить таблицу хэшей из файла .manifest
\return
*/
int gguf_hash_load(gguf_cxt_t * ctx_gguf, const char* path, char* data, size_t size)
{
char* s = data;
char* e = data + size;
char* name = NULL;
uint8_t hash[512/8];
while(s<e && s[0]!='\0'){
if(strncmp(s, "xxh64", 5)==0){
s+=6;
strtohash(hash, s, &s, 64);
//while (isspace(*s)) s++;
uint64_t h64 = __builtin_bswap64(*(uint64_t*)hash);
//h64 = strtoull(s, &s, 16);
while (s[0]!=':' && s[0]!='\0') s++;
if(s[0]==':') {
s++;
name = s;
while (isalnum(*s) || *s=='.'|| *s=='_') s++;
int len = s - name;
// проверить SDNV и загрузить хэш
struct gguf_str str = {len, name};
int y = _htable_lookup_tensor_info(ctx_gguf->htable, &str, ctx_gguf->infos);
if (y>=0) {
struct gguf_tensor_info * info = &ctx_gguf->infos[y];
uint64_t sdnv = info->sdnv;
printf("xxh64: %016"PRIx64" #%04lx :%.*s\n", h64, sdnv, len, name);
size_t size = _tensor_info_nbytes(info);
uint8_t* data = blk_load(path, NULL, info->offset+ctx_gguf->offset, size);
uint64_t h = 0;
if (data != NULL && (h = xxh64(0, data, size))==h64){
//printf("xxh64: %016"PRIx64" %s\n", h, "ok");
} else {
printf("xxh64: %016"PRIx64" offs=%zu, size=%zu %s\n", h, info->offset, size, "fail");
}
g_free(data);
} else {
uint64_t sdnv = ctx_gguf->infos[0].sdnv;
fprintf(stderr, "xxh64: #%04lx :`%.*s` -- not found\n", sdnv, len, name);
}
}
} else if (strncmp(s, "sha256", 6)==0){
s+=7;
strtohash(hash, s, &s, 256);
while (s[0]!=':' && s[0]!='\0') s++;
if(s[0]==':') {
s++;
name = s;
while (isalnum(*s) || *s=='.'|| *s=='_') s++;
int len = s - name;
// проверить SDNV и загрузить хэш
struct gguf_str str = {len, name};
int y = _htable_lookup_tensor_info(ctx_gguf->htable, &str, ctx_gguf->infos);
if (y>=0) {
uint64_t h64 = __builtin_bswap64(*(uint64_t*)hash);
struct gguf_tensor_info * info = &ctx_gguf->infos[y];
printf("sha256: %016"PRIx64" #%04lx :%.*s\n", h64, info->sdnv, len, name);
size_t size = _tensor_info_nbytes(info);
uint8_t* data = blk_load(path, NULL, info->offset+ctx_gguf->offset, size);
extern void sha256(uint8_t *hash, const uint8_t *data, unsigned int len);
sha256(hash, data, size);
uint64_t h = __builtin_bswap64(*(uint64_t*)hash);
if (data != NULL && h ==h64){
// printf("sha256: %016"PRIx64" %s\n", h, "ok");
} else {
printf("sha256: %016"PRIx64" offs=%zu, size=%zu %s\n", h, info->offset, size, "fail");
}
g_free(data);
}
}
int len = s - name;
} else if (strncmp(s, "sha3-256", 8)==0){
s+=9;
strtohash(hash, s, &s, 256);
} else {
fprintf(stderr, "\n");
_Exit(1);
}
// до конца строки
while(s[0]!='\0' && s[0]!='\n') s++;
if (s[0]=='\n') s++;
}
return 0;
}
// ----------------------
typedef struct _MainOptions MainOptions;
struct _MainOptions {
char* input_file;
char* output_file;
char* manifest;
char* group;
char* device;
char* name;// имя параметра для вывода в файл
int overwrite;
int verify; // проверить манифест
int verbose;
int version;
};
static MainOptions options= {
.input_file = NULL,
.output_file = NULL,
.manifest = NULL
};
static GOptionEntry entries[] =
{
{ "input", 'i', 0, G_OPTION_ARG_FILENAME, &options.input_file, "input filename", "*.gguf"},
{ "output", 'o', 0, G_OPTION_ARG_FILENAME, &options.output_file, "output filename", "*.gguf" },
{ "manifest", 'm', 0, G_OPTION_ARG_FILENAME, &options.manifest, "manifest file", "*.manifest" },
{ "name", 'n', 0, G_OPTION_ARG_STRING, &options.name, "name", "blk.*.attn_k.weight" },
{ "overwrite",'O', 0, G_OPTION_ARG_NONE, &options.overwrite, "overwtite output", NULL },
{ "verify", 'V', 0, G_OPTION_ARG_NONE, &options.verify, "verify manifest", NULL },
{ "verbose", 'v', 0, G_OPTION_ARG_NONE, &options.verbose, "Be verbose", NULL },
{ "version", 0 , 0, G_OPTION_ARG_NONE, &options.version, "program info", NULL },
{ NULL }
};
extern int write_png(char *file_name, uint8_t* image, int width, int height);
static inline void get_scale_min_k4(int j, const uint8_t * restrict q, uint8_t * restrict d, uint8_t * restrict m) {
if (j < 4) {
*d = q[j] & 63; *m = q[j + 4] & 63;
} else {
*d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4);
*m = (q[j+4] >> 4) | ((q[j-0] >> 6) << 4);
}
}
float dequantize_row_q4_K(const block_q4_K * restrict x, float * restrict y, int64_t k)
{
// assert(k % QK_K == 0);
const int nb = k / QK_K;
float y_max = 0;
for (int i = 0; i < nb; i++) {
const uint8_t * q = x[i].qs;