gguf.cpp 45 KB

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