-
Notifications
You must be signed in to change notification settings - Fork 10.9k
/
Copy pathgguf.cpp
1329 lines (1120 loc) · 44 KB
/
gguf.cpp
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
#include "ggml.h"
#include "ggml-backend.h"
#include "ggml-impl.h"
#include "gguf.h"
#include <cinttypes>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <new>
#include <stdexcept>
#include <string>
#include <vector>
template <typename T>
struct type_to_gguf_type;
template <>
struct type_to_gguf_type<uint8_t> {
static constexpr enum gguf_type value = GGUF_TYPE_UINT8;
};
template <>
struct type_to_gguf_type<int8_t> {
static constexpr enum gguf_type value = GGUF_TYPE_INT8;
};
template <>
struct type_to_gguf_type<uint16_t> {
static constexpr enum gguf_type value = GGUF_TYPE_UINT16;
};
template <>
struct type_to_gguf_type<int16_t> {
static constexpr enum gguf_type value = GGUF_TYPE_INT16;
};
template <>
struct type_to_gguf_type<uint32_t> {
static constexpr enum gguf_type value = GGUF_TYPE_UINT32;
};
template <>
struct type_to_gguf_type<int32_t> {
static constexpr enum gguf_type value = GGUF_TYPE_INT32;
};
template <>
struct type_to_gguf_type<float> {
static constexpr enum gguf_type value = GGUF_TYPE_FLOAT32;
};
template <>
struct type_to_gguf_type<bool> {
static constexpr enum gguf_type value = GGUF_TYPE_BOOL;
};
template <>
struct type_to_gguf_type<std::string> {
static constexpr enum gguf_type value = GGUF_TYPE_STRING;
};
template <>
struct type_to_gguf_type<uint64_t> {
static constexpr enum gguf_type value = GGUF_TYPE_UINT64;
};
template <>
struct type_to_gguf_type<int64_t> {
static constexpr enum gguf_type value = GGUF_TYPE_INT64;
};
template <>
struct type_to_gguf_type<double> {
static constexpr enum gguf_type value = GGUF_TYPE_FLOAT64;
};
static const std::map<gguf_type, size_t> GGUF_TYPE_SIZE = {
{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(int8_t)},
{GGUF_TYPE_STRING, 0}, // undefined
{GGUF_TYPE_ARRAY, 0}, // undefined
{GGUF_TYPE_UINT64, sizeof(uint64_t)},
{GGUF_TYPE_INT64, sizeof(int64_t)},
{GGUF_TYPE_FLOAT64, sizeof(double)},
};
static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
static const std::map<gguf_type, const char *> GGUF_TYPE_NAME = {
{GGUF_TYPE_UINT8, "u8"},
{GGUF_TYPE_INT8, "i8"},
{GGUF_TYPE_UINT16, "u16"},
{GGUF_TYPE_INT16, "i16"},
{GGUF_TYPE_UINT32, "u32"},
{GGUF_TYPE_INT32, "i32"},
{GGUF_TYPE_FLOAT32, "f32"},
{GGUF_TYPE_BOOL, "bool"},
{GGUF_TYPE_STRING, "str"},
{GGUF_TYPE_ARRAY, "arr"},
{GGUF_TYPE_UINT64, "u64"},
{GGUF_TYPE_INT64, "i64"},
{GGUF_TYPE_FLOAT64, "f64"},
};
static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
size_t gguf_type_size(enum gguf_type type) {
auto it = GGUF_TYPE_SIZE.find(type);
return it == GGUF_TYPE_SIZE.end() ? 0 : it->second;
}
struct gguf_kv {
std::string key;
bool is_array;
enum gguf_type type;
std::vector<int8_t> data;
std::vector<std::string> data_string;
template <typename T>
gguf_kv(const std::string & key, const T value)
: key(key), is_array(false), type(type_to_gguf_type<T>::value) {
GGML_ASSERT(!key.empty());
data.resize(sizeof(T));
memcpy(data.data(), &value, sizeof(T));
}
template <typename T>
gguf_kv(const std::string & key, const std::vector<T> & value)
: key(key), is_array(true), type(type_to_gguf_type<T>::value) {
GGML_ASSERT(!key.empty());
data.resize(value.size()*sizeof(T));
for (size_t i = 0; i < value.size(); ++i) {
const T tmp = value[i];
memcpy(data.data() + i*sizeof(T), &tmp, sizeof(T));
}
}
gguf_kv(const std::string & key, const std::string & value)
: key(key), is_array(false), type(GGUF_TYPE_STRING) {
GGML_ASSERT(!key.empty());
data_string.push_back(value);
}
gguf_kv(const std::string & key, const std::vector<std::string> & value)
: key(key), is_array(true), type(GGUF_TYPE_STRING) {
GGML_ASSERT(!key.empty());
data_string = value;
}
const std::string & get_key() const {
return key;
}
const enum gguf_type & get_type() const {
return type;
}
size_t get_ne() const {
if (type == GGUF_TYPE_STRING) {
const size_t ne = data_string.size();
GGML_ASSERT(is_array || ne == 1);
return ne;
}
const size_t type_size = gguf_type_size(type);
GGML_ASSERT(data.size() % type_size == 0);
const size_t ne = data.size() / type_size;
GGML_ASSERT(is_array || ne == 1);
return ne;
}
template <typename T>
const T & get_val(const size_t i = 0) const {
GGML_ASSERT(type_to_gguf_type<T>::value == type);
if constexpr (std::is_same<T, std::string>::value) {
GGML_ASSERT(data_string.size() >= i+1);
return data_string[i];
}
const size_t type_size = gguf_type_size(type);
GGML_ASSERT(data.size() % type_size == 0);
GGML_ASSERT(data.size() >= (i+1)*type_size);
return reinterpret_cast<const T *>(data.data())[i];
}
void cast(const enum gguf_type new_type) {
const size_t new_type_size = gguf_type_size(new_type);
GGML_ASSERT(data.size() % new_type_size == 0);
type = new_type;
}
};
struct gguf_tensor_info {
struct ggml_tensor t; // for holding the equivalent info
uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
};
struct gguf_context {
uint32_t version = GGUF_VERSION;
std::vector<struct gguf_kv> kv;
std::vector<struct gguf_tensor_info> info;
size_t alignment = GGUF_DEFAULT_ALIGNMENT;
size_t offset = 0; // offset of `data` from beginning of file
size_t size = 0; // size of `data` in bytes
void * data = nullptr;
};
struct gguf_reader {
FILE * file;
gguf_reader(FILE * file) : file(file) {}
template <typename T>
bool read(T & dst) const {
return fread(&dst, 1, sizeof(dst), file) == sizeof(dst);
}
template <typename T>
bool read(std::vector<T> & dst, const size_t n) const {
dst.resize(n);
for (size_t i = 0; i < dst.size(); ++i) {
if constexpr (std::is_same<T, bool>::value) {
bool tmp;
if (!read(tmp)) {
return false;
}
dst[i] = tmp;
} else {
if (!read(dst[i])) {
return false;
}
}
}
return true;
}
bool read(bool & dst) const {
int8_t tmp = -1;
if (!read(tmp)) {
return false;
}
dst = tmp != 0;
return true;
}
bool read(enum ggml_type & dst) const {
int32_t tmp = -1;
if (!read(tmp)) {
return false;
}
dst = ggml_type(tmp);
return true;
}
bool read(enum gguf_type & dst) const {
int32_t tmp = -1;
if (!read(tmp)) {
return false;
}
dst = gguf_type(tmp);
return true;
}
bool read(std::string & dst) const {
uint64_t size = -1;
if (!read(size)) {
return false;
}
dst.resize(size);
return fread(dst.data(), 1, dst.length(), file) == dst.length();
}
bool read(void * dst, const size_t size) const {
return fread(dst, 1, size, file) == size;
}
};
struct gguf_context * gguf_init_empty(void) {
return new gguf_context;
}
template<typename T>
bool gguf_read_emplace_helper(const struct gguf_reader & gr, std::vector<struct gguf_kv> & kv, const std::string & key, const bool is_array, const size_t n) {
if (is_array) {
std::vector<T> value;
try {
if (!gr.read(value, n)) {
return false;
}
} catch (std::length_error &) {
fprintf(stderr, "%s: encountered length_error while reading value for key '%s'\n", __func__, key.c_str());
return false;
} catch (std::bad_alloc &) {
fprintf(stderr, "%s: encountered bad_alloc error while reading value for key '%s'\n", __func__, key.c_str());
return false;
}
kv.emplace_back(key, value);
} else {
T value;
if (!gr.read(value)) {
return false;
}
kv.emplace_back(key, value);
}
return true;
}
struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params) {
const struct gguf_reader gr(file);
struct gguf_context * ctx = new gguf_context;
bool ok = true;
// file magic
{
std::vector<char> magic;
ok = ok && gr.read(magic, 4);
if (!ok) {
fprintf(stderr, "%s: failed to read magic\n", __func__);
gguf_free(ctx);
return nullptr;
}
for (uint32_t i = 0; i < magic.size(); i++) {
if (magic[i] != GGUF_MAGIC[i]) {
fprintf(stderr, "%s: invalid magic characters: '%c%c%c%c', expected 'GGUF'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
gguf_free(ctx);
return nullptr;
}
}
}
// header
int64_t n_kv = 0;
int64_t n_tensors = 0;
if (ok && gr.read(ctx->version)) {
if (ctx->version == 1) {
fprintf(stderr, "%s: GGUFv1 is no longer supported, please use a more up-to-date version\n", __func__);
ok = false;
}
if (ctx->version > GGUF_VERSION) {
fprintf(stderr, "%s: this GGUF file is version %" PRIu32 " but this software only supports up to version %d\n",
__func__, ctx->version, GGUF_VERSION);
ok = false;
}
} else {
ok = false;
}
if (ok && gr.read(n_tensors)) {
static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
if (n_tensors < 0 || n_tensors > int64_t(SIZE_MAX/sizeof(gguf_tensor_info))) {
fprintf(stderr, "%s: number of tensors is %" PRIi64 " but must be in [0, %zu]\n",
__func__, n_tensors, SIZE_MAX/sizeof(gguf_tensor_info));
ok = false;
}
} else {
ok = false;
}
if (ok && gr.read(n_kv)) {
static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
if (n_kv < 0 || n_kv > int64_t(SIZE_MAX/sizeof(gguf_kv))) {
fprintf(stderr, "%s: number of key value pairs is %" PRIi64 " but must be in [0, %zu]\n",
__func__, n_kv, SIZE_MAX/sizeof(gguf_kv));
ok = false;
}
} else {
ok = false;
}
if (!ok) {
fprintf(stderr, "%s: failed to read header\n", __func__);
gguf_free(ctx);
return nullptr;
}
// KV pairs
{
for (int64_t i = 0; ok && i < n_kv; ++i) {
std::string key;
gguf_type type = gguf_type(-1);
bool is_array = false;
uint64_t n = 1;
try {
ok = ok && gr.read(key);
} catch (std::length_error &) {
fprintf(stderr, "%s: encountered length_error while reading key %" PRIi64 "\n", __func__, i);
ok = false;
} catch (std::bad_alloc &) {
fprintf(stderr, "%s: encountered bad_alloc error while reading key %" PRIi64 "\n", __func__, i);
ok = false;
}
for (size_t j = 0; ok && j < ctx->kv.size(); ++j) {
if (key == ctx->kv[j].key) {
fprintf(stderr, "%s: duplicate key '%s' for tensors %zu and %" PRIi64 " \n", __func__, key.c_str(), j, i);
ok = false;
}
}
if (!ok) {
break;
}
ok = ok && gr.read(type);
if (type == GGUF_TYPE_ARRAY) {
is_array = true;
ok = ok && gr.read(type);
ok = ok && gr.read(n);
}
if (!ok) {
break;
}
switch (type) {
case GGUF_TYPE_UINT8: ok = ok && gguf_read_emplace_helper<uint8_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_INT8: ok = ok && gguf_read_emplace_helper<int8_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_UINT16: ok = ok && gguf_read_emplace_helper<uint16_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_INT16: ok = ok && gguf_read_emplace_helper<int16_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_UINT32: ok = ok && gguf_read_emplace_helper<uint32_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_INT32: ok = ok && gguf_read_emplace_helper<int32_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_FLOAT32: ok = ok && gguf_read_emplace_helper<float> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_BOOL: ok = ok && gguf_read_emplace_helper<bool> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_STRING: ok = ok && gguf_read_emplace_helper<std::string>(gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_UINT64: ok = ok && gguf_read_emplace_helper<uint64_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_INT64: ok = ok && gguf_read_emplace_helper<int64_t> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_FLOAT64: ok = ok && gguf_read_emplace_helper<double> (gr, ctx->kv, key, is_array, n); break;
case GGUF_TYPE_ARRAY:
default:
{
fprintf(stderr, "%s: key '%s' has invalid GGUF type %d\n", __func__, key.c_str(), type);
ok = false;
} break;
}
}
if (!ok) {
fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
gguf_free(ctx);
return nullptr;
}
GGML_ASSERT(int64_t(ctx->kv.size()) == n_kv);
const int alignment_idx = gguf_find_key(ctx, GGUF_KEY_GENERAL_ALIGNMENT);
ctx->alignment = alignment_idx == -1 ? GGUF_DEFAULT_ALIGNMENT : gguf_get_val_u32(ctx, alignment_idx);
if (ctx->alignment == 0 || (ctx->alignment & (ctx->alignment - 1)) != 0) {
fprintf(stderr, "%s: alignment %zu is not a power of 2\n", __func__, ctx->alignment);
gguf_free(ctx);
return nullptr;
}
}
// read the tensor info
for (int64_t i = 0; ok && i < n_tensors; ++i) {
struct gguf_tensor_info info;
// tensor name
{
std::string name;
try {
ok = ok && gr.read(name);
} catch (std::length_error &) {
fprintf(stderr, "%s: encountered length_error while reading tensor name %" PRIi64 "\n", __func__, i);
ok = false;
} catch (std::bad_alloc &) {
fprintf(stderr, "%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
ok = false;
}
if (name.length() >= GGML_MAX_NAME) {
fprintf(stderr, "%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
ok = false;
break;
}
ggml_set_name(&info.t, name.c_str());
// make sure there are no duplicate tensor names
for (int64_t j = 0; ok && j < i; ++j) {
if (strcmp(info.t.name, ctx->info[j].t.name) == 0) {
fprintf(stderr, "%s: duplicate tensor name '%s' for tensors %" PRIi64 " and %" PRIi64 "\n", __func__, info.t.name, j, i);
ok = false;
break;
}
}
}
if (!ok) {
break;
}
// tensor shape
{
uint32_t n_dims = -1;
ok = ok && gr.read(n_dims);
if (n_dims > GGML_MAX_DIMS) {
fprintf(stderr, "%s: tensor '%s' has invalid number of dimensions: %" PRIu32 " > %" PRIu32 "\n",
__func__, info.t.name, n_dims, GGML_MAX_DIMS);
ok = false;
break;
}
for (uint32_t j = 0; ok && j < GGML_MAX_DIMS; ++j) {
info.t.ne[j] = 1;
if (j < n_dims) {
ok = ok && gr.read(info.t.ne[j]);
}
// check that all ne are non-negative
if (info.t.ne[j] < 0) {
fprintf(stderr, "%s: tensor '%s' dimension %" PRIu32 " has invalid number of elements: %" PRIi64 " < 0\n",
__func__, info.t.name, j, info.t.ne[j]);
ok = false;
break;
}
}
// check that the total number of elements is representable
if (ok && ((INT64_MAX/info.t.ne[1] <= info.t.ne[0]) ||
(INT64_MAX/info.t.ne[2] <= info.t.ne[0]*info.t.ne[1]) ||
(INT64_MAX/info.t.ne[3] <= info.t.ne[0]*info.t.ne[1]*info.t.ne[2]))) {
fprintf(stderr, "%s: total number of elements in tensor '%s' with shape "
"(%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") is >= %" PRIi64 "\n",
__func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], INT64_MAX);
ok = false;
break;
}
}
if (!ok) {
break;
}
// tensor type
{
ok = ok && gr.read(info.t.type);
// check that tensor type is within defined range
if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
fprintf(stderr, "%s: tensor '%s' has invalid ggml type %d (%s)\n",
__func__, info.t.name, info.t.type, ggml_type_name(info.t.type));
ok = false;
break;
}
const size_t type_size = ggml_type_size(info.t.type);
const int64_t blck_size = ggml_blck_size(info.t.type);
// check that row size is divisible by block size
if (blck_size == 0 || info.t.ne[0] % blck_size != 0) {
fprintf(stderr, "%s: tensor '%s' of type %d (%s) has %" PRId64 " elements per row, "
"not a multiple of block size (%" PRId64 ")\n",
__func__, info.t.name, (int) info.t.type, ggml_type_name(info.t.type), info.t.ne[0], blck_size);
ok = false;
break;
}
// calculate byte offsets given the tensor shape and type
info.t.nb[0] = type_size;
info.t.nb[1] = info.t.nb[0]*(info.t.ne[0]/blck_size);
for (int j = 2; j < GGML_MAX_DIMS; ++j) {
info.t.nb[j] = info.t.nb[j - 1]*info.t.ne[j - 1];
}
}
if (!ok) {
break;
}
// tensor data offset within buffer
ok = ok && gr.read(info.offset);
ctx->info.push_back(info);
}
if (!ok) {
fprintf(stderr, "%s: failed to read tensor info\n", __func__);
gguf_free(ctx);
return nullptr;
}
GGML_ASSERT(int64_t(ctx->info.size()) == n_tensors);
// we require the data section to be aligned, so take into account any padding
if (fseek(file, GGML_PAD(ftell(file), ctx->alignment), SEEK_SET) != 0) {
fprintf(stderr, "%s: failed to seek to beginning of data section\n", __func__);
gguf_free(ctx);
return nullptr;
}
// store the current file offset - this is where the data section starts
ctx->offset = ftell(file);
// compute the total size of the data section, taking into account the alignment
{
ctx->size = 0;
for (size_t i = 0; i < ctx->info.size(); ++i) {
const gguf_tensor_info & ti = ctx->info[i];
if (ti.offset != ctx->size) {
fprintf(stderr, "%s: tensor '%s' has offset %" PRIu64 ", expected %zu\n",
__func__, ti.t.name, ti.offset, ctx->size);
fprintf(stderr, "%s: failed to read tensor data\n", __func__);
gguf_free(ctx);
return nullptr;
}
ctx->size += GGML_PAD(ggml_nbytes(&ti.t), ctx->alignment);
}
}
// load the tensor data only if requested
if (params.ctx != nullptr) {
// if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
// otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
// the ggml_tensor structs to the appropriate locations in the binary blob
// compute the exact size needed for the new ggml_context
const size_t mem_size =
params.no_alloc ?
(n_tensors )*ggml_tensor_overhead() :
(n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
struct ggml_init_params pdata = {
/*mem_size =*/ mem_size,
/*mem_buffer =*/ nullptr,
/*no_alloc =*/ params.no_alloc,
};
*params.ctx = ggml_init(pdata);
if (*params.ctx == nullptr) {
fprintf(stderr, "%s: failed to initialize ggml context for storing tensors\n", __func__);
gguf_free(ctx);
return nullptr;
}
struct ggml_context * ctx_data = *params.ctx;
struct ggml_tensor * data = nullptr;
if (!params.no_alloc) {
data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
ok = ok && data != nullptr;
if (ok) {
ggml_set_name(data, "GGUF tensor data binary blob");
}
// read the binary blob with the tensor data
ok = ok && gr.read(data->data, ctx->size);
if (!ok) {
fprintf(stderr, "%s: failed to read tensor data binary blob\n", __func__);
ggml_free(ctx_data);
*params.ctx = nullptr;
gguf_free(ctx);
return nullptr;
}
ctx->data = data->data;
}
ggml_set_no_alloc(ctx_data, true);
// create the tensors
for (size_t i = 0; i < ctx->info.size(); ++i) {
const struct gguf_tensor_info & info = ctx->info[i];
struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
ok = ok && cur != nullptr;
if (!ok) {
break;
}
ggml_set_name(cur, info.t.name);
// point the data member to the appropriate location in the binary blob using the tensor info
if (!params.no_alloc) {
cur->data = (char *) data->data + info.offset;
}
}
if (!ok) {
fprintf(stderr, "%s: failed to create tensors\n", __func__);
ggml_free(ctx_data);
*params.ctx = nullptr;
gguf_free(ctx);
return nullptr;
}
ggml_set_no_alloc(ctx_data, params.no_alloc);
}
return ctx;
}
struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
FILE * file = ggml_fopen(fname, "rb");
if (!file) {
fprintf(stderr, "%s: failed to open GGUF file '%s'\n", __func__, fname);
return nullptr;
}
struct gguf_context * result = gguf_init_from_file_impl(file, params);
fclose(file);
return result;
}
void gguf_free(struct gguf_context * ctx) {
if (ctx == nullptr) {
return;
}
delete ctx;
}
const char * gguf_type_name(enum gguf_type type) {
auto it = GGUF_TYPE_NAME.find(type);
return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
}
uint32_t gguf_get_version(const struct gguf_context * ctx) {
return ctx->version;
}
size_t gguf_get_alignment(const struct gguf_context * ctx) {
return ctx->alignment;
}
size_t gguf_get_data_offset(const struct gguf_context * ctx) {
return ctx->offset;
}
int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
return ctx->kv.size();
}
int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
// return -1 if key not found
int64_t keyfound = -1;
const int64_t n_kv = gguf_get_n_kv(ctx);
for (int64_t i = 0; i < n_kv; ++i) {
if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
keyfound = i;
break;
}
}
return keyfound;
}
const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
return ctx->kv[key_id].get_key().c_str();
}
enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
}
enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].is_array);
return ctx->kv[key_id].get_type();
}
const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
return ctx->kv[key_id].data.data();
}
const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
return ctx->kv[key_id].data_string[i].c_str();
}
size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
return ctx->kv[key_id].data_string.size();
}
const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
return ctx->kv[key_id].data.size() / type_size;
}
uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<uint8_t>();
}
int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<int8_t>();
}
uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<uint16_t>();
}
int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<int16_t>();
}
uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<uint32_t>();
}
int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<int32_t>();
}
float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<float>();
}
uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<uint64_t>();
}
int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<int64_t>();
}
double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<double>();
}
bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<bool>();
}
const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
return ctx->kv[key_id].get_val<std::string>().c_str();
}
const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
return ctx->kv[key_id].data.data();
}
int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
return ctx->info.size();
}
int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
// return -1 if tensor not found
int64_t tensor_id = -1;
const int64_t n_tensors = gguf_get_n_tensors(ctx);
for (int64_t i = 0; i < n_tensors; ++i) {
if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
tensor_id = i;
break;
}
}
return tensor_id;
}
size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
return ctx->info[tensor_id].offset;
}
const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
return ctx->info[tensor_id].t.name;
}
enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
return ctx->info[tensor_id].t.type;
}
size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
return ggml_nbytes(&ctx->info[tensor_id].t);
}
int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
const int64_t key_id = gguf_find_key(ctx, key);
if (key_id >= 0) {
ctx->kv.erase(ctx->kv.begin() + key_id);
}
return key_id;
}
template<typename T>
static void gguf_check_reserved_keys(const std::string & key, const T val) {
if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
if constexpr (std::is_same<T, uint32_t>::value) {
GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
} else {
GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
}
}
}
void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
gguf_check_reserved_keys(key, val);
gguf_remove_key(ctx, key);
ctx->kv.emplace_back(key, val);
}
void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {