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