okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1a (451f3e8a6): own-stack phase 1A and cleanup 5.4; the ggml/MMQ sources the engines build are vendored in third_party/strata-ggml (frozen at the pin, manifest and check), default engine builds need no llama.cpp download, the TQ overlay is plain files, CMakeLists.txt is split into cmake/backends/*; every engine unchanged (CUDA/HIP gfx1201/gfx1151/SYCL device code identical, SYCL 22/22 checksums, Metal 104/105 objects with only __TIME__ differing, CUDA tokens 26/26); release scripts still pass -DSTRATA_GGML_DIR (owner go 11-08)508e6999a

main
57.0 KiB1714 linesraw
1#include "ggml.h"
2#include "ggml-backend.h"
3#include "ggml-impl.h"
4#include "gguf.h"
5
6#include <cinttypes>
7#include <cstddef>
8#include <cstdint>
9#include <cstdio>
10#include <cstdlib>
11#include <cstring>
12#include <cerrno>
13#include <map>
14#include <new>
15#include <stdexcept>
16#include <string>
17#include <vector>
18
19#define GGUF_MAX_STRING_LENGTH  (1024*1024*1024)
20#define GGUF_MAX_ARRAY_ELEMENTS (1024*1024*1024)
21
22#ifdef _WIN32
23#    define gguf_ftell _ftelli64
24#    define gguf_fseek _fseeki64
25#else
26#    define gguf_ftell ftello
27#    define gguf_fseek fseeko
28#endif
29
30template <typename T>
31struct type_to_gguf_type;
32
33template <>
34struct type_to_gguf_type<uint8_t> {
35    static constexpr enum gguf_type value = GGUF_TYPE_UINT8;
36};
37
38template <>
39struct type_to_gguf_type<int8_t> {
40    static constexpr enum gguf_type value = GGUF_TYPE_INT8;
41};
42
43template <>
44struct type_to_gguf_type<uint16_t> {
45    static constexpr enum gguf_type value = GGUF_TYPE_UINT16;
46};
47
48template <>
49struct type_to_gguf_type<int16_t> {
50    static constexpr enum gguf_type value = GGUF_TYPE_INT16;
51};
52
53template <>
54struct type_to_gguf_type<uint32_t> {
55    static constexpr enum gguf_type value = GGUF_TYPE_UINT32;
56};
57
58template <>
59struct type_to_gguf_type<int32_t> {
60    static constexpr enum gguf_type value = GGUF_TYPE_INT32;
61};
62
63template <>
64struct type_to_gguf_type<float> {
65    static constexpr enum gguf_type value = GGUF_TYPE_FLOAT32;
66};
67
68template <>
69struct type_to_gguf_type<bool> {
70    static constexpr enum gguf_type value = GGUF_TYPE_BOOL;
71};
72
73template <>
74struct type_to_gguf_type<std::string> {
75    static constexpr enum gguf_type value = GGUF_TYPE_STRING;
76};
77
78template <>
79struct type_to_gguf_type<uint64_t> {
80    static constexpr enum gguf_type value = GGUF_TYPE_UINT64;
81};
82
83template <>
84struct type_to_gguf_type<int64_t> {
85    static constexpr enum gguf_type value = GGUF_TYPE_INT64;
86};
87
88template <>
89struct type_to_gguf_type<double> {
90    static constexpr enum gguf_type value = GGUF_TYPE_FLOAT64;
91};
92
93static const std::map<gguf_type, size_t> GGUF_TYPE_SIZE = {
94    {GGUF_TYPE_UINT8,   sizeof(uint8_t)},
95    {GGUF_TYPE_INT8,    sizeof(int8_t)},
96    {GGUF_TYPE_UINT16,  sizeof(uint16_t)},
97    {GGUF_TYPE_INT16,   sizeof(int16_t)},
98    {GGUF_TYPE_UINT32,  sizeof(uint32_t)},
99    {GGUF_TYPE_INT32,   sizeof(int32_t)},
100    {GGUF_TYPE_FLOAT32, sizeof(float)},
101    {GGUF_TYPE_BOOL,    sizeof(int8_t)},
102    {GGUF_TYPE_STRING,  0}, // undefined
103    {GGUF_TYPE_ARRAY,   0}, // undefined
104    {GGUF_TYPE_UINT64,  sizeof(uint64_t)},
105    {GGUF_TYPE_INT64,   sizeof(int64_t)},
106    {GGUF_TYPE_FLOAT64, sizeof(double)},
107};
108static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
109
110static const std::map<gguf_type, const char *> GGUF_TYPE_NAME = {
111    {GGUF_TYPE_UINT8,   "u8"},
112    {GGUF_TYPE_INT8,    "i8"},
113    {GGUF_TYPE_UINT16,  "u16"},
114    {GGUF_TYPE_INT16,   "i16"},
115    {GGUF_TYPE_UINT32,  "u32"},
116    {GGUF_TYPE_INT32,   "i32"},
117    {GGUF_TYPE_FLOAT32, "f32"},
118    {GGUF_TYPE_BOOL,    "bool"},
119    {GGUF_TYPE_STRING,  "str"},
120    {GGUF_TYPE_ARRAY,   "arr"},
121    {GGUF_TYPE_UINT64,  "u64"},
122    {GGUF_TYPE_INT64,   "i64"},
123    {GGUF_TYPE_FLOAT64, "f64"},
124};
125static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
126
127size_t gguf_type_size(enum gguf_type type) {
128    auto it = GGUF_TYPE_SIZE.find(type);
129    return it == GGUF_TYPE_SIZE.end() ? 0 : it->second;
130}
131
132struct gguf_kv {
133    std::string key;
134
135    bool is_array;
136    enum gguf_type type;
137
138    std::vector<int8_t>      data;
139    std::vector<std::string> data_string;
140
141    template <typename T>
142    gguf_kv(const std::string & key, const T value)
143            : key(key), is_array(false), type(type_to_gguf_type<T>::value) {
144        GGML_ASSERT(!key.empty());
145        data.resize(sizeof(T));
146        memcpy(data.data(), &value, sizeof(T));
147    }
148
149    template <typename T>
150    gguf_kv(const std::string & key, const std::vector<T> & value)
151            : key(key), is_array(true), type(type_to_gguf_type<T>::value) {
152        GGML_ASSERT(!key.empty());
153        data.resize(value.size()*sizeof(T));
154        for (size_t i = 0; i < value.size(); ++i) {
155            const T tmp = value[i];
156            memcpy(data.data() + i*sizeof(T), &tmp, sizeof(T));
157        }
158    }
159
160    gguf_kv(const std::string & key, const std::string & value)
161            : key(key), is_array(false), type(GGUF_TYPE_STRING) {
162        GGML_ASSERT(!key.empty());
163        data_string.push_back(value);
164    }
165
166    gguf_kv(const std::string & key, const std::vector<std::string> & value)
167            : key(key), is_array(true), type(GGUF_TYPE_STRING) {
168        GGML_ASSERT(!key.empty());
169        data_string = value;
170    }
171
172    const std::string & get_key() const {
173        return key;
174    }
175
176    const enum gguf_type & get_type() const {
177        return type;
178    }
179
180    size_t get_ne() const {
181        if (type == GGUF_TYPE_STRING) {
182            const size_t ne = data_string.size();
183            GGML_ASSERT(is_array || ne == 1);
184            return ne;
185        }
186        const size_t type_size = gguf_type_size(type);
187        GGML_ASSERT(data.size() % type_size == 0);
188        const size_t ne = data.size() / type_size;
189        GGML_ASSERT(is_array || ne == 1);
190        return ne;
191    }
192
193    template <typename T>
194    const T & get_val(const size_t i = 0) const {
195        GGML_ASSERT(type_to_gguf_type<T>::value == type);
196        if constexpr (std::is_same<T, std::string>::value) {
197            GGML_ASSERT(data_string.size() >= i+1);
198            return data_string[i];
199        }
200        const size_t type_size = gguf_type_size(type);
201        GGML_ASSERT(data.size() % type_size == 0);
202        GGML_ASSERT(data.size() >= (i+1)*type_size);
203        return reinterpret_cast<const T *>(data.data())[i];
204    }
205
206    void cast(const enum gguf_type new_type) {
207        const size_t new_type_size = gguf_type_size(new_type);
208        GGML_ASSERT(data.size() % new_type_size == 0);
209        type = new_type;
210    }
211};
212
213struct gguf_tensor_info {
214    struct ggml_tensor t; // for holding the equivalent info
215    uint64_t offset;      // offset from start of `data`, must be a multiple of `ALIGNMENT`
216};
217
218struct gguf_context {
219    uint32_t version = GGUF_VERSION;
220
221    std::vector<struct gguf_kv> kv;
222    std::vector<struct gguf_tensor_info> info;
223
224    size_t alignment = GGUF_DEFAULT_ALIGNMENT;
225    size_t offset    = 0; // offset of `data` from beginning of file
226    size_t size      = 0; // size of `data` in bytes
227
228    void * data = nullptr;
229};
230
231struct gguf_reader {
232    gguf_reader(
233            gguf_reader_callback_t callback,
234            void * userdata,
235            size_t max_chunk_read,
236            uint64_t data_offset = 0,
237            uint64_t nbytes_remain = 0)
238        : callback(callback),
239          userdata(userdata),
240          max_chunk_read(max_chunk_read),
241          start_offset(data_offset),
242          data_offset(data_offset),
243          nbytes_remain(nbytes_remain) {
244        GGML_ASSERT(max_chunk_read > 0);
245    }
246
247    // helper for remaining bytes in a file
248    static uint64_t file_remain(FILE * file) {
249        const int64_t cur = gguf_ftell(file);
250        if (cur < 0) {
251            return 0;
252        }
253        if (gguf_fseek(file, 0, SEEK_END) != 0) {
254            gguf_fseek(file, cur, SEEK_SET);
255
256            return 0;
257        }
258        const int64_t end = gguf_ftell(file);
259        if (end < 0) {
260            gguf_fseek(file, cur, SEEK_SET);
261
262            return 0;
263        }
264        gguf_fseek(file, cur, SEEK_SET);
265        return static_cast<uint64_t>(end - cur);
266    }
267
268    template <typename T>
269    bool read(T & dst) const {
270        const size_t size = sizeof(dst);
271        if (size > nbytes_remain) {
272            return false;
273        }
274        return read_raw(&dst, size) == size;
275    }
276
277    template <typename T>
278    bool read(std::vector<T> & dst, const size_t n) const {
279        if (n > GGUF_MAX_ARRAY_ELEMENTS) {
280            return false;
281        }
282        if constexpr (std::is_same<T, std::string>::value) {
283            // strings are prefixed with their length, so we need to account for that
284            if (n > SIZE_MAX / sizeof(uint64_t)) {
285                return false;
286            }
287            if (nbytes_remain < n * sizeof(uint64_t)) {
288                return false;
289            }
290        } else {
291            if (n > SIZE_MAX / sizeof(T)) {
292                return false;
293            }
294            if (nbytes_remain < n * sizeof(T)) {
295                return false;
296            }
297        }
298        dst.resize(n);
299        for (size_t i = 0; i < dst.size(); ++i) {
300            if constexpr (std::is_same<T, bool>::value) {
301                bool tmp;
302                if (!read(tmp)) {
303                    return false;
304                }
305                dst[i] = tmp;
306            } else {
307                if (!read(dst[i])) {
308                    return false;
309                }
310            }
311        }
312        return true;
313    }
314
315    bool read(bool & dst) const {
316        int8_t tmp = -1;
317        if (!read(tmp)) {
318            return false;
319        }
320        dst = tmp != 0;
321        return true;
322    }
323
324    bool read(enum ggml_type & dst) const {
325        int32_t tmp = -1;
326        if (!read(tmp)) {
327            return false;
328        }
329        dst = ggml_type(tmp);
330        return true;
331    }
332
333    bool read(enum gguf_type & dst) const {
334        int32_t tmp = -1;
335        if (!read(tmp)) {
336            return false;
337        }
338        dst = gguf_type(tmp);
339        return true;
340    }
341
342    bool read(std::string & dst) const {
343        uint64_t size = 0;
344        if (!read(size)) {
345            return false;
346        }
347        if (size > GGUF_MAX_STRING_LENGTH) {
348            GGML_LOG_ERROR("%s: string length %" PRIu64 " exceeds maximum %" PRIu64 "\n", __func__, size, (uint64_t) GGUF_MAX_STRING_LENGTH);
349            return false;
350        }
351        if (size > nbytes_remain) {
352            GGML_LOG_ERROR("%s: string length %" PRIu64 " exceeds remaining file size %" PRIu64 " bytes\n", __func__, size, nbytes_remain);
353            return false;
354        }
355        dst.resize(static_cast<size_t>(size));
356        return read_raw(dst.data(), static_cast<size_t>(size)) == size;
357    }
358
359    bool read(void * dst, const size_t size) const {
360        if (size > nbytes_remain) {
361            return false;
362        }
363        return read_raw(dst, size) == size;
364    }
365
366    uint64_t tell() const {
367        return data_offset;
368    }
369
370    // position in the file where the GGUF data starts, alignment is relative to it, not to the file
371    uint64_t start() const {
372        return start_offset;
373    }
374
375    bool seek(uint64_t absolute_offset) const {
376        const uint64_t end_offset = uint64_t(data_offset) + nbytes_remain;
377        if (absolute_offset > end_offset) {
378            return false;
379        }
380
381        data_offset = absolute_offset;
382        nbytes_remain = end_offset - absolute_offset;
383
384        return true;
385    }
386
387private:
388    size_t read_raw(void * dst, size_t size) const {
389        if (callback == nullptr || size == 0) {
390            return 0;
391        }
392
393        uint8_t * data = static_cast<uint8_t *>(dst);
394        size_t total_nread = 0;
395        bool reached_eof = false;
396
397        while (total_nread < size) {
398            const size_t chunk_size = std::min(max_chunk_read, size - total_nread);
399            if (data_offset + total_nread < data_offset) {
400                break;
401            }
402            const size_t nread = callback(userdata, static_cast<void *>(data + total_nread), data_offset + total_nread, chunk_size);
403            total_nread += nread;
404            if (nread != chunk_size) {
405                reached_eof = true;
406                break;
407            }
408        }
409
410        data_offset += total_nread;
411        GGML_ASSERT(total_nread <= nbytes_remain);
412        nbytes_remain -= total_nread;
413
414        if (reached_eof) {
415            nbytes_remain = 0;
416        }
417
418        return total_nread;
419    }
420
421    gguf_reader_callback_t callback = nullptr;
422    void * userdata = nullptr;
423    size_t max_chunk_read = 0;
424    uint64_t start_offset = 0;
425    mutable uint64_t data_offset = 0;
426    mutable uint64_t nbytes_remain = 0;
427};
428
429struct gguf_context * gguf_init_empty(void) {
430    return new gguf_context;
431}
432
433template<typename T>
434bool 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) {
435    if (is_array) {
436        std::vector<T> value;
437        try {
438            if (!gr.read(value, n)) {
439                return false;
440            }
441        } catch (std::length_error &) {
442            GGML_LOG_ERROR("%s: encountered length_error while reading value for key '%s'\n", __func__, key.c_str());
443            return false;
444        } catch (std::bad_alloc &) {
445            GGML_LOG_ERROR("%s: encountered bad_alloc error while reading value for key '%s'\n", __func__, key.c_str());
446            return false;
447        }
448        kv.emplace_back(key, value);
449    } else {
450        T value;
451        if (!gr.read(value)) {
452            return false;
453        }
454        kv.emplace_back(key, value);
455    }
456    return true;
457}
458
459static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr, struct gguf_init_params params) {
460    struct gguf_context * ctx = new gguf_context;
461
462    bool ok = true;
463
464    // file magic
465    {
466        std::vector<char> magic;
467        ok = ok && gr.read(magic, 4);
468
469        if (!ok) {
470            GGML_LOG_ERROR("%s: failed to read magic\n", __func__);
471            gguf_free(ctx);
472            return nullptr;
473        }
474
475        for (uint32_t i = 0; i < magic.size(); i++) {
476            if (magic[i] != GGUF_MAGIC[i]) {
477                char c0 = isprint(magic[0]) ? magic[0] : '?';
478                char c1 = isprint(magic[1]) ? magic[1] : '?';
479                char c2 = isprint(magic[2]) ? magic[2] : '?';
480                char c3 = isprint(magic[3]) ? magic[3] : '?';
481                GGML_LOG_ERROR("%s: invalid magic characters: '%c%c%c%c', expected 'GGUF'\n", __func__, c0, c1, c2, c3);
482                gguf_free(ctx);
483                return nullptr;
484            }
485        }
486    }
487
488    // header
489    int64_t n_kv      = 0;
490    int64_t n_tensors = 0;
491
492    if (ok && gr.read(ctx->version)) {
493        if (ok && ctx->version == 0) {
494            GGML_LOG_ERROR("%s: bad GGUF version: %" PRIu32 "\n", __func__, ctx->version);
495            ok = false;
496        }
497
498        /*
499         * bit layout is different when reading non-native endian models.
500         * assuming that the GGUF version is 3, the non-native endian model
501         * would read it as 0x30000000. we can use the AND operation against
502         * the last 4 hexadecimal digits to check if the model is the same
503         * endianness as the host system.
504        */
505        if (ok && (ctx->version & 0x0000FFFF) == 0x00000000) {
506            GGML_LOG_ERROR("%s: failed to load model: this GGUF file version %" PRIu32 " is extremely large, is there a mismatch between the host and model endianness?\n", __func__, ctx->version);
507            ok = false;
508        }
509
510        if (ok && ctx->version == 1) {
511            GGML_LOG_ERROR("%s: GGUFv1 is no longer supported, please use a more up-to-date version\n", __func__);
512            ok = false;
513        }
514        if (ok && ctx->version > GGUF_VERSION) {
515            GGML_LOG_ERROR("%s: this GGUF file is version %" PRIu32 " but this software only supports up to version %d\n",
516                __func__, ctx->version, GGUF_VERSION);
517            ok = false;
518        }
519    } else {
520        ok = false;
521    }
522
523    if (ok && gr.read(n_tensors)) {
524        static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
525        if (n_tensors < 0 || n_tensors > int64_t(SIZE_MAX/sizeof(gguf_tensor_info))) {
526            GGML_LOG_ERROR("%s: number of tensors is %" PRIi64 " but must be in [0, %zu]\n",
527                __func__, n_tensors, SIZE_MAX/sizeof(gguf_tensor_info));
528            ok = false;
529        }
530    } else {
531        ok = false;
532    }
533
534    if (ok && gr.read(n_kv)) {
535        static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
536        if (n_kv < 0 || n_kv > int64_t(SIZE_MAX/sizeof(gguf_kv))) {
537            GGML_LOG_ERROR("%s: number of key value pairs is %" PRIi64 " but must be in [0, %zu]\n",
538                    __func__, n_kv, SIZE_MAX/sizeof(gguf_kv));
539            ok = false;
540        }
541    } else {
542        ok = false;
543    }
544
545    if (!ok) {
546        GGML_LOG_ERROR("%s: failed to read header\n", __func__);
547        gguf_free(ctx);
548        return nullptr;
549    }
550
551    // KV pairs
552    {
553        for (int64_t i = 0; ok && i < n_kv; ++i) {
554            std::string key;
555            gguf_type   type     = gguf_type(-1);
556            bool        is_array = false;
557            uint64_t    n        = 1;
558
559            try {
560                ok = ok && gr.read(key);
561            } catch (std::length_error &) {
562                GGML_LOG_ERROR("%s: encountered length_error while reading key %" PRIi64 "\n", __func__, i);
563                ok = false;
564            } catch (std::bad_alloc &) {
565                GGML_LOG_ERROR("%s: encountered bad_alloc error while reading key %" PRIi64 "\n", __func__, i);
566                ok = false;
567            }
568            if (ok && key.empty()) {
569                GGML_LOG_ERROR("%s: key %" PRIi64 " is empty\n", __func__, i);
570                ok = false;
571            }
572            for (size_t j = 0; ok && j < ctx->kv.size(); ++j) {
573                if (key == ctx->kv[j].key) {
574                    GGML_LOG_ERROR("%s: duplicate key '%s' for tensors %zu and %" PRIi64 " \n", __func__, key.c_str(), j, i);
575                    ok = false;
576                }
577            }
578            if (!ok) {
579                break;
580            }
581
582            ok = ok && gr.read(type);
583            if (type == GGUF_TYPE_ARRAY) {
584                is_array = true;
585                ok = ok && gr.read(type);
586                ok = ok && gr.read(n);
587            }
588            if (!ok) {
589                break;
590            }
591
592            switch (type) {
593                case GGUF_TYPE_UINT8:   ok = ok && gguf_read_emplace_helper<uint8_t>    (gr, ctx->kv, key, is_array, n); break;
594                case GGUF_TYPE_INT8:    ok = ok && gguf_read_emplace_helper<int8_t>     (gr, ctx->kv, key, is_array, n); break;
595                case GGUF_TYPE_UINT16:  ok = ok && gguf_read_emplace_helper<uint16_t>   (gr, ctx->kv, key, is_array, n); break;
596                case GGUF_TYPE_INT16:   ok = ok && gguf_read_emplace_helper<int16_t>    (gr, ctx->kv, key, is_array, n); break;
597                case GGUF_TYPE_UINT32:  ok = ok && gguf_read_emplace_helper<uint32_t>   (gr, ctx->kv, key, is_array, n); break;
598                case GGUF_TYPE_INT32:   ok = ok && gguf_read_emplace_helper<int32_t>    (gr, ctx->kv, key, is_array, n); break;
599                case GGUF_TYPE_FLOAT32: ok = ok && gguf_read_emplace_helper<float>      (gr, ctx->kv, key, is_array, n); break;
600                case GGUF_TYPE_BOOL:    ok = ok && gguf_read_emplace_helper<bool>       (gr, ctx->kv, key, is_array, n); break;
601                case GGUF_TYPE_STRING:  ok = ok && gguf_read_emplace_helper<std::string>(gr, ctx->kv, key, is_array, n); break;
602                case GGUF_TYPE_UINT64:  ok = ok && gguf_read_emplace_helper<uint64_t>   (gr, ctx->kv, key, is_array, n); break;
603                case GGUF_TYPE_INT64:   ok = ok && gguf_read_emplace_helper<int64_t>    (gr, ctx->kv, key, is_array, n); break;
604                case GGUF_TYPE_FLOAT64: ok = ok && gguf_read_emplace_helper<double>     (gr, ctx->kv, key, is_array, n); break;
605                case GGUF_TYPE_ARRAY:
606                default:
607                    {
608                        GGML_LOG_ERROR("%s: key '%s' has invalid GGUF type %d\n", __func__, key.c_str(), type);
609                        ok = false;
610                    } break;
611            }
612        }
613
614        if (!ok) {
615            GGML_LOG_ERROR("%s: failed to read key-value pairs\n", __func__);
616            gguf_free(ctx);
617            return nullptr;
618        }
619        GGML_ASSERT(int64_t(ctx->kv.size()) == n_kv);
620
621        const int alignment_idx = gguf_find_key(ctx, GGUF_KEY_GENERAL_ALIGNMENT);
622        if (alignment_idx != -1 && gguf_get_kv_type(ctx, alignment_idx) != GGUF_TYPE_UINT32) {
623            GGML_LOG_ERROR("%s: key '%s' must be of type %s but is %s\n",
624                __func__, GGUF_KEY_GENERAL_ALIGNMENT, gguf_type_name(GGUF_TYPE_UINT32),
625                gguf_type_name(gguf_get_kv_type(ctx, alignment_idx)));
626            gguf_free(ctx);
627            return nullptr;
628        }
629        ctx->alignment = alignment_idx == -1 ? GGUF_DEFAULT_ALIGNMENT : gguf_get_val_u32(ctx, alignment_idx);
630
631        if (ctx->alignment == 0 || (ctx->alignment & (ctx->alignment - 1)) != 0) {
632            GGML_LOG_ERROR("%s: alignment %zu is not a power of 2\n", __func__, ctx->alignment);
633            gguf_free(ctx);
634            return nullptr;
635        }
636    }
637
638    // read the tensor info
639    for (int64_t i = 0; ok && i < n_tensors; ++i) {
640        struct gguf_tensor_info info;
641
642        // tensor name
643        {
644            std::string name;
645            try {
646                ok = ok && gr.read(name);
647            } catch (std::length_error &) {
648                GGML_LOG_ERROR("%s: encountered length_error while reading tensor name %" PRIi64 "\n", __func__, i);
649                ok = false;
650            } catch (std::bad_alloc &) {
651                GGML_LOG_ERROR("%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
652                ok = false;
653            }
654            if (name.length() >= GGML_MAX_NAME) {
655                GGML_LOG_ERROR("%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
656                ok = false;
657                break;
658            }
659            ggml_set_name(&info.t, name.c_str());
660
661            // make sure there are no duplicate tensor names
662            for (int64_t j = 0; ok && j < i; ++j) {
663                if (strcmp(info.t.name, ctx->info[j].t.name) == 0) {
664                    GGML_LOG_ERROR("%s: duplicate tensor name '%s' for tensors %" PRIi64 " and %" PRIi64 "\n", __func__, info.t.name, j, i);
665                    ok = false;
666                    break;
667                }
668            }
669        }
670        if (!ok) {
671            break;
672        }
673
674        // tensor shape
675        {
676            uint32_t n_dims = 0;
677            ok = ok && gr.read(n_dims);
678            if (n_dims > GGML_MAX_DIMS) {
679                GGML_LOG_ERROR("%s: tensor '%s' has invalid number of dimensions: %" PRIu32 " > %" PRIu32 "\n",
680                    __func__, info.t.name, n_dims, GGML_MAX_DIMS);
681                ok = false;
682                break;
683            }
684            for (uint32_t j = 0; ok && j < GGML_MAX_DIMS; ++j) {
685                info.t.ne[j] = 1;
686                if (j < n_dims) {
687                    ok = ok && gr.read(info.t.ne[j]);
688                }
689
690                // check that all ne are non-negative
691                if (info.t.ne[j] < 0) {
692                    GGML_LOG_ERROR("%s: tensor '%s' dimension %" PRIu32 " has invalid number of elements: %" PRIi64 " < 0\n",
693                        __func__, info.t.name, j, info.t.ne[j]);
694                    ok = false;
695                    break;
696                }
697            }
698
699            // check that the total number of elements is representable
700            // (a zero-element tensor is trivially representable; the guard also avoids a division by zero below)
701            if (ok && ggml_nelements(&info.t) > 0 &&
702                ((INT64_MAX/info.t.ne[1] <= info.t.ne[0]) ||
703                 (INT64_MAX/info.t.ne[2] <= info.t.ne[0]*info.t.ne[1]) ||
704                 (INT64_MAX/info.t.ne[3] <= info.t.ne[0]*info.t.ne[1]*info.t.ne[2]))) {
705
706                GGML_LOG_ERROR("%s: total number of elements in tensor '%s' with shape "
707                    "(%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") is >= %" PRIi64 "\n",
708                    __func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], INT64_MAX);
709                ok = false;
710                break;
711            }
712        }
713        if (!ok) {
714            break;
715        }
716
717        // tensor type
718        {
719            ok = ok && gr.read(info.t.type);
720
721            // check that tensor type is within defined range
722            if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
723                GGML_LOG_ERROR("%s: tensor '%s' has invalid ggml type %d. should be in [0, %d)\n",
724                    __func__, info.t.name, info.t.type, GGML_TYPE_COUNT);
725                ok = false;
726                break;
727            }
728            const size_t  type_size = ggml_type_size(info.t.type);
729            const int64_t blck_size = ggml_blck_size(info.t.type);
730
731            // check that row size is divisible by block size
732            if (blck_size == 0 || info.t.ne[0] % blck_size != 0) {
733                GGML_LOG_ERROR("%s: tensor '%s' of type %d (%s) has %" PRId64 " elements per row, "
734                    "not a multiple of block size (%" PRId64 ")\n",
735                    __func__, info.t.name, (int) info.t.type, ggml_type_name(info.t.type), info.t.ne[0], blck_size);
736                ok = false;
737                break;
738            }
739
740            // check that the size of the tensor in bytes is representable
741            if (ok && uint64_t(ggml_nelements(&info.t)/ggml_blck_size(info.t.type)) > SIZE_MAX/ggml_type_size(info.t.type)) {
742                GGML_LOG_ERROR("%s: tensor '%s' with shape (%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") has a size in bytes > %zu\n",
743                    __func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], SIZE_MAX);
744                ok = false;
745                break;
746            }
747
748            // calculate byte offsets given the tensor shape and type
749            info.t.nb[0] = type_size;
750            info.t.nb[1] = info.t.nb[0]*(info.t.ne[0]/blck_size);
751            for (int j = 2; j < GGML_MAX_DIMS; ++j) {
752                info.t.nb[j] = info.t.nb[j - 1]*info.t.ne[j - 1];
753            }
754        }
755        if (!ok) {
756            break;
757        }
758
759        // tensor data offset within buffer
760        ok = ok && gr.read(info.offset);
761
762        ctx->info.push_back(info);
763    }
764
765    if (!ok) {
766        GGML_LOG_ERROR("%s: failed to read tensor info\n", __func__);
767        gguf_free(ctx);
768        return nullptr;
769    }
770    GGML_ASSERT(int64_t(ctx->info.size()) == n_tensors);
771
772    // we require the data section to be aligned, so take into account any padding
773    if (n_tensors > 0 && !gr.seek(gr.start() + GGML_PAD(gr.tell() - gr.start(), ctx->alignment))) {
774        GGML_LOG_ERROR("%s: failed to seek to beginning of data section\n", __func__);
775        gguf_free(ctx);
776        return nullptr;
777    }
778
779    // store the current file offset - this is where the data section starts
780    ctx->offset = gr.tell();
781
782    // compute the total size of the data section, taking into account the alignment
783    {
784        ctx->size = 0;
785        for (size_t i = 0; i < ctx->info.size(); ++i) {
786            const gguf_tensor_info & ti = ctx->info[i];
787            if (ti.offset != ctx->size) {
788                GGML_LOG_ERROR("%s: tensor '%s' has offset %" PRIu64 ", expected %zu\n",
789                    __func__, ti.t.name, ti.offset, ctx->size);
790                GGML_LOG_ERROR("%s: failed to read tensor data\n", __func__);
791                gguf_free(ctx);
792                return nullptr;
793            }
794            size_t padded_size = GGML_PAD(ggml_nbytes(&ti.t), ctx->alignment);
795            if (SIZE_MAX - ctx->size < padded_size) {
796                GGML_LOG_ERROR("%s: tensor '%s' size overflow, cannot accumulate size %zu + %zu\n",
797                    __func__, ti.t.name, ctx->size, padded_size);
798                gguf_free(ctx);
799                return nullptr;
800            }
801            ctx->size += padded_size;
802        }
803    }
804
805    // load the tensor data only if requested
806    if (params.ctx != nullptr) {
807        // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
808        // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
809        //   the ggml_tensor structs to the appropriate locations in the binary blob
810
811        // compute the exact size needed for the new ggml_context
812        size_t mem_size = 0;
813        if (params.no_alloc) {
814            if (n_tensors != 0 && SIZE_MAX / n_tensors < ggml_tensor_overhead()) {
815                GGML_LOG_ERROR("%s: memory size overflow while allocating ggml context\n", __func__);
816                gguf_free(ctx);
817                return nullptr;
818            }
819
820            const size_t overhead = n_tensors * ggml_tensor_overhead();
821
822            mem_size = overhead;
823        } else {
824            if ((n_tensors + 1) != 0 && SIZE_MAX / (n_tensors + 1) < ggml_tensor_overhead()) {
825                GGML_LOG_ERROR("%s: memory size overflow while allocating ggml context\n", __func__);
826                gguf_free(ctx);
827                return nullptr;
828            }
829
830            const size_t overhead = (n_tensors + 1) * ggml_tensor_overhead();
831
832            if (SIZE_MAX - overhead < ctx->size) {
833                GGML_LOG_ERROR("%s: memory size overflow while allocating ggml context\n", __func__);
834                gguf_free(ctx);
835                return nullptr;
836            }
837
838            mem_size = overhead + ctx->size;
839        }
840
841        struct ggml_init_params pdata = {
842            /*mem_size   =*/ mem_size,
843            /*mem_buffer =*/ nullptr,
844            /*no_alloc   =*/ params.no_alloc,
845        };
846
847        *params.ctx = ggml_init(pdata);
848        if (*params.ctx == nullptr) {
849            GGML_LOG_ERROR("%s: failed to initialize ggml context for storing tensors\n", __func__);
850            gguf_free(ctx);
851            return nullptr;
852        }
853
854        struct ggml_context * ctx_data = *params.ctx;
855
856        struct ggml_tensor * data = nullptr;
857
858        if (!params.no_alloc) {
859            data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
860
861            ok = ok && data != nullptr;
862
863            if (ok) {
864                ggml_set_name(data, "GGUF tensor data binary blob");
865            }
866
867            // read the binary blob with the tensor data
868            ok = ok && gr.read(data->data, ctx->size);
869
870            if (!ok) {
871                GGML_LOG_ERROR("%s: failed to read tensor data binary blob\n", __func__);
872                ggml_free(ctx_data);
873                *params.ctx = nullptr;
874                gguf_free(ctx);
875                return nullptr;
876            }
877
878            ctx->data = data->data;
879        }
880
881        ggml_set_no_alloc(ctx_data, true);
882
883        // create the tensors
884        for (size_t i = 0; i < ctx->info.size(); ++i) {
885            const struct gguf_tensor_info & info = ctx->info[i];
886
887            struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
888
889            ok = ok && cur != nullptr;
890
891            if (!ok) {
892                break;
893            }
894
895            ggml_set_name(cur, info.t.name);
896
897            // point the data member to the appropriate location in the binary blob using the tensor info
898            if (!params.no_alloc) {
899                cur->data = (char *) data->data + info.offset;
900            }
901        }
902
903        if (!ok) {
904            GGML_LOG_ERROR("%s: failed to create tensors\n", __func__);
905            ggml_free(ctx_data);
906            *params.ctx = nullptr;
907            gguf_free(ctx);
908            return nullptr;
909        }
910
911        ggml_set_no_alloc(ctx_data, params.no_alloc);
912    }
913
914    return ctx;
915}
916
917struct gguf_context * gguf_init_from_callback(gguf_reader_callback_t callback, void * userdata, size_t max_chunk_read, uint64_t max_expected_size, struct gguf_init_params params) {
918    if (callback == nullptr) {
919        return nullptr;
920    }
921
922    const struct gguf_reader gr(callback, userdata, max_chunk_read == 0 ? SIZE_MAX : max_chunk_read, 0, max_expected_size);
923    return gguf_init_from_reader(gr, params);
924}
925
926struct gguf_file_reader {
927    FILE * file;
928    uint64_t offset;
929};
930
931static size_t gguf_file_reader_callback(void * userdata, void * output, uint64_t offset, size_t len) {
932    GGML_ASSERT(len > 0);
933
934    gguf_file_reader & reader = *static_cast<gguf_file_reader *>(userdata);
935
936    if (reader.offset != offset) {
937        if (offset > INT64_MAX || gguf_fseek(reader.file, static_cast<int64_t>(offset), SEEK_SET) != 0) {
938            return 0;
939        }
940
941        reader.offset = offset;
942    }
943
944    const size_t nread = fread(static_cast<uint8_t *>(output), 1, len, reader.file);
945    reader.offset += nread;
946    return nread;
947}
948
949struct gguf_context * gguf_init_from_file_ptr(FILE * file, struct gguf_init_params params) {
950    if (!file) {
951        return nullptr;
952    }
953
954    const int64_t cur = gguf_ftell(file);
955    if (cur < 0) {
956        return nullptr;
957    }
958
959    gguf_file_reader reader = {
960        /*.file   = */ file,
961        /*.offset = */ static_cast<uint64_t>(cur),
962    };
963    const struct gguf_reader gr(gguf_file_reader_callback, &reader, SIZE_MAX, reader.offset, gguf_reader::file_remain(file));
964    return gguf_init_from_reader(gr, params);
965}
966
967struct gguf_buffer_reader {
968    const uint8_t * data;
969    size_t          size;
970};
971
972static size_t gguf_buffer_reader_callback(void * userdata, void * output, uint64_t offset, size_t len) {
973    GGML_ASSERT(len > 0);
974
975    const gguf_buffer_reader & reader = *static_cast<gguf_buffer_reader *>(userdata);
976
977    if (offset > reader.size || len > reader.size - offset) {
978        return 0;
979    }
980
981    const size_t data_offset = static_cast<size_t>(offset);
982    const size_t nread = std::min(len, reader.size - data_offset);
983    memcpy(static_cast<uint8_t *>(output), reader.data + data_offset, nread);
984    return nread;
985}
986
987struct gguf_context * gguf_init_from_buffer(const void * data, size_t size, struct gguf_init_params params) {
988    if (data == nullptr || size == 0) {
989        return nullptr;
990    }
991
992    gguf_buffer_reader reader = {
993        /*.data = */ static_cast<const uint8_t *>(data),
994        /*.size = */ size,
995    };
996    const struct gguf_reader gr(gguf_buffer_reader_callback, &reader, SIZE_MAX, 0, size);
997    return gguf_init_from_reader(gr, params);
998}
999
1000struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
1001    FILE * file = ggml_fopen(fname, "rb");
1002
1003    if (!file) {
1004        GGML_LOG_ERROR("%s: failed to open GGUF file '%s' (%s)\n", __func__, fname, strerror(errno));
1005        return nullptr;
1006    }
1007
1008    struct gguf_context * result = gguf_init_from_file_ptr(file, params);
1009    fclose(file);
1010    return result;
1011}
1012
1013void gguf_free(struct gguf_context * ctx) {
1014    if (ctx == nullptr) {
1015        return;
1016    }
1017    delete ctx;
1018}
1019
1020const char * gguf_type_name(enum gguf_type type) {
1021    auto it = GGUF_TYPE_NAME.find(type);
1022    return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
1023}
1024
1025uint32_t gguf_get_version(const struct gguf_context * ctx) {
1026    return ctx->version;
1027}
1028
1029size_t gguf_get_alignment(const struct gguf_context * ctx) {
1030    return ctx->alignment;
1031}
1032
1033size_t gguf_get_data_offset(const struct gguf_context * ctx) {
1034    return ctx->offset;
1035}
1036
1037int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
1038    return ctx->kv.size();
1039}
1040
1041int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
1042    // return -1 if key not found
1043    int64_t keyfound = -1;
1044
1045    const int64_t n_kv = gguf_get_n_kv(ctx);
1046
1047    for (int64_t i = 0; i < n_kv; ++i) {
1048        if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
1049            keyfound = i;
1050            break;
1051        }
1052    }
1053
1054    return keyfound;
1055}
1056
1057const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
1058    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1059    return ctx->kv[key_id].get_key().c_str();
1060}
1061
1062enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
1063    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1064    return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
1065}
1066
1067enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id) {
1068    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1069    GGML_ASSERT(ctx->kv[key_id].is_array);
1070    return ctx->kv[key_id].get_type();
1071}
1072
1073const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id) {
1074    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1075    GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
1076    return ctx->kv[key_id].data.data();
1077}
1078
1079const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
1080    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1081    GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
1082    return ctx->kv[key_id].data_string[i].c_str();
1083}
1084
1085size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
1086    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1087
1088    if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
1089        return ctx->kv[key_id].data_string.size();
1090    }
1091
1092    const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
1093    GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
1094    return ctx->kv[key_id].data.size() / type_size;
1095}
1096
1097uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
1098    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1099    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1100    return ctx->kv[key_id].get_val<uint8_t>();
1101}
1102
1103int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
1104    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1105    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1106    return ctx->kv[key_id].get_val<int8_t>();
1107}
1108
1109uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
1110    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1111    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1112    return ctx->kv[key_id].get_val<uint16_t>();
1113}
1114
1115int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
1116    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1117    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1118    return ctx->kv[key_id].get_val<int16_t>();
1119}
1120
1121uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
1122    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1123    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1124    return ctx->kv[key_id].get_val<uint32_t>();
1125}
1126
1127int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
1128    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1129    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1130    return ctx->kv[key_id].get_val<int32_t>();
1131}
1132
1133float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
1134    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1135    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1136    return ctx->kv[key_id].get_val<float>();
1137}
1138
1139uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
1140    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1141    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1142    return ctx->kv[key_id].get_val<uint64_t>();
1143}
1144
1145int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
1146    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1147    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1148    return ctx->kv[key_id].get_val<int64_t>();
1149}
1150
1151double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
1152    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1153    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1154    return ctx->kv[key_id].get_val<double>();
1155}
1156
1157bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
1158    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1159    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1160    return ctx->kv[key_id].get_val<bool>();
1161}
1162
1163const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
1164    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1165    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1166    return ctx->kv[key_id].get_val<std::string>().c_str();
1167}
1168
1169const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
1170    GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
1171    GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
1172    GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
1173    return ctx->kv[key_id].data.data();
1174}
1175
1176int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
1177    return ctx->info.size();
1178}
1179
1180int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
1181    // return -1 if tensor not found
1182    int64_t tensor_id = -1;
1183
1184    const int64_t n_tensors = gguf_get_n_tensors(ctx);
1185
1186    for (int64_t i = 0; i < n_tensors; ++i) {
1187        if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
1188            tensor_id = i;
1189            break;
1190        }
1191    }
1192
1193    return tensor_id;
1194}
1195
1196size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
1197    GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
1198    return ctx->info[tensor_id].offset;
1199}
1200
1201const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
1202    GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
1203    return ctx->info[tensor_id].t.name;
1204}
1205
1206const int64_t * gguf_get_tensor_ne(const struct gguf_context * ctx, int64_t tensor_id) {
1207    GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
1208    return ctx->info[tensor_id].t.ne;
1209}
1210
1211enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
1212    GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
1213    return ctx->info[tensor_id].t.type;
1214}
1215
1216size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
1217    GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
1218    return ggml_nbytes(&ctx->info[tensor_id].t);
1219}
1220
1221int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
1222    const int64_t key_id = gguf_find_key(ctx, key);
1223    if (key_id >= 0) {
1224        ctx->kv.erase(ctx->kv.begin() + key_id);
1225    }
1226    return key_id;
1227}
1228
1229template<typename T>
1230static void gguf_check_reserved_keys(const std::string & key, const T val) {
1231    if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
1232        if constexpr (std::is_same<T, uint32_t>::value) {
1233            GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
1234        } else {
1235            GGML_UNUSED(val);
1236            GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
1237        }
1238    }
1239}
1240
1241void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
1242    gguf_check_reserved_keys(key, val);
1243    gguf_remove_key(ctx, key);
1244    ctx->kv.emplace_back(key, val);
1245}
1246
1247void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
1248    gguf_check_reserved_keys(key, val);
1249    gguf_remove_key(ctx, key);
1250    ctx->kv.emplace_back(key, val);
1251}
1252
1253void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
1254    gguf_check_reserved_keys(key, val);
1255    gguf_remove_key(ctx, key);
1256    ctx->kv.emplace_back(key, val);
1257}
1258
1259void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
1260    gguf_check_reserved_keys(key, val);
1261    gguf_remove_key(ctx, key);
1262    ctx->kv.emplace_back(key, val);
1263}
1264
1265void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
1266    gguf_check_reserved_keys(key, val);
1267    gguf_remove_key(ctx, key);
1268    ctx->kv.emplace_back(key, val);
1269}
1270
1271void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
1272    gguf_check_reserved_keys(key, val);
1273    gguf_remove_key(ctx, key);
1274    ctx->kv.emplace_back(key, val);
1275}
1276
1277void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
1278    gguf_check_reserved_keys(key, val);
1279    gguf_remove_key(ctx, key);
1280    ctx->kv.emplace_back(key, val);
1281}
1282
1283void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
1284    gguf_check_reserved_keys(key, val);
1285    gguf_remove_key(ctx, key);
1286    ctx->kv.emplace_back(key, val);
1287}
1288
1289void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
1290    gguf_check_reserved_keys(key, val);
1291    gguf_remove_key(ctx, key);
1292    ctx->kv.emplace_back(key, val);
1293}
1294
1295void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
1296    gguf_check_reserved_keys(key, val);
1297    gguf_remove_key(ctx, key);
1298    ctx->kv.emplace_back(key, val);
1299}
1300
1301void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
1302    gguf_check_reserved_keys(key, val);
1303    gguf_remove_key(ctx, key);
1304    ctx->kv.emplace_back(key, val);
1305}
1306
1307void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
1308    gguf_check_reserved_keys(key, val);
1309    gguf_remove_key(ctx, key);
1310    ctx->kv.emplace_back(key, std::string(val));
1311}
1312
1313void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n) {
1314    gguf_check_reserved_keys(key, data);
1315    gguf_remove_key(ctx, key);
1316
1317    const size_t nbytes = n*gguf_type_size(type);
1318    std::vector<int8_t> tmp(nbytes);
1319    if (!tmp.empty()) {
1320        memcpy(tmp.data(), data, nbytes);
1321    }
1322    ctx->kv.emplace_back(key, tmp);
1323    ctx->kv.back().cast(type);
1324}
1325
1326void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, size_t n) {
1327    gguf_check_reserved_keys(key, data);
1328    gguf_remove_key(ctx, key);
1329
1330    std::vector<std::string> tmp(n);
1331    for (size_t i = 0; i < n; ++i) {
1332        tmp[i] = data[i];
1333    }
1334    ctx->kv.emplace_back(key, tmp);
1335}
1336
1337// set or add KV pairs from another context
1338void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src) {
1339    const int64_t n_kv = gguf_get_n_kv(src);
1340    for (int64_t i = 0; i < n_kv; ++i) {
1341        const struct gguf_kv & kv = src->kv[i];
1342
1343        if (!kv.is_array) {
1344            switch (kv.get_type()) {
1345                case GGUF_TYPE_UINT8:   gguf_set_val_u8  (ctx, kv.get_key().c_str(), kv.get_val<uint8_t>());             break;
1346                case GGUF_TYPE_INT8:    gguf_set_val_i8  (ctx, kv.get_key().c_str(), kv.get_val<int8_t>());              break;
1347                case GGUF_TYPE_UINT16:  gguf_set_val_u16 (ctx, kv.get_key().c_str(), kv.get_val<uint16_t>());            break;
1348                case GGUF_TYPE_INT16:   gguf_set_val_i16 (ctx, kv.get_key().c_str(), kv.get_val<int16_t>());             break;
1349                case GGUF_TYPE_UINT32:  gguf_set_val_u32 (ctx, kv.get_key().c_str(), kv.get_val<uint32_t>());            break;
1350                case GGUF_TYPE_INT32:   gguf_set_val_i32 (ctx, kv.get_key().c_str(), kv.get_val<int32_t>());             break;
1351                case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, kv.get_key().c_str(), kv.get_val<float>());               break;
1352                case GGUF_TYPE_UINT64:  gguf_set_val_u64 (ctx, kv.get_key().c_str(), kv.get_val<uint64_t>());            break;
1353                case GGUF_TYPE_INT64:   gguf_set_val_i64 (ctx, kv.get_key().c_str(), kv.get_val<int64_t>());             break;
1354                case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, kv.get_key().c_str(), kv.get_val<double>());              break;
1355                case GGUF_TYPE_BOOL:    gguf_set_val_bool(ctx, kv.get_key().c_str(), kv.get_val<bool>());                break;
1356                case GGUF_TYPE_STRING:  gguf_set_val_str (ctx, kv.get_key().c_str(), kv.get_val<std::string>().c_str()); break;
1357                case GGUF_TYPE_ARRAY:
1358                default: GGML_ABORT("invalid type");
1359            }
1360            continue;
1361        }
1362
1363        const size_t ne = kv.get_ne();
1364
1365        switch (kv.get_type()) {
1366            case GGUF_TYPE_UINT8:
1367            case GGUF_TYPE_INT8:
1368            case GGUF_TYPE_UINT16:
1369            case GGUF_TYPE_INT16:
1370            case GGUF_TYPE_UINT32:
1371            case GGUF_TYPE_INT32:
1372            case GGUF_TYPE_FLOAT32:
1373            case GGUF_TYPE_UINT64:
1374            case GGUF_TYPE_INT64:
1375            case GGUF_TYPE_FLOAT64:
1376            case GGUF_TYPE_BOOL: {
1377                gguf_set_arr_data(ctx, kv.get_key().c_str(), kv.get_type(), kv.data.data(), ne);
1378            } break;
1379            case GGUF_TYPE_STRING: {
1380                std::vector<const char *> tmp(ne);
1381                for (size_t j = 0; j < ne; ++j) {
1382                    tmp[j] = kv.data_string[j].c_str();
1383                }
1384                gguf_set_arr_str(ctx, kv.get_key().c_str(), tmp.data(), ne);
1385            } break;
1386            case GGUF_TYPE_ARRAY:
1387            default: GGML_ABORT("invalid type");
1388        }
1389    }
1390}
1391
1392void gguf_add_tensor(
1393             struct gguf_context * ctx,
1394        const struct ggml_tensor * tensor) {
1395    GGML_ASSERT(tensor);
1396    if (gguf_find_tensor(ctx, tensor->name) != -1) {
1397        GGML_ABORT("duplicate tensor name: %s", tensor->name);
1398    }
1399
1400    struct gguf_tensor_info ti;
1401    ti.t = *tensor;
1402    ti.offset = ctx->info.empty() ? 0 :
1403        ctx->info.back().offset + GGML_PAD(ggml_nbytes(&ctx->info.back().t), ctx->alignment);
1404    ctx->info.push_back(ti);
1405}
1406
1407void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
1408    const int64_t tensor_id = gguf_find_tensor(ctx, name);
1409    if (tensor_id < 0) {
1410        GGML_ABORT("tensor not found: %s", name);
1411    }
1412    struct ggml_tensor * tensor = &ctx->info[tensor_id].t;
1413    const size_t  type_size = ggml_type_size(type);
1414    const int64_t blck_size = ggml_blck_size(type);
1415
1416    tensor->type = type;
1417    GGML_ASSERT(tensor->ne[0] % blck_size == 0 && "tensor row size not divisible by block size of new type");
1418
1419    tensor->nb[0] = type_size;
1420    tensor->nb[1] = tensor->nb[0]*(tensor->ne[0]/blck_size);
1421    for (int i = 2; i < GGML_MAX_DIMS; i++) {
1422        tensor->nb[i] = tensor->nb[i - 1]*tensor->ne[i - 1];
1423    }
1424
1425    // update offsets
1426    const int64_t n_tensors = gguf_get_n_tensors(ctx);
1427    for (int64_t i = tensor_id + 1; i < n_tensors; ++i) {
1428        ctx->info[i].offset = ctx->info[i - 1].offset + GGML_PAD(ggml_nbytes(&ctx->info[i - 1].t), ctx->alignment);
1429    }
1430}
1431
1432void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data) {
1433    const int64_t tensor_id = gguf_find_tensor(ctx, name);
1434    if (tensor_id < 0) {
1435        GGML_ABORT("tensor not found: %s", name);
1436    }
1437
1438    ctx->info[tensor_id].t.data = (void *)(uintptr_t)data; // double cast suppresses warning about casting away const
1439}
1440
1441struct gguf_writer_base {
1442    size_t written_bytes {0u};
1443
1444    virtual ~gguf_writer_base(void) = default;
1445
1446    // we bet on devirtualization
1447    virtual void write(int8_t val) = 0;
1448    virtual void write(const std::vector<int8_t> & val) = 0;
1449    virtual void write_tensor_data(const struct gguf_tensor_info & info, size_t offset_data, size_t alignment) = 0;
1450
1451    template <typename T>
1452    void write(const T & val) {
1453        for (size_t i = 0; i < sizeof(val); ++i) {
1454            write(reinterpret_cast<const int8_t *>(&val)[i]);
1455        }
1456    }
1457
1458    void write(const bool & val) {
1459        const int8_t val8 = val ? 1 : 0;
1460        write(val8);
1461    }
1462
1463    void write(const std::string & val) {
1464        {
1465            const uint64_t n = val.length();
1466            write(n);
1467        }
1468        for (size_t i = 0; i < val.length(); ++i) {
1469            write((val.data())[i]);
1470        }
1471    }
1472
1473    void write(const char * val) {
1474        write(std::string(val));
1475    }
1476
1477    void write(const enum ggml_type & val) {
1478        write(int32_t(val));
1479    }
1480
1481    void write(const enum gguf_type & val) {
1482        write(int32_t(val));
1483    }
1484
1485    void write(const struct gguf_kv & kv) {
1486        const uint64_t ne = kv.get_ne();
1487
1488        write(kv.get_key());
1489
1490        if (kv.is_array) {
1491            write(GGUF_TYPE_ARRAY);
1492            write(kv.get_type());
1493            write(ne);
1494        } else {
1495            write(kv.get_type());
1496        }
1497
1498        switch (kv.get_type()) {
1499            case GGUF_TYPE_UINT8:
1500            case GGUF_TYPE_INT8:
1501            case GGUF_TYPE_UINT16:
1502            case GGUF_TYPE_INT16:
1503            case GGUF_TYPE_UINT32:
1504            case GGUF_TYPE_INT32:
1505            case GGUF_TYPE_FLOAT32:
1506            case GGUF_TYPE_UINT64:
1507            case GGUF_TYPE_INT64:
1508            case GGUF_TYPE_FLOAT64: {
1509                write(kv.data);
1510            } break;
1511            case GGUF_TYPE_BOOL: {
1512                for (size_t i = 0; i < ne; ++i) {
1513                    write(kv.get_val<bool>(i));
1514                }
1515            } break;
1516            case GGUF_TYPE_STRING: {
1517                for (size_t i = 0; i < ne; ++i) {
1518                    write(kv.get_val<std::string>(i));
1519                }
1520            } break;
1521            case GGUF_TYPE_ARRAY:
1522            default: GGML_ABORT("invalid type");
1523        }
1524    }
1525
1526    void write_tensor_meta(const struct gguf_tensor_info & info) {
1527        write(info.t.name);
1528
1529        const uint32_t n_dims = ggml_n_dims(&info.t);
1530        write(n_dims);
1531
1532        for (uint32_t j = 0; j < n_dims; ++j) {
1533            write(info.t.ne[j]);
1534        }
1535        write(info.t.type);
1536        write(info.offset);
1537    }
1538
1539    void pad(const size_t alignment) {
1540        while (written_bytes % alignment != 0) {
1541            const int8_t zero = 0;
1542            write(zero);
1543        }
1544    }
1545};
1546
1547// vector buffer based writer
1548struct gguf_writer_buf final : public gguf_writer_base {
1549    std::vector<int8_t> & buf;
1550
1551    gguf_writer_buf(std::vector<int8_t> & buf) : buf(buf) {}
1552
1553    using gguf_writer_base::write;
1554
1555    void write(const int8_t val) override {
1556        buf.push_back(val);
1557        written_bytes++;
1558    }
1559
1560    void write(const std::vector<int8_t> & val) override {
1561        buf.insert(buf.end(), val.begin(), val.end());
1562        written_bytes += val.size();
1563    }
1564
1565    void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) override {
1566        GGML_ASSERT(buf.size() - offset_data == info.offset);
1567
1568        GGML_ASSERT(ggml_is_contiguous(&info.t));
1569        const size_t offset = buf.size();
1570        const size_t nbytes = ggml_nbytes(&info.t);
1571
1572        buf.resize(offset + nbytes);
1573        if (info.t.buffer) {
1574            ggml_backend_tensor_get(&info.t, buf.data() + offset, 0, nbytes);
1575        } else {
1576            GGML_ASSERT(info.t.data);
1577            memcpy(buf.data() + offset, info.t.data, nbytes);
1578        }
1579        written_bytes += nbytes;
1580
1581        pad(alignment);
1582    }
1583};
1584
1585// file based writer
1586struct gguf_writer_file final : public gguf_writer_base {
1587    FILE * file;
1588
1589    gguf_writer_file(FILE* file) : file(file) {}
1590
1591    using gguf_writer_base::write;
1592
1593    void write(const int8_t val) override {
1594        const auto real_val = static_cast<uint8_t>(val);
1595        const auto ret = fputc(real_val, file);
1596        written_bytes++;
1597        if (ret != real_val) {
1598            throw std::runtime_error("unexpected fputc result '" + std::to_string(ret) + "' instead of '" + std::to_string((int)real_val) + "'");
1599        }
1600    }
1601
1602    void write(const std::vector<int8_t> & val) override {
1603        const auto ret = fwrite(val.data(), 1, val.size(), file);
1604        written_bytes += val.size();
1605        if (ret != val.size()) {
1606            throw std::runtime_error("unexpected fwrite number of bytes written, '" + std::to_string(ret) + "' instead of '" + std::to_string(val.size()) + "'");
1607        }
1608    }
1609
1610    void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) override {
1611        GGML_ASSERT(written_bytes - offset_data == info.offset);
1612
1613        GGML_ASSERT(ggml_is_contiguous(&info.t));
1614        const size_t nbytes = ggml_nbytes(&info.t);
1615
1616        std::vector<int8_t> buf(nbytes);
1617        if (info.t.buffer) {
1618            ggml_backend_tensor_get(&info.t, buf.data(), 0, nbytes);
1619        } else {
1620            GGML_ASSERT(info.t.data);
1621            memcpy(buf.data(), info.t.data, nbytes);
1622        }
1623        write(buf);
1624
1625        pad(alignment);
1626    }
1627};
1628
1629template <typename writer_t>
1630static void gguf_write_out(const struct gguf_context * ctx, writer_t & gw, bool only_meta) {
1631    const int64_t n_kv      = gguf_get_n_kv(ctx);
1632    const int64_t n_tensors = gguf_get_n_tensors(ctx);
1633
1634    // write header
1635    gw.write(GGUF_MAGIC[0]);
1636    gw.write(GGUF_MAGIC[1]);
1637    gw.write(GGUF_MAGIC[2]);
1638    gw.write(GGUF_MAGIC[3]);
1639    gw.write(ctx->version);
1640    gw.write(n_tensors);
1641    gw.write(n_kv);
1642
1643    // write key-value pairs
1644    for (int64_t i = 0; i < n_kv; ++i) {
1645        gw.write(ctx->kv[i]);
1646    }
1647
1648    // write tensor info
1649    for (int64_t i = 0; i < n_tensors; ++i) {
1650        gw.write_tensor_meta(ctx->info[i]);
1651    }
1652
1653    // we require the data section to be aligned
1654    gw.pad(ctx->alignment);
1655
1656    if (only_meta) {
1657        return;
1658    }
1659
1660    const size_t offset_data = gw.written_bytes;
1661
1662    // write tensor data
1663    for (int64_t i = 0; i < n_tensors; ++i) {
1664        gw.write_tensor_data(ctx->info[i], offset_data, ctx->alignment);
1665    }
1666}
1667
1668void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta) {
1669    gguf_writer_buf gw(buf);
1670    gguf_write_out(ctx, gw, only_meta);
1671}
1672
1673bool gguf_write_to_file_ptr(const struct gguf_context * ctx, FILE * file, bool only_meta) {
1674    GGML_ASSERT(file);
1675
1676    try {
1677        gguf_writer_file gw(file);
1678        gguf_write_out(ctx, gw, only_meta);
1679    } catch (const std::runtime_error& ex) {
1680        GGML_LOG_ERROR("%s: failed to write GGUF data: %s\n", __func__, ex.what());
1681        return false;
1682    }
1683    return true;
1684}
1685
1686bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
1687    FILE * file = ggml_fopen(fname, "wb");
1688
1689    if (!file) {
1690        GGML_LOG_ERROR("%s: failed to open file '%s' for writing GGUF data\n", __func__, fname);
1691        return false;
1692    }
1693
1694    const bool success = gguf_write_to_file_ptr(ctx, file, only_meta);
1695    if (!success) {
1696        GGML_LOG_ERROR("%s: failed to write GGUF data into '%s'\n", __func__, fname);
1697    }
1698
1699    fclose(file);
1700    return success;
1701}
1702
1703size_t gguf_get_meta_size(const struct gguf_context * ctx) {
1704    // only return size
1705    std::vector<int8_t> buf;
1706    gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
1707    return buf.size();
1708}
1709
1710void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
1711    std::vector<int8_t> buf;
1712    gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
1713    memcpy(data, buf.data(), buf.size());
1714}