JohannesGaessler commited on
Commit
92311a3
·
1 Parent(s): 226358f

GGUF: C++ refactor, backend support, misc fixes (skip) (llama/11030)

Browse files
Files changed (2) hide show
  1. ggml/include/gguf.h +202 -0
  2. ggml/src/gguf.cpp +1325 -0
ggml/include/gguf.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file contains functionality related to "GGUF" files, the binary file format used by ggml.
2
+ // GGUF files have the following structure:
3
+ //
4
+ // 1. File magic "GGUF" (4 bytes).
5
+ // 2. File version (uint32_t).
6
+ // 3. Number of ggml tensors in file (int64_t).
7
+ // 4. Number of key-value-pairs in file (int64_t).
8
+ // 5. For each KV pair:
9
+ // 1. The key (string).
10
+ // 2. The value type (gguf_type).
11
+ // 3a. If the value type is GGUF_TYPE_ARRAY:
12
+ // 1. The type of the array (gguf_type).
13
+ // 2. The number of elements in the array (uint64_t).
14
+ // 3. The binary representation of each element in the array.
15
+ // 3b. Otherwise:
16
+ // 1. The binary representation of the value.
17
+ // 6. For each ggml tensor:
18
+ // 1. The tensor name (string).
19
+ // 2. The number of dimensions of the tensor (uint32_t).
20
+ // 3. For each dimension:
21
+ // 1. The size of the tensor in the dimension (int64_t).
22
+ // 4. The tensor data type (ggml_type).
23
+ // 5. The tensor data offset in the tensor data binary blob (uint64_t).
24
+ // 7. The tensor data binary blob (optional, aligned).
25
+ //
26
+ // Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator.
27
+ // All enums are stored as int32_t.
28
+ // All bool values are stored as int8_t.
29
+ // If the special key "general.alignment" (uint32_t) is defined it is used for alignment,
30
+ // otherwise GGUF_DEFAULT_ALIGNMENT is used.
31
+ //
32
+ // Module maintainer: Johannes Gäßler (@JohannesGaessler, [email protected])
33
+
34
+ #pragma once
35
+
36
+ #include "ggml.h"
37
+
38
+ #include <stdbool.h>
39
+ #include <stdint.h>
40
+
41
+ #define GGUF_MAGIC "GGUF"
42
+ #define GGUF_VERSION 3
43
+
44
+ #define GGUF_KEY_GENERAL_ALIGNMENT "general.alignment"
45
+
46
+ #define GGUF_DEFAULT_ALIGNMENT 32
47
+
48
+ #ifdef __cplusplus
49
+ extern "C" {
50
+ #endif
51
+
52
+ // types that can be stored as GGUF KV data
53
+ enum gguf_type {
54
+ GGUF_TYPE_UINT8 = 0,
55
+ GGUF_TYPE_INT8 = 1,
56
+ GGUF_TYPE_UINT16 = 2,
57
+ GGUF_TYPE_INT16 = 3,
58
+ GGUF_TYPE_UINT32 = 4,
59
+ GGUF_TYPE_INT32 = 5,
60
+ GGUF_TYPE_FLOAT32 = 6,
61
+ GGUF_TYPE_BOOL = 7,
62
+ GGUF_TYPE_STRING = 8,
63
+ GGUF_TYPE_ARRAY = 9,
64
+ GGUF_TYPE_UINT64 = 10,
65
+ GGUF_TYPE_INT64 = 11,
66
+ GGUF_TYPE_FLOAT64 = 12,
67
+ GGUF_TYPE_COUNT, // marks the end of the enum
68
+ };
69
+
70
+ struct gguf_context;
71
+
72
+ struct gguf_init_params {
73
+ bool no_alloc;
74
+
75
+ // if not NULL, create a ggml_context and allocate the tensor data in it
76
+ struct ggml_context ** ctx;
77
+ };
78
+
79
+ GGML_API struct gguf_context * gguf_init_empty(void);
80
+ GGML_API struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params);
81
+ //GGML_API struct gguf_context * gguf_init_from_buffer(..);
82
+
83
+ GGML_API void gguf_free(struct gguf_context * ctx);
84
+
85
+ GGML_API const char * gguf_type_name(enum gguf_type type);
86
+
87
+ GGML_API uint32_t gguf_get_version (const struct gguf_context * ctx);
88
+ GGML_API size_t gguf_get_alignment (const struct gguf_context * ctx);
89
+ GGML_API size_t gguf_get_data_offset(const struct gguf_context * ctx);
90
+
91
+ GGML_API int64_t gguf_get_n_kv(const struct gguf_context * ctx);
92
+ GGML_API int64_t gguf_find_key(const struct gguf_context * ctx, const char * key); // returns -1 if key is not found
93
+ GGML_API const char * gguf_get_key (const struct gguf_context * ctx, int64_t key_id);
94
+
95
+ GGML_API enum gguf_type gguf_get_kv_type (const struct gguf_context * ctx, int64_t key_id);
96
+ GGML_API enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id);
97
+
98
+ // will abort if the wrong type is used for the key
99
+ GGML_API uint8_t gguf_get_val_u8 (const struct gguf_context * ctx, int64_t key_id);
100
+ GGML_API int8_t gguf_get_val_i8 (const struct gguf_context * ctx, int64_t key_id);
101
+ GGML_API uint16_t gguf_get_val_u16 (const struct gguf_context * ctx, int64_t key_id);
102
+ GGML_API int16_t gguf_get_val_i16 (const struct gguf_context * ctx, int64_t key_id);
103
+ GGML_API uint32_t gguf_get_val_u32 (const struct gguf_context * ctx, int64_t key_id);
104
+ GGML_API int32_t gguf_get_val_i32 (const struct gguf_context * ctx, int64_t key_id);
105
+ GGML_API float gguf_get_val_f32 (const struct gguf_context * ctx, int64_t key_id);
106
+ GGML_API uint64_t gguf_get_val_u64 (const struct gguf_context * ctx, int64_t key_id);
107
+ GGML_API int64_t gguf_get_val_i64 (const struct gguf_context * ctx, int64_t key_id);
108
+ GGML_API double gguf_get_val_f64 (const struct gguf_context * ctx, int64_t key_id);
109
+ GGML_API bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id);
110
+ GGML_API const char * gguf_get_val_str (const struct gguf_context * ctx, int64_t key_id);
111
+ GGML_API const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id);
112
+ GGML_API size_t gguf_get_arr_n (const struct gguf_context * ctx, int64_t key_id);
113
+
114
+ // get raw pointer to the first element of the array with the given key_id
115
+ // for bool arrays, note that they are always stored as int8 on all platforms (usually this makes no difference)
116
+ GGML_API const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id);
117
+
118
+ // get ith C string from array with given key_id
119
+ GGML_API const char * gguf_get_arr_str (const struct gguf_context * ctx, int64_t key_id, size_t i);
120
+
121
+ GGML_API int64_t gguf_get_n_tensors (const struct gguf_context * ctx);
122
+ GGML_API int64_t gguf_find_tensor (const struct gguf_context * ctx, const char * name); // returns -1 if the tensor is not found
123
+ GGML_API size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id);
124
+ GGML_API const char * gguf_get_tensor_name (const struct gguf_context * ctx, int64_t tensor_id);
125
+ GGML_API enum ggml_type gguf_get_tensor_type (const struct gguf_context * ctx, int64_t tensor_id);
126
+ GGML_API size_t gguf_get_tensor_size (const struct gguf_context * ctx, int64_t tensor_id);
127
+
128
+ // removes key if it exists, returns id that the key had prior to removal (-1 if it didn't exist)
129
+ GGML_API int64_t gguf_remove_key(struct gguf_context * ctx, const char * key);
130
+
131
+ // overrides an existing KV pair or adds a new one, the new KV pair is always at the back
132
+ GGML_API void gguf_set_val_u8 (struct gguf_context * ctx, const char * key, uint8_t val);
133
+ GGML_API void gguf_set_val_i8 (struct gguf_context * ctx, const char * key, int8_t val);
134
+ GGML_API void gguf_set_val_u16 (struct gguf_context * ctx, const char * key, uint16_t val);
135
+ GGML_API void gguf_set_val_i16 (struct gguf_context * ctx, const char * key, int16_t val);
136
+ GGML_API void gguf_set_val_u32 (struct gguf_context * ctx, const char * key, uint32_t val);
137
+ GGML_API void gguf_set_val_i32 (struct gguf_context * ctx, const char * key, int32_t val);
138
+ GGML_API void gguf_set_val_f32 (struct gguf_context * ctx, const char * key, float val);
139
+ GGML_API void gguf_set_val_u64 (struct gguf_context * ctx, const char * key, uint64_t val);
140
+ GGML_API void gguf_set_val_i64 (struct gguf_context * ctx, const char * key, int64_t val);
141
+ GGML_API void gguf_set_val_f64 (struct gguf_context * ctx, const char * key, double val);
142
+ GGML_API void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val);
143
+ GGML_API void gguf_set_val_str (struct gguf_context * ctx, const char * key, const char * val);
144
+
145
+ // creates a new array with n elements of the given type and copies the corresponding number of bytes from data
146
+ GGML_API void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n);
147
+
148
+ // creates a new array with n strings and copies the corresponding strings from data
149
+ GGML_API void gguf_set_arr_str (struct gguf_context * ctx, const char * key, const char ** data, size_t n);
150
+
151
+ // set or add KV pairs from another context
152
+ GGML_API void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src);
153
+
154
+ // add tensor to GGUF context, tensor name must be unique
155
+ GGML_API void gguf_add_tensor(struct gguf_context * ctx, const struct ggml_tensor * tensor);
156
+
157
+ // after changing a tensor's type, the offsets of all tensors with higher indices are immediately recalculated
158
+ // in such a way that the tensor data remains as one contiguous block (except for padding)
159
+ GGML_API void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type);
160
+
161
+ // assumes that at least gguf_get_tensor_size bytes can be read from data
162
+ GGML_API void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data);
163
+
164
+ // writing gguf files can be done in 3 ways:
165
+ //
166
+ // - write the entire gguf_context to a binary file in a single pass:
167
+ //
168
+ // gguf_write_to_file(ctx, fname, /*only_meta =*/ false);
169
+ //
170
+ // - write only the meta data to a file, then re-open the file and append the tensor data:
171
+ //
172
+ // gguf_write_to_file(ctx, fname, /*only_meta =*/ true);
173
+ // FILE * f = fopen(fname, "ab");
174
+ // fwrite(f, ...); // write tensor data
175
+ // fclose(f);
176
+ //
177
+ // - first prepare a file with a placeholder for the meta data, write the tensor data, then write the meta data:
178
+ //
179
+ // FILE * f = fopen(fname, "wb");
180
+ // const size_t size_meta = gguf_get_meta_size(ctx);
181
+ // fseek(f, size_meta, SEEK_SET);
182
+ // fwrite(f, ...); // write tensor data
183
+ // void * data = malloc(size_meta);
184
+ // gguf_get_meta_data(ctx, data);
185
+ // rewind(f);
186
+ // fwrite(data, 1, data, f);
187
+ // free(data);
188
+ // fclose(f);
189
+ //
190
+
191
+ // write the entire context to a binary file
192
+ GGML_API bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta);
193
+
194
+ // get the size in bytes of the meta data (header, kv pairs, tensor info) including padding
195
+ GGML_API size_t gguf_get_meta_size(const struct gguf_context * ctx);
196
+
197
+ // writes the meta data to pointer "data"
198
+ GGML_API void gguf_get_meta_data(const struct gguf_context * ctx, void * data);
199
+
200
+ #ifdef __cplusplus
201
+ }
202
+ #endif
ggml/src/gguf.cpp ADDED
@@ -0,0 +1,1325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 <map>
13
+ #include <new>
14
+ #include <stdexcept>
15
+ #include <string>
16
+ #include <vector>
17
+
18
+ template <typename T>
19
+ struct type_to_gguf_type;
20
+
21
+ template <>
22
+ struct type_to_gguf_type<uint8_t> {
23
+ static constexpr enum gguf_type value = GGUF_TYPE_UINT8;
24
+ };
25
+
26
+ template <>
27
+ struct type_to_gguf_type<int8_t> {
28
+ static constexpr enum gguf_type value = GGUF_TYPE_INT8;
29
+ };
30
+
31
+ template <>
32
+ struct type_to_gguf_type<uint16_t> {
33
+ static constexpr enum gguf_type value = GGUF_TYPE_UINT16;
34
+ };
35
+
36
+ template <>
37
+ struct type_to_gguf_type<int16_t> {
38
+ static constexpr enum gguf_type value = GGUF_TYPE_INT16;
39
+ };
40
+
41
+ template <>
42
+ struct type_to_gguf_type<uint32_t> {
43
+ static constexpr enum gguf_type value = GGUF_TYPE_UINT32;
44
+ };
45
+
46
+ template <>
47
+ struct type_to_gguf_type<int32_t> {
48
+ static constexpr enum gguf_type value = GGUF_TYPE_INT32;
49
+ };
50
+
51
+ template <>
52
+ struct type_to_gguf_type<float> {
53
+ static constexpr enum gguf_type value = GGUF_TYPE_FLOAT32;
54
+ };
55
+
56
+ template <>
57
+ struct type_to_gguf_type<bool> {
58
+ static constexpr enum gguf_type value = GGUF_TYPE_BOOL;
59
+ };
60
+
61
+ template <>
62
+ struct type_to_gguf_type<std::string> {
63
+ static constexpr enum gguf_type value = GGUF_TYPE_STRING;
64
+ };
65
+
66
+ template <>
67
+ struct type_to_gguf_type<uint64_t> {
68
+ static constexpr enum gguf_type value = GGUF_TYPE_UINT64;
69
+ };
70
+
71
+ template <>
72
+ struct type_to_gguf_type<int64_t> {
73
+ static constexpr enum gguf_type value = GGUF_TYPE_INT64;
74
+ };
75
+
76
+ template <>
77
+ struct type_to_gguf_type<double> {
78
+ static constexpr enum gguf_type value = GGUF_TYPE_FLOAT64;
79
+ };
80
+
81
+ static const std::map<gguf_type, size_t> GGUF_TYPE_SIZE = {
82
+ {GGUF_TYPE_UINT8, sizeof(uint8_t)},
83
+ {GGUF_TYPE_INT8, sizeof(int8_t)},
84
+ {GGUF_TYPE_UINT16, sizeof(uint16_t)},
85
+ {GGUF_TYPE_INT16, sizeof(int16_t)},
86
+ {GGUF_TYPE_UINT32, sizeof(uint32_t)},
87
+ {GGUF_TYPE_INT32, sizeof(int32_t)},
88
+ {GGUF_TYPE_FLOAT32, sizeof(float)},
89
+ {GGUF_TYPE_BOOL, sizeof(int8_t)},
90
+ {GGUF_TYPE_STRING, 0}, // undefined
91
+ {GGUF_TYPE_ARRAY, 0}, // undefined
92
+ {GGUF_TYPE_UINT64, sizeof(uint64_t)},
93
+ {GGUF_TYPE_INT64, sizeof(int64_t)},
94
+ {GGUF_TYPE_FLOAT64, sizeof(double)},
95
+ };
96
+ static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
97
+
98
+ static const std::map<gguf_type, const char *> GGUF_TYPE_NAME = {
99
+ {GGUF_TYPE_UINT8, "u8"},
100
+ {GGUF_TYPE_INT8, "i8"},
101
+ {GGUF_TYPE_UINT16, "u16"},
102
+ {GGUF_TYPE_INT16, "i16"},
103
+ {GGUF_TYPE_UINT32, "u32"},
104
+ {GGUF_TYPE_INT32, "i32"},
105
+ {GGUF_TYPE_FLOAT32, "f32"},
106
+ {GGUF_TYPE_BOOL, "bool"},
107
+ {GGUF_TYPE_STRING, "str"},
108
+ {GGUF_TYPE_ARRAY, "arr"},
109
+ {GGUF_TYPE_UINT64, "u64"},
110
+ {GGUF_TYPE_INT64, "i64"},
111
+ {GGUF_TYPE_FLOAT64, "f64"},
112
+ };
113
+ static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
114
+
115
+ size_t gguf_type_size(enum gguf_type type) {
116
+ auto it = GGUF_TYPE_SIZE.find(type);
117
+ return it == GGUF_TYPE_SIZE.end() ? 0 : it->second;
118
+ }
119
+
120
+ struct gguf_kv {
121
+ std::string key;
122
+
123
+ bool is_array;
124
+ enum gguf_type type;
125
+
126
+ std::vector<int8_t> data;
127
+ std::vector<std::string> data_string;
128
+
129
+ template <typename T>
130
+ gguf_kv(const std::string & key, const T value)
131
+ : key(key), is_array(false), type(type_to_gguf_type<T>::value) {
132
+ GGML_ASSERT(!key.empty());
133
+ data.resize(sizeof(T));
134
+ memcpy(data.data(), &value, sizeof(T));
135
+ }
136
+
137
+ template <typename T>
138
+ gguf_kv(const std::string & key, const std::vector<T> & value)
139
+ : key(key), is_array(true), type(type_to_gguf_type<T>::value) {
140
+ GGML_ASSERT(!key.empty());
141
+ data.resize(value.size()*sizeof(T));
142
+ for (size_t i = 0; i < value.size(); ++i) {
143
+ const T tmp = value[i];
144
+ memcpy(data.data() + i*sizeof(T), &tmp, sizeof(T));
145
+ }
146
+ }
147
+
148
+ gguf_kv(const std::string & key, const std::string & value)
149
+ : key(key), is_array(false), type(GGUF_TYPE_STRING) {
150
+ GGML_ASSERT(!key.empty());
151
+ data_string.push_back(value);
152
+ }
153
+
154
+ gguf_kv(const std::string & key, const std::vector<std::string> & value)
155
+ : key(key), is_array(true), type(GGUF_TYPE_STRING) {
156
+ GGML_ASSERT(!key.empty());
157
+ data_string = value;
158
+ }
159
+
160
+ const std::string & get_key() const {
161
+ return key;
162
+ }
163
+
164
+ const enum gguf_type & get_type() const {
165
+ return type;
166
+ }
167
+
168
+ size_t get_ne() const {
169
+ if (type == GGUF_TYPE_STRING) {
170
+ const size_t ne = data_string.size();
171
+ GGML_ASSERT(is_array || ne == 1);
172
+ return ne;
173
+ }
174
+ const size_t type_size = gguf_type_size(type);
175
+ GGML_ASSERT(data.size() % type_size == 0);
176
+ const size_t ne = data.size() / type_size;
177
+ GGML_ASSERT(is_array || ne == 1);
178
+ return ne;
179
+ }
180
+
181
+ template <typename T>
182
+ const T & get_val(const size_t i = 0) const {
183
+ GGML_ASSERT(type_to_gguf_type<T>::value == type);
184
+ if constexpr (std::is_same<T, std::string>::value) {
185
+ GGML_ASSERT(data_string.size() >= i+1);
186
+ return data_string[i];
187
+ }
188
+ const size_t type_size = gguf_type_size(type);
189
+ GGML_ASSERT(data.size() % type_size == 0);
190
+ GGML_ASSERT(data.size() >= (i+1)*type_size);
191
+ return reinterpret_cast<const T *>(data.data())[i];
192
+ }
193
+
194
+ void cast(const enum gguf_type new_type) {
195
+ const size_t new_type_size = gguf_type_size(new_type);
196
+ GGML_ASSERT(data.size() % new_type_size == 0);
197
+ type = new_type;
198
+ }
199
+ };
200
+
201
+ struct gguf_tensor_info {
202
+ struct ggml_tensor t; // for holding the equivalent info
203
+ uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
204
+ };
205
+
206
+ struct gguf_context {
207
+ uint32_t version = GGUF_VERSION;
208
+
209
+ std::vector<struct gguf_kv> kv;
210
+ std::vector<struct gguf_tensor_info> info;
211
+
212
+ size_t alignment = GGUF_DEFAULT_ALIGNMENT;
213
+ size_t offset = 0; // offset of `data` from beginning of file
214
+ size_t size = 0; // size of `data` in bytes
215
+
216
+ void * data = nullptr;
217
+ };
218
+
219
+ struct gguf_reader {
220
+ FILE * file;
221
+
222
+ gguf_reader(FILE * file) : file(file) {}
223
+
224
+ template <typename T>
225
+ bool read(T & dst) const {
226
+ return fread(&dst, 1, sizeof(dst), file) == sizeof(dst);
227
+ }
228
+
229
+ template <typename T>
230
+ bool read(std::vector<T> & dst, const size_t n) const {
231
+ dst.resize(n);
232
+ for (size_t i = 0; i < dst.size(); ++i) {
233
+ if constexpr (std::is_same<T, bool>::value) {
234
+ bool tmp;
235
+ if (!read(tmp)) {
236
+ return false;
237
+ }
238
+ dst[i] = tmp;
239
+ } else {
240
+ if (!read(dst[i])) {
241
+ return false;
242
+ }
243
+ }
244
+ }
245
+ return true;
246
+ }
247
+
248
+ bool read(bool & dst) const {
249
+ int8_t tmp = -1;
250
+ if (!read(tmp)) {
251
+ return false;
252
+ }
253
+ dst = tmp != 0;
254
+ return true;
255
+ }
256
+
257
+ bool read(enum ggml_type & dst) const {
258
+ int32_t tmp = -1;
259
+ if (!read(tmp)) {
260
+ return false;
261
+ }
262
+ dst = ggml_type(tmp);
263
+ return true;
264
+ }
265
+
266
+ bool read(enum gguf_type & dst) const {
267
+ int32_t tmp = -1;
268
+ if (!read(tmp)) {
269
+ return false;
270
+ }
271
+ dst = gguf_type(tmp);
272
+ return true;
273
+ }
274
+
275
+ bool read(std::string & dst) const {
276
+ uint64_t size = -1;
277
+ if (!read(size)) {
278
+ return false;
279
+ }
280
+ dst.resize(size);
281
+ return fread(dst.data(), 1, dst.length(), file) == dst.length();
282
+ }
283
+
284
+ bool read(void * dst, const size_t size) const {
285
+ return fread(dst, 1, size, file) == size;
286
+ }
287
+ };
288
+
289
+ struct gguf_context * gguf_init_empty(void) {
290
+ return new gguf_context;
291
+ }
292
+
293
+ template<typename T>
294
+ 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) {
295
+ if (is_array) {
296
+ std::vector<T> value;
297
+ try {
298
+ if (!gr.read(value, n)) {
299
+ return false;
300
+ }
301
+ } catch (std::length_error &) {
302
+ fprintf(stderr, "%s: encountered length_error while reading value for key '%s'\n", __func__, key.c_str());
303
+ return false;
304
+ } catch (std::bad_alloc &) {
305
+ fprintf(stderr, "%s: encountered bad_alloc error while reading value for key '%s'\n", __func__, key.c_str());
306
+ return false;
307
+ }
308
+ kv.emplace_back(key, value);
309
+ } else {
310
+ T value;
311
+ if (!gr.read(value)) {
312
+ return false;
313
+ }
314
+ kv.emplace_back(key, value);
315
+ }
316
+ return true;
317
+ }
318
+
319
+ struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params) {
320
+ const struct gguf_reader gr(file);
321
+ struct gguf_context * ctx = new gguf_context;
322
+
323
+ bool ok = true;
324
+
325
+ // file magic
326
+ {
327
+ std::vector<char> magic;
328
+ ok = ok && gr.read(magic, 4);
329
+
330
+ if (!ok) {
331
+ fprintf(stderr, "%s: failed to read magic\n", __func__);
332
+ gguf_free(ctx);
333
+ return nullptr;
334
+ }
335
+
336
+ for (uint32_t i = 0; i < magic.size(); i++) {
337
+ if (magic[i] != GGUF_MAGIC[i]) {
338
+ fprintf(stderr, "%s: invalid magic characters: '%c%c%c%c', expected 'GGUF'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
339
+ gguf_free(ctx);
340
+ return nullptr;
341
+ }
342
+ }
343
+ }
344
+
345
+ // header
346
+ int64_t n_kv = 0;
347
+ int64_t n_tensors = 0;
348
+
349
+ if (ok && gr.read(ctx->version)) {
350
+ if (ctx->version == 1) {
351
+ fprintf(stderr, "%s: GGUFv1 is no longer supported, please use a more up-to-date version\n", __func__);
352
+ ok = false;
353
+ }
354
+ if (ctx->version > GGUF_VERSION) {
355
+ fprintf(stderr, "%s: this GGUF file is version %" PRIu32 " but this software only supports up to version %d\n",
356
+ __func__, ctx->version, GGUF_VERSION);
357
+ ok = false;
358
+ }
359
+ } else {
360
+ ok = false;
361
+ }
362
+
363
+ if (ok && gr.read(n_tensors)) {
364
+ static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
365
+ if (n_tensors < 0 || n_tensors > int64_t(SIZE_MAX/sizeof(gguf_tensor_info))) {
366
+ fprintf(stderr, "%s: number of tensors is %" PRIi64 " but must be in [0, %zu]\n",
367
+ __func__, n_tensors, SIZE_MAX/sizeof(gguf_tensor_info));
368
+ ok = false;
369
+ }
370
+ } else {
371
+ ok = false;
372
+ }
373
+
374
+ if (ok && gr.read(n_kv)) {
375
+ static_assert(sizeof(size_t) <= 8 && sizeof(gguf_tensor_info) >= 2, "int64_t insufficient for indexing");
376
+ if (n_kv < 0 || n_kv > int64_t(SIZE_MAX/sizeof(gguf_kv))) {
377
+ fprintf(stderr, "%s: number of key value pairs is %" PRIi64 " but must be in [0, %zu]\n",
378
+ __func__, n_kv, SIZE_MAX/sizeof(gguf_kv));
379
+ ok = false;
380
+ }
381
+ } else {
382
+ ok = false;
383
+ }
384
+
385
+ if (!ok) {
386
+ fprintf(stderr, "%s: failed to read header\n", __func__);
387
+ gguf_free(ctx);
388
+ return nullptr;
389
+ }
390
+
391
+ // KV pairs
392
+ {
393
+ for (int64_t i = 0; ok && i < n_kv; ++i) {
394
+ std::string key;
395
+ gguf_type type = gguf_type(-1);
396
+ bool is_array = false;
397
+ uint64_t n = 1;
398
+
399
+ try {
400
+ ok = ok && gr.read(key);
401
+ } catch (std::length_error &) {
402
+ fprintf(stderr, "%s: encountered length_error while reading key %" PRIi64 "\n", __func__, i);
403
+ ok = false;
404
+ } catch (std::bad_alloc &) {
405
+ fprintf(stderr, "%s: encountered bad_alloc error while reading key %" PRIi64 "\n", __func__, i);
406
+ ok = false;
407
+ }
408
+ for (size_t j = 0; ok && j < ctx->kv.size(); ++j) {
409
+ if (key == ctx->kv[j].key) {
410
+ fprintf(stderr, "%s: duplicate key '%s' for tensors %zu and %" PRIi64 " \n", __func__, key.c_str(), j, i);
411
+ ok = false;
412
+ }
413
+ }
414
+ if (!ok) {
415
+ break;
416
+ }
417
+
418
+ ok = ok && gr.read(type);
419
+ if (type == GGUF_TYPE_ARRAY) {
420
+ is_array = true;
421
+ ok = ok && gr.read(type);
422
+ ok = ok && gr.read(n);
423
+ }
424
+ if (!ok) {
425
+ break;
426
+ }
427
+
428
+ switch (type) {
429
+ case GGUF_TYPE_UINT8: ok = ok && gguf_read_emplace_helper<uint8_t> (gr, ctx->kv, key, is_array, n); break;
430
+ case GGUF_TYPE_INT8: ok = ok && gguf_read_emplace_helper<int8_t> (gr, ctx->kv, key, is_array, n); break;
431
+ case GGUF_TYPE_UINT16: ok = ok && gguf_read_emplace_helper<uint16_t> (gr, ctx->kv, key, is_array, n); break;
432
+ case GGUF_TYPE_INT16: ok = ok && gguf_read_emplace_helper<int16_t> (gr, ctx->kv, key, is_array, n); break;
433
+ case GGUF_TYPE_UINT32: ok = ok && gguf_read_emplace_helper<uint32_t> (gr, ctx->kv, key, is_array, n); break;
434
+ case GGUF_TYPE_INT32: ok = ok && gguf_read_emplace_helper<int32_t> (gr, ctx->kv, key, is_array, n); break;
435
+ case GGUF_TYPE_FLOAT32: ok = ok && gguf_read_emplace_helper<float> (gr, ctx->kv, key, is_array, n); break;
436
+ case GGUF_TYPE_BOOL: ok = ok && gguf_read_emplace_helper<bool> (gr, ctx->kv, key, is_array, n); break;
437
+ case GGUF_TYPE_STRING: ok = ok && gguf_read_emplace_helper<std::string>(gr, ctx->kv, key, is_array, n); break;
438
+ case GGUF_TYPE_UINT64: ok = ok && gguf_read_emplace_helper<uint64_t> (gr, ctx->kv, key, is_array, n); break;
439
+ case GGUF_TYPE_INT64: ok = ok && gguf_read_emplace_helper<int64_t> (gr, ctx->kv, key, is_array, n); break;
440
+ case GGUF_TYPE_FLOAT64: ok = ok && gguf_read_emplace_helper<double> (gr, ctx->kv, key, is_array, n); break;
441
+ case GGUF_TYPE_ARRAY:
442
+ default:
443
+ {
444
+ fprintf(stderr, "%s: key '%s' has invalid GGUF type %d\n", __func__, key.c_str(), type);
445
+ ok = false;
446
+ } break;
447
+ }
448
+ }
449
+
450
+ if (!ok) {
451
+ fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
452
+ gguf_free(ctx);
453
+ return nullptr;
454
+ }
455
+ GGML_ASSERT(int64_t(ctx->kv.size()) == n_kv);
456
+
457
+ const int alignment_idx = gguf_find_key(ctx, GGUF_KEY_GENERAL_ALIGNMENT);
458
+ ctx->alignment = alignment_idx == -1 ? GGUF_DEFAULT_ALIGNMENT : gguf_get_val_u32(ctx, alignment_idx);
459
+
460
+ if (ctx->alignment == 0 || (ctx->alignment & (ctx->alignment - 1)) != 0) {
461
+ fprintf(stderr, "%s: alignment %zu is not a power of 2\n", __func__, ctx->alignment);
462
+ gguf_free(ctx);
463
+ return nullptr;
464
+ }
465
+ }
466
+
467
+ // read the tensor info
468
+ for (int64_t i = 0; ok && i < n_tensors; ++i) {
469
+ struct gguf_tensor_info info;
470
+
471
+ // tensor name
472
+ {
473
+ std::string name;
474
+ try {
475
+ ok = ok && gr.read(name);
476
+ } catch (std::length_error &) {
477
+ fprintf(stderr, "%s: encountered length_error while reading tensor name %" PRIi64 "\n", __func__, i);
478
+ ok = false;
479
+ } catch (std::bad_alloc &) {
480
+ fprintf(stderr, "%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
481
+ ok = false;
482
+ }
483
+ if (name.length() >= GGML_MAX_NAME) {
484
+ fprintf(stderr, "%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
485
+ ok = false;
486
+ break;
487
+ }
488
+ ggml_set_name(&info.t, name.c_str());
489
+
490
+ // make sure there are no duplicate tensor names
491
+ for (int64_t j = 0; ok && j < i; ++j) {
492
+ if (strcmp(info.t.name, ctx->info[j].t.name) == 0) {
493
+ fprintf(stderr, "%s: duplicate tensor name '%s' for tensors %" PRIi64 " and %" PRIi64 "\n", __func__, info.t.name, j, i);
494
+ ok = false;
495
+ break;
496
+ }
497
+ }
498
+ }
499
+ if (!ok) {
500
+ break;
501
+ }
502
+
503
+ // tensor shape
504
+ {
505
+ uint32_t n_dims = -1;
506
+ ok = ok && gr.read(n_dims);
507
+ if (n_dims > GGML_MAX_DIMS) {
508
+ fprintf(stderr, "%s: tensor '%s' has invalid number of dimensions: %" PRIu32 " > %" PRIu32 "\n",
509
+ __func__, info.t.name, n_dims, GGML_MAX_DIMS);
510
+ ok = false;
511
+ break;
512
+ }
513
+ for (uint32_t j = 0; ok && j < GGML_MAX_DIMS; ++j) {
514
+ info.t.ne[j] = 1;
515
+ if (j < n_dims) {
516
+ ok = ok && gr.read(info.t.ne[j]);
517
+ }
518
+
519
+ // check that all ne are non-negative
520
+ if (info.t.ne[j] < 0) {
521
+ fprintf(stderr, "%s: tensor '%s' dimension %" PRIu32 " has invalid number of elements: %" PRIi64 " < 0\n",
522
+ __func__, info.t.name, j, info.t.ne[j]);
523
+ ok = false;
524
+ break;
525
+ }
526
+ }
527
+
528
+ // check that the total number of elements is representable
529
+ if (ok && ((INT64_MAX/info.t.ne[1] <= info.t.ne[0]) ||
530
+ (INT64_MAX/info.t.ne[2] <= info.t.ne[0]*info.t.ne[1]) ||
531
+ (INT64_MAX/info.t.ne[3] <= info.t.ne[0]*info.t.ne[1]*info.t.ne[2]))) {
532
+
533
+ fprintf(stderr, "%s: total number of elements in tensor '%s' with shape "
534
+ "(%" PRIi64 ", %" PRIi64 ", %" PRIi64 ", %" PRIi64 ") is >= %" PRIi64 "\n",
535
+ __func__, info.t.name, info.t.ne[0], info.t.ne[1], info.t.ne[2], info.t.ne[3], INT64_MAX);
536
+ ok = false;
537
+ break;
538
+ }
539
+ }
540
+ if (!ok) {
541
+ break;
542
+ }
543
+
544
+ // tensor type
545
+ {
546
+ ok = ok && gr.read(info.t.type);
547
+
548
+ // check that tensor type is within defined range
549
+ if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) {
550
+ fprintf(stderr, "%s: tensor '%s' has invalid ggml type %d (%s)\n",
551
+ __func__, info.t.name, info.t.type, ggml_type_name(info.t.type));
552
+ ok = false;
553
+ break;
554
+ }
555
+ const size_t type_size = ggml_type_size(info.t.type);
556
+ const int64_t blck_size = ggml_blck_size(info.t.type);
557
+
558
+ // check that row size is divisible by block size
559
+ if (blck_size == 0 || info.t.ne[0] % blck_size != 0) {
560
+ fprintf(stderr, "%s: tensor '%s' of type %d (%s) has %" PRId64 " elements per row, "
561
+ "not a multiple of block size (%" PRId64 ")\n",
562
+ __func__, info.t.name, (int) info.t.type, ggml_type_name(info.t.type), info.t.ne[0], blck_size);
563
+ ok = false;
564
+ break;
565
+ }
566
+
567
+ // calculate byte offsets given the tensor shape and type
568
+ info.t.nb[0] = type_size;
569
+ info.t.nb[1] = info.t.nb[0]*(info.t.ne[0]/blck_size);
570
+ for (int j = 2; j < GGML_MAX_DIMS; ++j) {
571
+ info.t.nb[j] = info.t.nb[j - 1]*info.t.ne[j - 1];
572
+ }
573
+ }
574
+ if (!ok) {
575
+ break;
576
+ }
577
+
578
+ // tensor data offset within buffer
579
+ ok = ok && gr.read(info.offset);
580
+
581
+ ctx->info.push_back(info);
582
+ }
583
+
584
+ if (!ok) {
585
+ fprintf(stderr, "%s: failed to read tensor info\n", __func__);
586
+ gguf_free(ctx);
587
+ return nullptr;
588
+ }
589
+ GGML_ASSERT(int64_t(ctx->info.size()) == n_tensors);
590
+
591
+ // we require the data section to be aligned, so take into account any padding
592
+ if (fseek(file, GGML_PAD(ftell(file), ctx->alignment), SEEK_SET) != 0) {
593
+ fprintf(stderr, "%s: failed to seek to beginning of data section\n", __func__);
594
+ gguf_free(ctx);
595
+ return nullptr;
596
+ }
597
+
598
+ // store the current file offset - this is where the data section starts
599
+ ctx->offset = ftell(file);
600
+
601
+ // compute the total size of the data section, taking into account the alignment
602
+ {
603
+ ctx->size = 0;
604
+ for (size_t i = 0; i < ctx->info.size(); ++i) {
605
+ const gguf_tensor_info & ti = ctx->info[i];
606
+ if (ti.offset != ctx->size) {
607
+ fprintf(stderr, "%s: tensor '%s' has offset %" PRIu64 ", expected %zu\n",
608
+ __func__, ti.t.name, ti.offset, ctx->size);
609
+ fprintf(stderr, "%s: failed to read tensor data\n", __func__);
610
+ gguf_free(ctx);
611
+ return nullptr;
612
+ }
613
+ ctx->size += GGML_PAD(ggml_nbytes(&ti.t), ctx->alignment);
614
+ }
615
+ }
616
+
617
+ // load the tensor data only if requested
618
+ if (params.ctx != nullptr) {
619
+ // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
620
+ // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
621
+ // the ggml_tensor structs to the appropriate locations in the binary blob
622
+
623
+ // compute the exact size needed for the new ggml_context
624
+ const size_t mem_size =
625
+ params.no_alloc ?
626
+ (n_tensors )*ggml_tensor_overhead() :
627
+ (n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
628
+
629
+ struct ggml_init_params pdata = {
630
+ /*mem_size =*/ mem_size,
631
+ /*mem_buffer =*/ nullptr,
632
+ /*no_alloc =*/ params.no_alloc,
633
+ };
634
+
635
+ *params.ctx = ggml_init(pdata);
636
+ if (*params.ctx == nullptr) {
637
+ fprintf(stderr, "%s: failed to initialize ggml context for storing tensors\n", __func__);
638
+ gguf_free(ctx);
639
+ return nullptr;
640
+ }
641
+
642
+ struct ggml_context * ctx_data = *params.ctx;
643
+
644
+ struct ggml_tensor * data = nullptr;
645
+
646
+ if (!params.no_alloc) {
647
+ data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
648
+
649
+ ok = ok && data != nullptr;
650
+
651
+ // read the binary blob with the tensor data
652
+ ok = ok && gr.read(data->data, ctx->size);
653
+
654
+ if (!ok) {
655
+ fprintf(stderr, "%s: failed to read tensor data binary blob\n", __func__);
656
+ ggml_free(ctx_data);
657
+ *params.ctx = nullptr;
658
+ gguf_free(ctx);
659
+ return nullptr;
660
+ }
661
+
662
+ ctx->data = data->data;
663
+ }
664
+
665
+ ggml_set_no_alloc(ctx_data, true);
666
+
667
+ // create the tensors
668
+ for (size_t i = 0; i < ctx->info.size(); ++i) {
669
+ const struct gguf_tensor_info & info = ctx->info[i];
670
+
671
+ struct ggml_tensor * cur = ggml_new_tensor(ctx_data, info.t.type, GGML_MAX_DIMS, info.t.ne);
672
+
673
+ ok = ok && cur != nullptr;
674
+
675
+ if (!ok) {
676
+ break;
677
+ }
678
+
679
+ ggml_set_name(cur, info.t.name);
680
+
681
+ // point the data member to the appropriate location in the binary blob using the tensor info
682
+ if (!params.no_alloc) {
683
+ cur->data = (char *) data->data + info.offset;
684
+ }
685
+ }
686
+
687
+ if (!ok) {
688
+ fprintf(stderr, "%s: failed to create tensors\n", __func__);
689
+ ggml_free(ctx_data);
690
+ *params.ctx = nullptr;
691
+ gguf_free(ctx);
692
+ return nullptr;
693
+ }
694
+
695
+ ggml_set_no_alloc(ctx_data, params.no_alloc);
696
+ }
697
+
698
+ return ctx;
699
+ }
700
+
701
+ struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
702
+ FILE * file = ggml_fopen(fname, "rb");
703
+
704
+ if (!file) {
705
+ fprintf(stderr, "%s: failed to open GGUF file '%s'\n", __func__, fname);
706
+ return nullptr;
707
+ }
708
+
709
+ struct gguf_context * result = gguf_init_from_file_impl(file, params);
710
+ fclose(file);
711
+ return result;
712
+ }
713
+
714
+ void gguf_free(struct gguf_context * ctx) {
715
+ if (ctx == nullptr) {
716
+ return;
717
+ }
718
+ delete ctx;
719
+ }
720
+
721
+ const char * gguf_type_name(enum gguf_type type) {
722
+ auto it = GGUF_TYPE_NAME.find(type);
723
+ return it == GGUF_TYPE_NAME.end() ? nullptr : it->second;
724
+ }
725
+
726
+ uint32_t gguf_get_version(const struct gguf_context * ctx) {
727
+ return ctx->version;
728
+ }
729
+
730
+ size_t gguf_get_alignment(const struct gguf_context * ctx) {
731
+ return ctx->alignment;
732
+ }
733
+
734
+ size_t gguf_get_data_offset(const struct gguf_context * ctx) {
735
+ return ctx->offset;
736
+ }
737
+
738
+ int64_t gguf_get_n_kv(const struct gguf_context * ctx) {
739
+ return ctx->kv.size();
740
+ }
741
+
742
+ int64_t gguf_find_key(const struct gguf_context * ctx, const char * key) {
743
+ // return -1 if key not found
744
+ int64_t keyfound = -1;
745
+
746
+ const int64_t n_kv = gguf_get_n_kv(ctx);
747
+
748
+ for (int64_t i = 0; i < n_kv; ++i) {
749
+ if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
750
+ keyfound = i;
751
+ break;
752
+ }
753
+ }
754
+
755
+ return keyfound;
756
+ }
757
+
758
+ const char * gguf_get_key(const struct gguf_context * ctx, int64_t key_id) {
759
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
760
+ return ctx->kv[key_id].get_key().c_str();
761
+ }
762
+
763
+ enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int64_t key_id) {
764
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
765
+ return ctx->kv[key_id].is_array ? GGUF_TYPE_ARRAY : ctx->kv[key_id].get_type();
766
+ }
767
+
768
+ enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id) {
769
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
770
+ GGML_ASSERT(ctx->kv[key_id].is_array);
771
+ return ctx->kv[key_id].get_type();
772
+ }
773
+
774
+ const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id) {
775
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
776
+ GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
777
+ return ctx->kv[key_id].data.data();
778
+ }
779
+
780
+ const char * gguf_get_arr_str(const struct gguf_context * ctx, int64_t key_id, size_t i) {
781
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
782
+ GGML_ASSERT(ctx->kv[key_id].get_type() == GGUF_TYPE_STRING);
783
+ return ctx->kv[key_id].data_string[i].c_str();
784
+ }
785
+
786
+ size_t gguf_get_arr_n(const struct gguf_context * ctx, int64_t key_id) {
787
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
788
+
789
+ if (ctx->kv[key_id].type == GGUF_TYPE_STRING) {
790
+ return ctx->kv[key_id].data_string.size();
791
+ }
792
+
793
+ const size_t type_size = gguf_type_size(ctx->kv[key_id].type);
794
+ GGML_ASSERT(ctx->kv[key_id].data.size() % type_size == 0);
795
+ return ctx->kv[key_id].data.size() / type_size;
796
+ }
797
+
798
+ uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int64_t key_id) {
799
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
800
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
801
+ return ctx->kv[key_id].get_val<uint8_t>();
802
+ }
803
+
804
+ int8_t gguf_get_val_i8(const struct gguf_context * ctx, int64_t key_id) {
805
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
806
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
807
+ return ctx->kv[key_id].get_val<int8_t>();
808
+ }
809
+
810
+ uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int64_t key_id) {
811
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
812
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
813
+ return ctx->kv[key_id].get_val<uint16_t>();
814
+ }
815
+
816
+ int16_t gguf_get_val_i16(const struct gguf_context * ctx, int64_t key_id) {
817
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
818
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
819
+ return ctx->kv[key_id].get_val<int16_t>();
820
+ }
821
+
822
+ uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int64_t key_id) {
823
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
824
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
825
+ return ctx->kv[key_id].get_val<uint32_t>();
826
+ }
827
+
828
+ int32_t gguf_get_val_i32(const struct gguf_context * ctx, int64_t key_id) {
829
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
830
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
831
+ return ctx->kv[key_id].get_val<int32_t>();
832
+ }
833
+
834
+ float gguf_get_val_f32(const struct gguf_context * ctx, int64_t key_id) {
835
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
836
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
837
+ return ctx->kv[key_id].get_val<float>();
838
+ }
839
+
840
+ uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int64_t key_id) {
841
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
842
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
843
+ return ctx->kv[key_id].get_val<uint64_t>();
844
+ }
845
+
846
+ int64_t gguf_get_val_i64(const struct gguf_context * ctx, int64_t key_id) {
847
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
848
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
849
+ return ctx->kv[key_id].get_val<int64_t>();
850
+ }
851
+
852
+ double gguf_get_val_f64(const struct gguf_context * ctx, int64_t key_id) {
853
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
854
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
855
+ return ctx->kv[key_id].get_val<double>();
856
+ }
857
+
858
+ bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id) {
859
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
860
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
861
+ return ctx->kv[key_id].get_val<bool>();
862
+ }
863
+
864
+ const char * gguf_get_val_str(const struct gguf_context * ctx, int64_t key_id) {
865
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
866
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
867
+ return ctx->kv[key_id].get_val<std::string>().c_str();
868
+ }
869
+
870
+ const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id) {
871
+ GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
872
+ GGML_ASSERT(ctx->kv[key_id].get_ne() == 1);
873
+ GGML_ASSERT(ctx->kv[key_id].get_type() != GGUF_TYPE_STRING);
874
+ return ctx->kv[key_id].data.data();
875
+ }
876
+
877
+ int64_t gguf_get_n_tensors(const struct gguf_context * ctx) {
878
+ return ctx->info.size();
879
+ }
880
+
881
+ int64_t gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
882
+ // return -1 if tensor not found
883
+ int64_t tensor_id = -1;
884
+
885
+ const int64_t n_tensors = gguf_get_n_tensors(ctx);
886
+
887
+ for (int64_t i = 0; i < n_tensors; ++i) {
888
+ if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
889
+ tensor_id = i;
890
+ break;
891
+ }
892
+ }
893
+
894
+ return tensor_id;
895
+ }
896
+
897
+ size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id) {
898
+ GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
899
+ return ctx->info[tensor_id].offset;
900
+ }
901
+
902
+ const char * gguf_get_tensor_name(const struct gguf_context * ctx, int64_t tensor_id) {
903
+ GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
904
+ return ctx->info[tensor_id].t.name;
905
+ }
906
+
907
+ enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int64_t tensor_id) {
908
+ GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
909
+ return ctx->info[tensor_id].t.type;
910
+ }
911
+
912
+ size_t gguf_get_tensor_size(const struct gguf_context * ctx, int64_t tensor_id) {
913
+ GGML_ASSERT(tensor_id >= 0 && tensor_id < gguf_get_n_tensors(ctx));
914
+ return ggml_nbytes(&ctx->info[tensor_id].t);
915
+ }
916
+
917
+ int64_t gguf_remove_key(struct gguf_context * ctx, const char * key) {
918
+ const int64_t key_id = gguf_find_key(ctx, key);
919
+ if (key_id >= 0) {
920
+ ctx->kv.erase(ctx->kv.begin() + key_id);
921
+ }
922
+ return key_id;
923
+ }
924
+
925
+ template<typename T>
926
+ static void gguf_check_reserved_keys(const std::string & key, const T val) {
927
+ if (key == GGUF_KEY_GENERAL_ALIGNMENT) {
928
+ if constexpr (std::is_same<T, uint32_t>::value) {
929
+ GGML_ASSERT(val > 0 && (val & (val - 1)) == 0 && GGUF_KEY_GENERAL_ALIGNMENT " must be power of 2");
930
+ } else {
931
+ GGML_ABORT(GGUF_KEY_GENERAL_ALIGNMENT " must be type u32");
932
+ }
933
+ }
934
+ }
935
+
936
+ void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
937
+ gguf_check_reserved_keys(key, val);
938
+ gguf_remove_key(ctx, key);
939
+ ctx->kv.emplace_back(key, val);
940
+ }
941
+
942
+ void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
943
+ gguf_check_reserved_keys(key, val);
944
+ gguf_remove_key(ctx, key);
945
+ ctx->kv.emplace_back(key, val);
946
+ }
947
+
948
+ void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
949
+ gguf_check_reserved_keys(key, val);
950
+ gguf_remove_key(ctx, key);
951
+ ctx->kv.emplace_back(key, val);
952
+ }
953
+
954
+ void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
955
+ gguf_check_reserved_keys(key, val);
956
+ gguf_remove_key(ctx, key);
957
+ ctx->kv.emplace_back(key, val);
958
+ }
959
+
960
+ void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
961
+ gguf_check_reserved_keys(key, val);
962
+ gguf_remove_key(ctx, key);
963
+ ctx->kv.emplace_back(key, val);
964
+ }
965
+
966
+ void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
967
+ gguf_check_reserved_keys(key, val);
968
+ gguf_remove_key(ctx, key);
969
+ ctx->kv.emplace_back(key, val);
970
+ }
971
+
972
+ void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
973
+ gguf_check_reserved_keys(key, val);
974
+ gguf_remove_key(ctx, key);
975
+ ctx->kv.emplace_back(key, val);
976
+ }
977
+
978
+ void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
979
+ gguf_check_reserved_keys(key, val);
980
+ gguf_remove_key(ctx, key);
981
+ ctx->kv.emplace_back(key, val);
982
+ }
983
+
984
+ void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
985
+ gguf_check_reserved_keys(key, val);
986
+ gguf_remove_key(ctx, key);
987
+ ctx->kv.emplace_back(key, val);
988
+ }
989
+
990
+ void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
991
+ gguf_check_reserved_keys(key, val);
992
+ gguf_remove_key(ctx, key);
993
+ ctx->kv.emplace_back(key, val);
994
+ }
995
+
996
+ void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
997
+ gguf_check_reserved_keys(key, val);
998
+ gguf_remove_key(ctx, key);
999
+ ctx->kv.emplace_back(key, val);
1000
+ }
1001
+
1002
+ void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
1003
+ gguf_check_reserved_keys(key, val);
1004
+ gguf_remove_key(ctx, key);
1005
+ ctx->kv.emplace_back(key, std::string(val));
1006
+ }
1007
+
1008
+ void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n) {
1009
+ gguf_check_reserved_keys(key, data);
1010
+ gguf_remove_key(ctx, key);
1011
+
1012
+ const size_t nbytes = n*gguf_type_size(type);
1013
+ std::vector<int8_t> tmp(nbytes);
1014
+ if (!tmp.empty()) {
1015
+ memcpy(tmp.data(), data, nbytes);
1016
+ }
1017
+ ctx->kv.emplace_back(key, tmp);
1018
+ ctx->kv.back().cast(type);
1019
+ }
1020
+
1021
+ void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, size_t n) {
1022
+ gguf_check_reserved_keys(key, data);
1023
+ gguf_remove_key(ctx, key);
1024
+
1025
+ std::vector<std::string> tmp(n);
1026
+ for (size_t i = 0; i < n; ++i) {
1027
+ tmp[i] = data[i];
1028
+ }
1029
+ ctx->kv.emplace_back(key, tmp);
1030
+ }
1031
+
1032
+ // set or add KV pairs from another context
1033
+ void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src) {
1034
+ const int64_t n_kv = gguf_get_n_kv(src);
1035
+ for (int64_t i = 0; i < n_kv; ++i) {
1036
+ const struct gguf_kv & kv = src->kv[i];
1037
+
1038
+ if (!kv.is_array) {
1039
+ switch (kv.get_type()) {
1040
+ case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, kv.get_key().c_str(), kv.get_val<uint8_t>()); break;
1041
+ case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, kv.get_key().c_str(), kv.get_val<int8_t>()); break;
1042
+ case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, kv.get_key().c_str(), kv.get_val<uint16_t>()); break;
1043
+ case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, kv.get_key().c_str(), kv.get_val<int16_t>()); break;
1044
+ case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, kv.get_key().c_str(), kv.get_val<uint32_t>()); break;
1045
+ case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, kv.get_key().c_str(), kv.get_val<int32_t>()); break;
1046
+ case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, kv.get_key().c_str(), kv.get_val<float>()); break;
1047
+ case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, kv.get_key().c_str(), kv.get_val<uint64_t>()); break;
1048
+ case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, kv.get_key().c_str(), kv.get_val<int64_t>()); break;
1049
+ case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, kv.get_key().c_str(), kv.get_val<double>()); break;
1050
+ case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, kv.get_key().c_str(), kv.get_val<bool>()); break;
1051
+ case GGUF_TYPE_STRING: gguf_set_val_str (ctx, kv.get_key().c_str(), kv.get_val<std::string>().c_str()); break;
1052
+ case GGUF_TYPE_ARRAY:
1053
+ default: GGML_ABORT("invalid type");
1054
+ }
1055
+ continue;
1056
+ }
1057
+
1058
+ const size_t ne = kv.get_ne();
1059
+
1060
+ switch (kv.get_type()) {
1061
+ case GGUF_TYPE_UINT8:
1062
+ case GGUF_TYPE_INT8:
1063
+ case GGUF_TYPE_UINT16:
1064
+ case GGUF_TYPE_INT16:
1065
+ case GGUF_TYPE_UINT32:
1066
+ case GGUF_TYPE_INT32:
1067
+ case GGUF_TYPE_FLOAT32:
1068
+ case GGUF_TYPE_UINT64:
1069
+ case GGUF_TYPE_INT64:
1070
+ case GGUF_TYPE_FLOAT64:
1071
+ case GGUF_TYPE_BOOL: {
1072
+ gguf_set_arr_data(ctx, kv.get_key().c_str(), kv.get_type(), kv.data.data(), ne);
1073
+ } break;
1074
+ case GGUF_TYPE_STRING: {
1075
+ std::vector<const char *> tmp(ne);
1076
+ for (size_t j = 0; j < ne; ++j) {
1077
+ tmp[j] = kv.data_string[j].c_str();
1078
+ }
1079
+ gguf_set_arr_str(ctx, kv.get_key().c_str(), tmp.data(), ne);
1080
+ } break;
1081
+ case GGUF_TYPE_ARRAY:
1082
+ default: GGML_ABORT("invalid type");
1083
+ }
1084
+ }
1085
+ }
1086
+
1087
+ void gguf_add_tensor(
1088
+ struct gguf_context * ctx,
1089
+ const struct ggml_tensor * tensor) {
1090
+ GGML_ASSERT(tensor);
1091
+ if (gguf_find_tensor(ctx, tensor->name) != -1) {
1092
+ GGML_ABORT("duplicate tensor name: %s", tensor->name);
1093
+ }
1094
+
1095
+ struct gguf_tensor_info ti;
1096
+ ti.t = *tensor;
1097
+ ti.offset = ctx->info.empty() ? 0 :
1098
+ ctx->info.back().offset + GGML_PAD(ggml_nbytes(&ctx->info.back().t), ctx->alignment);
1099
+ ctx->info.push_back(ti);
1100
+ }
1101
+
1102
+ void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
1103
+ const int64_t tensor_id = gguf_find_tensor(ctx, name);
1104
+ if (tensor_id < 0) {
1105
+ GGML_ABORT("tensor not found: %s", name);
1106
+ }
1107
+ struct ggml_tensor * tensor = &ctx->info[tensor_id].t;
1108
+ const size_t type_size = ggml_type_size(type);
1109
+ const int64_t blck_size = ggml_blck_size(type);
1110
+
1111
+ tensor->type = type;
1112
+ GGML_ASSERT(tensor->ne[0] % blck_size == 0 && "tensor row size not divisible by block size of new type");
1113
+
1114
+ tensor->nb[0] = type_size;
1115
+ tensor->nb[1] = tensor->nb[0]*(tensor->ne[0]/blck_size);
1116
+ for (int i = 2; i < GGML_MAX_DIMS; i++) {
1117
+ tensor->nb[i] = tensor->nb[i - 1]*tensor->ne[i - 1];
1118
+ }
1119
+
1120
+ // update offsets
1121
+ const int64_t n_tensors = gguf_get_n_tensors(ctx);
1122
+ for (int64_t i = tensor_id + 1; i < n_tensors; ++i) {
1123
+ ctx->info[i].offset = ctx->info[i - 1].offset + GGML_PAD(ggml_nbytes(&ctx->info[i - 1].t), ctx->alignment);
1124
+ }
1125
+ }
1126
+
1127
+ void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data) {
1128
+ const int64_t tensor_id = gguf_find_tensor(ctx, name);
1129
+ if (tensor_id < 0) {
1130
+ GGML_ABORT("tensor not found: %s", name);
1131
+ }
1132
+
1133
+ ctx->info[tensor_id].t.data = (void *)(uintptr_t)data; // double cast suppresses warning about casting away const
1134
+ }
1135
+
1136
+ struct gguf_writer {
1137
+ std::vector<int8_t> & buf;
1138
+
1139
+ gguf_writer(std::vector<int8_t> & buf) : buf(buf) {}
1140
+
1141
+ template <typename T>
1142
+ void write(const T & val) const {
1143
+ for (size_t i = 0; i < sizeof(val); ++i) {
1144
+ buf.push_back(reinterpret_cast<const int8_t *>(&val)[i]);
1145
+ }
1146
+ }
1147
+
1148
+ void write(const std::vector<int8_t> & val) const {
1149
+ buf.insert(buf.end(), val.begin(), val.end());
1150
+ }
1151
+
1152
+ void write(const bool & val) const {
1153
+ const int8_t val8 = val ? 1 : 0;
1154
+ write(val8);
1155
+ }
1156
+
1157
+ void write(const std::string & val) const {
1158
+ {
1159
+ const uint64_t n = val.length();
1160
+ write(n);
1161
+ }
1162
+ for (size_t i = 0; i < val.length(); ++i) {
1163
+ buf.push_back(reinterpret_cast<const int8_t *>(val.data())[i]);
1164
+ }
1165
+ }
1166
+
1167
+ void write(const char * val) const {
1168
+ write(std::string(val));
1169
+ }
1170
+
1171
+ void write(const enum ggml_type & val) const {
1172
+ write(int32_t(val));
1173
+ }
1174
+
1175
+ void write(const enum gguf_type & val) const {
1176
+ write(int32_t(val));
1177
+ }
1178
+
1179
+ void write(const struct gguf_kv & kv) const {
1180
+ const uint64_t ne = kv.get_ne();
1181
+
1182
+ write(kv.get_key());
1183
+
1184
+ if (kv.is_array) {
1185
+ write(GGUF_TYPE_ARRAY);
1186
+ write(kv.get_type());
1187
+ write(ne);
1188
+ } else {
1189
+ write(kv.get_type());
1190
+ }
1191
+
1192
+ switch (kv.get_type()) {
1193
+ case GGUF_TYPE_UINT8:
1194
+ case GGUF_TYPE_INT8:
1195
+ case GGUF_TYPE_UINT16:
1196
+ case GGUF_TYPE_INT16:
1197
+ case GGUF_TYPE_UINT32:
1198
+ case GGUF_TYPE_INT32:
1199
+ case GGUF_TYPE_FLOAT32:
1200
+ case GGUF_TYPE_UINT64:
1201
+ case GGUF_TYPE_INT64:
1202
+ case GGUF_TYPE_FLOAT64: {
1203
+ write(kv.data);
1204
+ } break;
1205
+ case GGUF_TYPE_BOOL: {
1206
+ for (size_t i = 0; i < ne; ++i) {
1207
+ write(kv.get_val<bool>(i));
1208
+ }
1209
+ } break;
1210
+ case GGUF_TYPE_STRING: {
1211
+ for (size_t i = 0; i < ne; ++i) {
1212
+ write(kv.get_val<std::string>(i));
1213
+ }
1214
+ } break;
1215
+ case GGUF_TYPE_ARRAY:
1216
+ default: GGML_ABORT("invalid type");
1217
+ }
1218
+ }
1219
+
1220
+ void write_tensor_meta(const struct gguf_tensor_info & info) const {
1221
+ write(info.t.name);
1222
+
1223
+ const uint32_t n_dims = ggml_n_dims(&info.t);
1224
+ write(n_dims);
1225
+
1226
+ for (uint32_t j = 0; j < n_dims; ++j) {
1227
+ write(info.t.ne[j]);
1228
+ }
1229
+ write(info.t.type);
1230
+ write(info.offset);
1231
+ }
1232
+
1233
+ void pad(const size_t alignment) const {
1234
+ while (buf.size() % alignment != 0) {
1235
+ const int8_t zero = 0;
1236
+ write(zero);
1237
+ }
1238
+ }
1239
+
1240
+ void write_tensor_data(const struct gguf_tensor_info & info, const size_t offset_data, const size_t alignment) const {
1241
+ GGML_ASSERT(buf.size() - offset_data == info.offset);
1242
+
1243
+ GGML_ASSERT(ggml_is_contiguous(&info.t));
1244
+ const size_t offset = buf.size();
1245
+ const size_t nbytes = ggml_nbytes(&info.t);
1246
+
1247
+ buf.resize(offset + nbytes);
1248
+ if (info.t.buffer) {
1249
+ ggml_backend_tensor_get(&info.t, buf.data() + offset, 0, nbytes);
1250
+ } else {
1251
+ GGML_ASSERT(info.t.data);
1252
+ memcpy(buf.data() + offset, info.t.data, nbytes);
1253
+ }
1254
+
1255
+ pad(alignment);
1256
+ }
1257
+ };
1258
+
1259
+ void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta) {
1260
+ const struct gguf_writer gw(buf);
1261
+
1262
+ const int64_t n_kv = gguf_get_n_kv(ctx);
1263
+ const int64_t n_tensors = gguf_get_n_tensors(ctx);
1264
+
1265
+ // write header
1266
+ gw.write(GGUF_MAGIC[0]);
1267
+ gw.write(GGUF_MAGIC[1]);
1268
+ gw.write(GGUF_MAGIC[2]);
1269
+ gw.write(GGUF_MAGIC[3]);
1270
+ gw.write(ctx->version);
1271
+ gw.write(n_tensors);
1272
+ gw.write(n_kv);
1273
+
1274
+ // write key-value pairs
1275
+ for (int64_t i = 0; i < n_kv; ++i) {
1276
+ gw.write(ctx->kv[i]);
1277
+ }
1278
+
1279
+ // write tensor info
1280
+ for (int64_t i = 0; i < n_tensors; ++i) {
1281
+ gw.write_tensor_meta(ctx->info[i]);
1282
+ }
1283
+
1284
+ // we require the data section to be aligned
1285
+ gw.pad(ctx->alignment);
1286
+
1287
+ if (only_meta) {
1288
+ return;
1289
+ }
1290
+
1291
+ const size_t offset_data = gw.buf.size();
1292
+
1293
+ // write tensor data
1294
+ for (int64_t i = 0; i < n_tensors; ++i) {
1295
+ gw.write_tensor_data(ctx->info[i], offset_data, ctx->alignment);
1296
+ }
1297
+ }
1298
+
1299
+ bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
1300
+ FILE * file = ggml_fopen(fname, "wb");
1301
+
1302
+ if (!file) {
1303
+ fprintf(stderr, "%s: failed to open file '%s' for writing GGUF data\n", __func__, fname);
1304
+ return false;
1305
+ }
1306
+
1307
+ std::vector<int8_t> buf;
1308
+ gguf_write_to_buf(ctx, buf, only_meta);
1309
+ const bool ok = fwrite(buf.data(), 1, buf.size(), file) == buf.size();
1310
+ fclose(file);
1311
+ return ok;
1312
+ }
1313
+
1314
+ size_t gguf_get_meta_size(const struct gguf_context * ctx) {
1315
+ // only return size
1316
+ std::vector<int8_t> buf;
1317
+ gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
1318
+ return buf.size();
1319
+ }
1320
+
1321
+ void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
1322
+ std::vector<int8_t> buf;
1323
+ gguf_write_to_buf(ctx, buf, /*only_meta =*/ true);
1324
+ memcpy(data, buf.data(), buf.size());
1325
+ }