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